Skip to content

Commit

Permalink
Merge branch 'SV-27/logger-inferface' into SV-37/logging-controllers
Browse files Browse the repository at this point in the history
  • Loading branch information
MarijusCoding authored Oct 8, 2024
2 parents f15c4fa + 848d702 commit 24aa0a1
Show file tree
Hide file tree
Showing 8 changed files with 174 additions and 50 deletions.
110 changes: 104 additions & 6 deletions controllers/front/return.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@
use Invertus\SaferPay\Api\Enum\TransactionStatus;
use Invertus\SaferPay\Config\SaferPayConfig;
use Invertus\SaferPay\Controller\AbstractSaferPayController;
use Invertus\SaferPay\Core\Payment\DTO\CheckoutData;
use Invertus\SaferPay\DTO\Response\Assert\AssertBody;
use Invertus\SaferPay\Enum\ControllerName;
use Invertus\SaferPay\Exception\Api\SaferPayApiException;
use Invertus\SaferPay\Logger\LoggerInterface;
use Invertus\SaferPay\Processor\CheckoutProcessor;
use Invertus\SaferPay\Service\SaferPayOrderStatusService;
use Invertus\SaferPay\Service\TransactionFlow\SaferPayTransactionAssertion;
use Invertus\SaferPay\Service\TransactionFlow\SaferPayTransactionAuthorization;
Expand All @@ -50,19 +52,96 @@ public function postProcess()

$cartId = (int) Tools::getValue('cartId');
$order = new Order($this->getOrderId($cartId));
$secureKey = Tools::getValue('secureKey');
$cart = new Cart($cartId);

if (!$order->id) {
return;
if (!Validate::isLoadedObject($cart)) {
$this->warning[] = $this->module->l('An unknown error error occurred. Please contact support', self::FILENAME);
$this->redirectWithNotifications($this->getRedirectionToControllerUrl('fail'));
}

if ($cart->secure_key !== $secureKey) {
$this->warning[] = $this->module->l('Error. Insecure cart', self::FILENAME);
$this->redirectWithNotifications($this->getRedirectionToControllerUrl('fail'));
}

/** @var SaferPayTransactionAssertion $transactionAssert */
$transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class);

try {
/** @var SaferPayTransactionAssertion $transactionAssert */
$transactionAssert = $this->module->getService(SaferPayTransactionAssertion::class);
$transactionResponse = $transactionAssert->assert($cartId, false);
$assertResponseBody = $transactionAssert->assert($cartId);
$transactionStatus = $assertResponseBody->getTransaction()->getStatus();
} catch (Exception $e) {
\PrestaShopLogger::addLog($e->getMessage());
$this->warning[] = $this->module->l('An error occurred. Please contact support', self::FILENAME);
$this->redirectWithNotifications($this->getRedirectionToControllerUrl('fail'));
}

/**
* NOTE: This flow is for hosted iframe payment method
*/
if (Tools::getValue('isBusinessLicence')) {
try {
/** @var CheckoutProcessor $checkoutProcessor * */
$checkoutProcessor = $this->module->getService(CheckoutProcessor::class);

$checkoutData = CheckoutData::create(
(int) $cartId,
$assertResponseBody->getPaymentMeans()->getBrand()->getPaymentMethod(),
(int) Configuration::get(SaferPayConfig::IS_BUSINESS_LICENCE)
);
$checkoutData->setOrderStatus($transactionStatus);

$checkoutProcessor->run($checkoutData);

$orderId = $this->getOrderId($cartId);

$order = new Order($orderId);
if (!$assertResponseBody->getLiability()->getLiabilityShift() &&
in_array($order->payment, SaferPayConfig::SUPPORTED_3DS_PAYMENT_METHODS) &&
(int) Configuration::get(SaferPayConfig::PAYMENT_BEHAVIOR_WITHOUT_3D) === SaferPayConfig::PAYMENT_BEHAVIOR_WITHOUT_3D_CANCEL
) {
/** @var SaferPayOrderStatusService $orderStatusService */
$orderStatusService = $this->module->getService(SaferPayOrderStatusService::class);
$orderStatusService->cancel($order);
}

//NOTE to get latest information possible and not override new information.

$paymentMethod = $assertResponseBody->getPaymentMeans()->getBrand()->getPaymentMethod();// if payment does not support order capture, it means it always auto-captures it (at least with accountToAccount payment),

// so in this case if status comes back "captured" we just update the order state accordingly
if (!SaferPayConfig::supportsOrderCapture($paymentMethod) &&
$transactionStatus === TransactionStatus::CAPTURED
) {
/** @var SaferPayOrderStatusService $orderStatusService */
$orderStatusService = $this->module->getService(SaferPayOrderStatusService::class);
$orderStatusService->setComplete($order);

return;
}

if (SaferPayConfig::supportsOrderCapture($paymentMethod) &&
(int) Configuration::get(SaferPayConfig::PAYMENT_BEHAVIOR) === SaferPayConfig::DEFAULT_PAYMENT_BEHAVIOR_CAPTURE &&
$transactionStatus !== TransactionStatus::CAPTURED
) {
/** @var SaferPayOrderStatusService $orderStatusService */
$orderStatusService = $this->module->getService(SaferPayOrderStatusService::class);
$orderStatusService->capture($order);

return;
}
} catch (Exception $e) {
\PrestaShopLogger::addLog($e->getMessage());
$this->warning[] = $this->module->l('An error occurred. Please contact support', self::FILENAME);
$this->redirectWithNotifications($this->getRedirectionToControllerUrl('fail'));
}
}

try {
/** @var SaferPayOrderStatusService $orderStatusService */
$orderStatusService = $this->module->getService(SaferPayOrderStatusService::class);
if ($transactionResponse->getTransaction()->getStatus() === TransactionStatus::PENDING) {
if ($assertResponseBody->getTransaction()->getStatus() === TransactionStatus::PENDING) {
$orderStatusService->setPending($order);
}
} catch (SaferPayApiException $e) {
Expand Down Expand Up @@ -214,4 +293,23 @@ private function getOrderId($cartId)
// For PrestaShop 1.6 use the alternative method
return Order::getOrderByCartId($cartId);
}

/**
* @param string $controllerName
*
* @return string
*/
private function getRedirectionToControllerUrl($controllerName)
{
return $this->context->link->getModuleLink(
$this->module->name,
$controllerName,
[
'cartId' => $this->context->cart->id,
'orderId' => Order::getOrderByCartId($this->context->cart->id),
'secureKey' => $this->context->cart->secure_key,
'moduleId' => $this->module->id,
]
);
}
}
26 changes: 18 additions & 8 deletions saferpayofficial.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ public function hookPaymentOptions($params)
/** @var Invertus\SaferPay\Service\SaferPayCartService $assertService */
$cartService = $this->getService(\Invertus\SaferPay\Service\SaferPayCartService::class);
if (!$cartService->isCurrencyAvailable($params['cart'])) {
return;
return [];
}

/** @var \Invertus\SaferPay\Provider\PaymentTypeProvider $paymentTypeProvider */
Expand All @@ -206,15 +206,29 @@ public function hookPaymentOptions($params)
\Invertus\SaferPay\Service\PaymentRestrictionValidation::class
);

$logosEnabled = $paymentRepository->getAllActiveLogosNames();
$logosEnabled = array_column($logosEnabled, 'name');

$activePaymentMethods = $paymentRepository->getActivePaymentMethodsNames();
$activePaymentMethods = array_column($activePaymentMethods, 'name');


foreach ($paymentMethods as $paymentMethod) {
$paymentMethod['paymentMethod'] = str_replace(' ', '', $paymentMethod['paymentMethod']);

if (!in_array($paymentMethod['paymentMethod'], $activePaymentMethods)) {
continue;
}

if (!in_array($this->context->currency->iso_code, $paymentMethods[$paymentMethod['paymentMethod']]['currencies'])) {
continue;
}

if (!$paymentRestrictionValidation->isPaymentMethodValid($paymentMethod['paymentMethod'])) {
continue;
}

$imageUrl = ($paymentRepository->isLogoEnabledByName($paymentMethod['paymentMethod']))
$imageUrl = (in_array($paymentMethod['paymentMethod'], $logosEnabled))
? $paymentMethod['logoUrl'] : '';

$isCreditCard = in_array(
Expand Down Expand Up @@ -365,14 +379,10 @@ public function hookDisplayCustomerAccount()
return;
}
if (\Invertus\SaferPay\Config\SaferPayConfig::isVersion17()) {
return $this->context->smarty->fetch(
$this->getLocalPath() . 'views/templates/hook/front/MyAccount.tpl'
);
return $this->display(__FILE__, 'front/MyAccount.tpl');
}

return $this->context->smarty->fetch(
$this->getLocalPath() . 'views/templates/hook/front/MyAccount_16.tpl'
);
return $this->display(__FILE__, 'front/MyAccount_16.tpl');
}

public function displayNavigationTop()
Expand Down
9 changes: 6 additions & 3 deletions src/DTO/Request/Initialize/InitializeRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,14 @@ public function getAsArray()
'AddressSource' => $this->deliveryAddressForm->getAddressSource(),
'MandatoryFields' => $this->deliveryAddressForm->getMandatoryFields(),
],
'CardForm' => [
'HolderName' => SaferPayConfig::SAFERPAY_CARDFORM_HOLDERNAME_REQUIRENCE,
],
];

if ($this->getPaymentMeansField() === []) {
$return['CardForm'] = [
'HolderName' => SaferPayConfig::SAFERPAY_CARDFORM_HOLDERNAME_REQUIRENCE,
];
}

if ($this->notification !== null) {
$return['Notification'] = [
'MerchantEmails' => [$this->notification->getMerchantEmail()],
Expand Down
40 changes: 39 additions & 1 deletion src/Repository/SaferPayPaymentRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,52 @@ public function isLogoEnabledByName($paymentName)
return Db::getInstance()->getValue($query);
}

public function getAllActiveLogosNames()
{
$query = new DbQuery();
$query->select('name');
$query->from('saferpay_logo');
$query->where('active = "1"');

$result = Db::getInstance()->executeS($query);

if (!$result) {
return [];
}

return $result;
}

public function getActivePaymentMethods()
{
$query = new DbQuery();
$query->select('*');
$query->from('saferpay_payment');
$query->where('active = "1"');

return Db::getInstance()->executeS($query);
$result = Db::getInstance()->executeS($query);

if (!$result) {
return [];
}

return $result;
}

public function getActivePaymentMethodsNames()
{
$query = new DbQuery();
$query->select('name');
$query->from('saferpay_payment');
$query->where('active = "1"');

$result = Db::getInstance()->executeS($query);

if (!$result) {
return [];
}

return $result;
}

public function truncateTable()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,10 @@ public function __construct(
*/
public function isValid($paymentName)
{
if (!$this->paymentRepository->isActiveByName($paymentName)) {
return false;
}

if (!$this->isCountrySupportedByPaymentName($paymentName)) {
return false;
}

if (!$this->isCurrencySupportedByPaymentName($paymentName)) {
return false;
}

return true;
}

Expand Down Expand Up @@ -135,26 +127,4 @@ private function isCountrySupportedByPaymentName($paymentName)

return $isCountryInList || $isAllCountries;
}

/**
* @param string $paymentName
*
* @return bool
*/
private function isCurrencySupportedByPaymentName($paymentName)
{
$enabledCurrencies = $this->getEnabledCurrenciesByPaymentName($paymentName);

if (in_array('0', $enabledCurrencies)) {
$enabledCurrencies = [];
$currencyOptions = $this->obtainPaymentMethods->obtainPaymentMethods()[$paymentName]['currencies'];
foreach ($currencyOptions as $isoCode) {
$enabledCurrencies[$isoCode] = $isoCode;
}

return in_array($this->legacyContext->getCurrencyIsoCode(), $enabledCurrencies);
}

return in_array($this->legacyContext->getCurrencyId(), $enabledCurrencies);
}
}
5 changes: 5 additions & 0 deletions src/Service/SaferPayOrderStatusService.php
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,11 @@ public function cancel(Order $order)
$order->update();
$saferPayOrder->canceled = 1;
$saferPayOrder->update();

$assertId = $this->orderRepository->getAssertIdBySaferPayOrderId($saferPayOrder->id);
$saferPayAssert = new SaferPayAssert($assertId);
$saferPayAssert->status = TransactionStatus::CANCELED;
$saferPayAssert->update();
}

public function refund(Order $order, $refundedAmount)
Expand Down
2 changes: 1 addition & 1 deletion views/templates/front/credit_cards.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
</tr>
</thead>
{foreach $rows as $row}
{$row nofilter|escape:'htmlall':'UTF-8'}
{$row|escape:'htmlall':'UTF-8'|nofilter}
{/foreach}
</table>
</div>
Expand Down
2 changes: 1 addition & 1 deletion views/templates/front/credit_cards_16.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
</tr>
</thead>
{foreach $rows as $row}
{$row nofilter|escape:'htmlall':'UTF-8'}
{$row|escape:'htmlall':'UTF-8'|nofilter}
{/foreach}
</table>
</div>

0 comments on commit 24aa0a1

Please sign in to comment.