From 38ab49f628c96bd556970a89ff729ae14cc7df62 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Thu, 25 Aug 2022 15:32:48 +0500 Subject: [PATCH 01/31] Support catalog discount in combination to cart discount --- CHANGELOG.md | 5 ++++ Model/Generator.php | 10 ++++---- Model/Handler/DiscountHandler.php | 42 +++++++++++++++++++++++++------ Model/Handler/PriceHandler.php | 7 +++++- 4 files changed, 51 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d9019b2b..f499b535 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ # Changelog All notable changes to this project will be documented in this file. +## [3.0.0] +**Improvements** +- Add support when cart and catalog rules are applied simultaneously +- Make text "No saved credit cards" translatable + ## [2.0.5] **Fixes** - Resolve compilation issue for Magento 2.1.9 and below diff --git a/Model/Generator.php b/Model/Generator.php index 4513c58e..2e71a21d 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -194,7 +194,7 @@ public function createRequest($terminalId, $orderId) if ($order->getId()) { $couponCode = $order->getDiscountDescription(); $couponCodeAmount = $order->getDiscountAmount(); - $discountAllItems = $this->discountHandler->allItemsHaveDiscount($order->getAllVisibleItems()); + $discountAllItems = $this->discountHandler->allItemsHaveDiscount($order->getAllItems()); $orderLines = $this->itemOrderLines($couponCodeAmount, $order, $discountAllItems); if ($this->orderLines->sendShipment($order) && !empty($order->getShippingMethod(true))) { $orderLines[] = $this->orderLines->handleShipping($order, $discountAllItems, true); @@ -543,7 +543,6 @@ public function fixedProductTax($order) private function itemOrderLines($couponCodeAmount, $order, $discountAllItems) { $orderLines = []; - $couponCode = $order->getDiscountDescription(); $storePriceIncTax = $this->storeConfig->storePriceIncTax(); foreach ($order->getAllItems() as $item) { @@ -570,16 +569,17 @@ private function itemOrderLines($couponCodeAmount, $order, $discountAllItems) $dataForPrice = $this->priceHandler->dataForPrice( $item, $unitPrice, - $couponCode, + $couponCodeAmount, $this->discountHandler->getItemDiscount($discountAmount, $productOriginalPrice, $item->getQtyOrdered()) ); $taxAmount = $dataForPrice["taxAmount"]; + $catalogDiscount = $dataForPrice["catalogDiscount"]; $discount = $this->discountHandler->orderLineDiscount( $discountAllItems, - $dataForPrice["discount"] + $dataForPrice["discount"], + $catalogDiscount ); - $catalogDiscount = $dataForPrice["catalogDiscount"]; $itemTaxAmount = $taxAmount; $orderLines[] = $this->orderLines->itemOrderLine( $item, diff --git a/Model/Handler/DiscountHandler.php b/Model/Handler/DiscountHandler.php index e567e2a5..2b38281f 100644 --- a/Model/Handler/DiscountHandler.php +++ b/Model/Handler/DiscountHandler.php @@ -90,15 +90,31 @@ public function getAppliedDiscounts($item) * * @return int|string */ - public function orderLineDiscount($discountOnAllItems, $discount) + public function orderLineDiscount($discountOnAllItems, $discount, $catalogDiscount) { - if ($discountOnAllItems) { + if ($discountOnAllItems && !$catalogDiscount) { $discount = 0; } return number_format($discount, 2, '.', ''); } + /** + * Calculate combination of cart and catalog price rule. + * + * @param $originalPrice + * @param $rowTotal + * + * @return float|int + */ + public function combinationDiscount($originalPrice, $rowTotal) + { + $discountAmount = $originalPrice - $rowTotal; + $discountPercentage = ($discountAmount / $originalPrice) * 100; + + return number_format($discountPercentage, 2, '.', ''); + } + /** * Get discount applied to shipping. * @@ -161,10 +177,13 @@ public function getItemDiscountInformation( if (!empty($discountAmount)) { $discountAmount = ($discountAmount * 100) / ($originalPrice * $quantity); } elseif ($originalPrice > 0 && $originalPrice > $discountedPrice) { - $discount['catalog'] = true; + $discount['catalogDiscount'] = true; $discountAmount = $this->catalogDiscount($originalPrice, $discountedPrice); + } elseif ($originalPrice > 0 && $originalPrice > $discountedPrice && !empty($discountAmount)) { + $discount['catalogDiscount'] = true; + $discountAmount = $this->combinationDiscount($originalPrice, $discountedPrice); } - $discount['discount'] = $this->orderLineDiscount($discountOnAllItems, $discountAmount); + $discount['discount'] = $this->orderLineDiscount($discountOnAllItems, $discountAmount, $discount['catalogDiscount']); return $discount; } @@ -180,9 +199,18 @@ public function allItemsHaveDiscount($orderItems) { $discountOnAllItems = true; foreach ($orderItems as $item) { - $appliedRule = $item->getAppliedRuleIds(); - $productType = $item->getProductType(); - if (!empty($appliedRule)) { + $appliedRule = $item->getAppliedRuleIds(); + $productType = $item->getProductType(); + $originalPrice = $item->getBaseOriginalPrice(); + + if ($this->storeConfig->storePriceIncTax()) { + $price = $item->getPriceInclTax(); + } else { + $price = $item->getPrice(); + } + if ($originalPrice > $price) { + $discountOnAllItems = false; + } elseif (!empty($appliedRule)) { $appliedRuleArr = explode(",", $appliedRule); foreach ($appliedRuleArr as $ruleId) { $coupon = $this->storeConfig->getRuleInformationByID($ruleId); diff --git a/Model/Handler/PriceHandler.php b/Model/Handler/PriceHandler.php index c6fea3d5..6926988b 100644 --- a/Model/Handler/PriceHandler.php +++ b/Model/Handler/PriceHandler.php @@ -55,15 +55,20 @@ public function dataForPrice($item, $unitPrice, $couponCode, $itemDiscount) $taxPercent = $item->getTaxPercent(); $quantity = $item->getQtyOrdered(); $originalPrice = $item->getBaseOriginalPrice(); + $data["taxAmount"] = $this->calculateTaxAmount($unitPrice, $taxPercent, $quantity); + $rowTotal = ($item->getRowTotal()-$item->getDiscountAmount()+$item->getTaxAmount()+$item->getDiscountTaxCompensationAmount()); if ($this->storeConfig->storePriceIncTax()) { $price = $item->getPriceInclTax(); } else { $price = $item->getPrice(); } - $data["taxAmount"] = $this->calculateTaxAmount($unitPrice, $taxPercent, $quantity); if ($originalPrice > $price && empty($couponCode)) { $data["catalogDiscount"] = true; $data["discount"] = $this->discountHandler->catalogDiscount($originalPrice, $price); + } elseif ($originalPrice > $price && !empty($couponCode)) { + $originalPrice = $originalPrice * $quantity; + $data["catalogDiscount"] = true; + $data["discount"] = $this->discountHandler->combinationDiscount($originalPrice, $rowTotal); } else { $data["discount"] = $itemDiscount; } From d9eef09acc078fbf9b6fb407da1747b6873b80d2 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Thu, 25 Aug 2022 16:44:30 +0500 Subject: [PATCH 02/31] Cancel order issues when there is no transaction and code formatting --- Block/Callback/Redirect.php | 1 + Block/Callback/Verify.php | 2 + CHANGELOG.md | 3 ++ Controller/Customer/Index.php | 8 +++- Controller/Index/Failmessage.php | 2 +- Controller/Index/Request.php | 11 ++--- Helper/Data.php | 7 +-- Logger/Handler.php | 26 +++++++++++ Logger/Logger.php | 78 ++++++++++++++++++++++++++++++++ Observer/OrderCancelObserver.php | 2 +- 10 files changed, 127 insertions(+), 13 deletions(-) create mode 100755 Logger/Handler.php create mode 100755 Logger/Logger.php diff --git a/Block/Callback/Redirect.php b/Block/Callback/Redirect.php index ff8c9643..aaaafa32 100755 --- a/Block/Callback/Redirect.php +++ b/Block/Callback/Redirect.php @@ -15,5 +15,6 @@ class Redirect extends Template { protected function _prepareLayout() { + return $this; } } diff --git a/Block/Callback/Verify.php b/Block/Callback/Verify.php index 6b7e560c..3dfdf10e 100755 --- a/Block/Callback/Verify.php +++ b/Block/Callback/Verify.php @@ -16,5 +16,7 @@ class Verify extends Template protected function _prepareLayout() { $this->setMessage(__('OKAY')); + + return $this; } } diff --git a/CHANGELOG.md b/CHANGELOG.md index f499b535..7c0080a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ All notable changes to this project will be documented in this file. - Add support when cart and catalog rules are applied simultaneously - Make text "No saved credit cards" translatable +**Fixes** +- Cancel order issues when there is no transaction + ## [2.0.5] **Fixes** - Resolve compilation issue for Magento 2.1.9 and below diff --git a/Controller/Customer/Index.php b/Controller/Customer/Index.php index 1d55fb2e..303a7250 100644 --- a/Controller/Customer/Index.php +++ b/Controller/Customer/Index.php @@ -38,6 +38,12 @@ public function __construct( parent::__construct($context); } + /** + * Dispatch request + * + * @return \Magento\Framework\Controller\ResultInterface|ResponseInterface|void + * @throws \Magento\Framework\Exception\NotFoundException + */ public function execute() { $action = $this->getRequest()->getParam('action'); @@ -80,7 +86,7 @@ public function execute() $model->setPrimary(0)->save(); } $response = ['status' => 'updated']; - } catch (Exception $e) { + } catch (\Exception $e) { $response = ['status' => 'error']; } } diff --git a/Controller/Index/Failmessage.php b/Controller/Index/Failmessage.php index 54547be5..8a48dfb7 100755 --- a/Controller/Index/Failmessage.php +++ b/Controller/Index/Failmessage.php @@ -28,7 +28,7 @@ public function execute() { $this->writeLog(); $msg = $this->getRequest()->getParam('msg'); - $this->logger->debug('messageManager - Error message: ' . $msg); + $this->altapayLogger->addDebugLog('messageManager - Error message', $msg); $this->messageManager->addErrorMessage($msg); return $this->_redirect('checkout', ['_fragment' => 'payment']); diff --git a/Controller/Index/Request.php b/Controller/Index/Request.php index 4a320d73..a53e37fa 100755 --- a/Controller/Index/Request.php +++ b/Controller/Index/Request.php @@ -26,21 +26,18 @@ class Request extends Index */ public function execute() { - $this->writeLog(); + $this->writeLog(); + $result = new DataObject(); + $response = $this->getResponse(); if ($this->checkPost()) { $params = $this->generator->createRequest( $this->getRequest()->getParam('paytype'), $this->getRequest()->getParam('orderid') ); - - $result = new DataObject(); - $response = $this->getResponse(); $result->addData($params); - - return $response->representJson($result->toJson()); } - die('No post!?'); + return $response->representJson($result->toJson()); } } diff --git a/Helper/Data.php b/Helper/Data.php index a9bdc415..e5a961fe 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -76,20 +76,21 @@ public function __construct( */ public function transactionDetail($orderId) { - $order = $this->order->load($orderId); + $versionDetails = []; + $order = $this->order->load($orderId); if ($order->getId()) { $storeName = $order->getStore()->getName(); $websiteName = $order->getStore()->getWebsite()->getName(); $moduleInfo = $this->moduleList->getOne(self::MODULE_CODE); - $versionDetails = []; $versionDetails['ecomPlatform'] = 'Magento'; $versionDetails['ecomVersion'] = $this->productMetadata->getVersion(); $versionDetails['ecomPluginName'] = $moduleInfo['name']; $versionDetails['ecomPluginVersion'] = $moduleInfo['setup_version']; $versionDetails['otherInfo'] = 'websiteName - ' . $websiteName . ', storeName - ' . $storeName; - return $versionDetails; } + + return $versionDetails; } /** diff --git a/Logger/Handler.php b/Logger/Handler.php new file mode 100755 index 00000000..16c939a5 --- /dev/null +++ b/Logger/Handler.php @@ -0,0 +1,26 @@ +addInfo($type . ': ' . json_encode($data)); + } elseif (is_object($data)) { + $this->addInfo($type . ': ' . json_encode($data)); + } else { + $this->addInfo($type . ': ' . $data); + } + } + + /** + * @param $type + * @param $data + */ + public function addErrorLog($type, $data) + { + if (is_array($data)) { + $this->addError($type . ': ' . json_encode($data)); + } elseif (is_object($data)) { + $this->addError($type . ': ' . json_encode($data)); + } else { + $this->addError($type . ': ' . $data); + } + } + + /** + * @param $type + * @param $data + */ + public function addCriticalLog($type, $data) + { + if (is_array($data)) { + $this->addCritical($type . ': ' . json_encode($data)); + } elseif (is_object($data)) { + $this->addCritical($type . ': ' . json_encode($data)); + } else { + $this->addCritical($type . ': ' . $data); + } + } + + /** + * @param $type + * @param $data + */ + public function addDebugLog($type, $data) + { + if (is_array($data)) { + $this->addCritical($type . ': ' . json_encode($data)); + } elseif (is_object($data)) { + $this->addCritical($type . ': ' . json_encode($data)); + } else { + $this->addCritical($type . ': ' . $data); + } + } +} diff --git a/Observer/OrderCancelObserver.php b/Observer/OrderCancelObserver.php index 9f2fbebe..59869e29 100755 --- a/Observer/OrderCancelObserver.php +++ b/Observer/OrderCancelObserver.php @@ -49,7 +49,7 @@ public function execute(Observer $observer) /** @var Payment $payment */ $payment = $order->getPayment(); - if (in_array($payment->getMethod(), SystemConfig::getTerminalCodes())) { + if (in_array($payment->getMethod(), SystemConfig::getTerminalCodes()) && $payment->getLastTransId()) { $api = new ReleaseReservation($this->systemConfig->getAuth($order->getStore()->getCode())); $api->setTransaction($payment->getLastTransId()); /** @var ReleaseReservationResponse $response */ From 60fc8b0684eb8e81a0906374d5eaed9d72c56b93 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Thu, 25 Aug 2022 17:03:52 +0500 Subject: [PATCH 03/31] Order failing issue when applying a fixed discount on the cart --- CHANGELOG.md | 1 + Model/Generator.php | 7 ++++--- Model/Handler/DiscountHandler.php | 18 ++++++++++-------- Model/Handler/PriceHandler.php | 15 ++++++++------- Observer/CaptureObserver.php | 9 ++++++--- Observer/CreditmemoRefundObserver.php | 10 ++++++---- 6 files changed, 35 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c0080a2..f1f836ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project will be documented in this file. **Fixes** - Cancel order issues when there is no transaction +- Order failing issue when applying a fixed discount on the cart ## [2.0.5] **Fixes** diff --git a/Model/Generator.php b/Model/Generator.php index 2e71a21d..57f0b739 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -570,8 +570,8 @@ private function itemOrderLines($couponCodeAmount, $order, $discountAllItems) $item, $unitPrice, $couponCodeAmount, - $this->discountHandler->getItemDiscount($discountAmount, $productOriginalPrice, - $item->getQtyOrdered()) + $this->discountHandler->getItemDiscount($discountAmount, $originalPrice, $item->getQtyOrdered()), + $discountAllItems ); $taxAmount = $dataForPrice["taxAmount"]; $catalogDiscount = $dataForPrice["catalogDiscount"]; @@ -587,7 +587,8 @@ private function itemOrderLines($couponCodeAmount, $order, $discountAllItems) $discount, $itemTaxAmount, $order, - true + true, + $discountAllItems ); $roundingCompensation = $this->priceHandler->compensationAmountCal( $item, diff --git a/Model/Handler/DiscountHandler.php b/Model/Handler/DiscountHandler.php index 2b38281f..a73a45c9 100644 --- a/Model/Handler/DiscountHandler.php +++ b/Model/Handler/DiscountHandler.php @@ -159,7 +159,7 @@ public function catalogDiscount($originalPrice, $discountedPrice) /** * @param $originalPrice - * @param $discountedPrice + * @param $priceInclTax * @param $discountAmount * @param $quantity * @param $discountOnAllItems @@ -168,20 +168,22 @@ public function catalogDiscount($originalPrice, $discountedPrice) */ public function getItemDiscountInformation( $originalPrice, - $discountedPrice, + $priceInclTax, $discountAmount, $quantity, - $discountOnAllItems + $discountOnAllItems, + $item ) { + $rowTotal = $item->getRowTotal()-$item->getDiscountAmount()+$item->getTaxAmount()+$item->getDiscountTaxCompensationAmount(); $discount = ['discount' => 0, 'catalogDiscount' => false]; - if (!empty($discountAmount)) { + if ($discountAmount && $originalPrice == $priceInclTax) { $discountAmount = ($discountAmount * 100) / ($originalPrice * $quantity); - } elseif ($originalPrice > 0 && $originalPrice > $discountedPrice) { + } elseif ($originalPrice > 0 && $originalPrice > $priceInclTax && empty($discountAmount)) { $discount['catalogDiscount'] = true; - $discountAmount = $this->catalogDiscount($originalPrice, $discountedPrice); - } elseif ($originalPrice > 0 && $originalPrice > $discountedPrice && !empty($discountAmount)) { + $discountAmount = $this->catalogDiscount($originalPrice, $priceInclTax); + } elseif ($originalPrice > 0 && $originalPrice > $priceInclTax && $discountAmount) { $discount['catalogDiscount'] = true; - $discountAmount = $this->combinationDiscount($originalPrice, $discountedPrice); + $discountAmount = $this->combinationDiscount($originalPrice, $rowTotal); } $discount['discount'] = $this->orderLineDiscount($discountOnAllItems, $discountAmount, $discount['catalogDiscount']); diff --git a/Model/Handler/PriceHandler.php b/Model/Handler/PriceHandler.php index 6926988b..e5762a51 100644 --- a/Model/Handler/PriceHandler.php +++ b/Model/Handler/PriceHandler.php @@ -49,7 +49,7 @@ public function __construct( * * @return mixed */ - public function dataForPrice($item, $unitPrice, $couponCode, $itemDiscount) + public function dataForPrice($item, $unitPrice, $couponAmount, $itemDiscount, $discountAllItems) { $data["catalogDiscount"] = false; $taxPercent = $item->getTaxPercent(); @@ -62,10 +62,10 @@ public function dataForPrice($item, $unitPrice, $couponCode, $itemDiscount) } else { $price = $item->getPrice(); } - if ($originalPrice > $price && empty($couponCode)) { + if ($originalPrice > $price && !(float)$couponAmount) { $data["catalogDiscount"] = true; $data["discount"] = $this->discountHandler->catalogDiscount($originalPrice, $price); - } elseif ($originalPrice > $price && !empty($couponCode)) { + } elseif ($originalPrice > $price && abs((float)$couponAmount) > 0 && !$discountAllItems) { $originalPrice = $originalPrice * $quantity; $data["catalogDiscount"] = true; $data["discount"] = $this->discountHandler->combinationDiscount($originalPrice, $rowTotal); @@ -124,7 +124,8 @@ public function compensationAmountCal( $couponCodeAmount, $catalogDiscountCheck, $storePriceIncTax, - $newOrder + $newOrder, + $discountAllItems ) { if ($newOrder) { $quantity = $item->getQtyOrdered(); @@ -139,14 +140,14 @@ public function compensationAmountCal( $gatewaySubTotal = ($unitPrice * $quantity) + $taxAmount; $gatewaySubTotal = $gatewaySubTotal - ($gatewaySubTotal * ($discountedAmount / 100)); // Magento calculation pattern - if (abs($couponCodeAmount) > 0 && $storePriceIncTax) { + if (abs((float)$couponCodeAmount) > 0 && $storePriceIncTax && !$catalogDiscountCheck && $discountAllItems) { $cmsPriceCal = $unitPriceWithoutTax * $quantity; $cmsTaxCal = $cmsPriceCal * ($taxPercent / 100); $cmsSubTotal = $cmsPriceCal + $cmsTaxCal; $cmsSubTotal = $cmsSubTotal - ($cmsSubTotal * ($discountedAmount / 100)); $compensation = $cmsSubTotal - $gatewaySubTotal; - } elseif ($catalogDiscountCheck || empty($couponCodeAmount) || $couponCodeAmount == 0) { - $cmsSubTotal = $item->getBaseRowTotal() + $item->getBaseTaxAmount(); + } else { + $cmsSubTotal = $item->getRowTotal()-$item->getDiscountAmount()+$item->getTaxAmount()+$item->getDiscountTaxCompensationAmount(); $compensation = $cmsSubTotal - $gatewaySubTotal; } diff --git a/Observer/CaptureObserver.php b/Observer/CaptureObserver.php index 8ec8a5c8..032a2f89 100755 --- a/Observer/CaptureObserver.php +++ b/Observer/CaptureObserver.php @@ -167,6 +167,7 @@ private function itemOrderLines($couponCodeAmount, $invoice, $discountAllItems) if ($qty > 0 && $productType != 'bundle' && $item->getPriceInclTax()) { $discountAmount = $item->getDiscountAmount(); $originalPrice = $item->getOrderItem()->getOriginalPrice(); + $totalPrice = $originalPrice * $qty; if ($originalPrice == 0) { $originalPrice = $item->getPriceInclTax(); @@ -184,11 +185,12 @@ private function itemOrderLines($couponCodeAmount, $invoice, $discountAllItems) $taxAmount = $this->priceHandler->calculateTaxAmount($unitPrice, $taxPercent, $qty); } $itemDiscountInformation = $this->discountHandler->getItemDiscountInformation( - $originalPrice, + $$totalPrice, $price, $discountAmount, $qty, - $discountAllItems + $discountAllItems, + $item ); $discountedAmount = $itemDiscountInformation['discount']; $catalogDiscountCheck = $itemDiscountInformation['catalogDiscount']; @@ -198,7 +200,8 @@ private function itemOrderLines($couponCodeAmount, $invoice, $discountAllItems) $discountedAmount, $taxAmount, $invoice->getOrder(), - false + false, + $discountAllItems ); $roundingCompensation = $this->priceHandler->compensationAmountCal( $item, diff --git a/Observer/CreditmemoRefundObserver.php b/Observer/CreditmemoRefundObserver.php index adf15d61..cf51c4c5 100755 --- a/Observer/CreditmemoRefundObserver.php +++ b/Observer/CreditmemoRefundObserver.php @@ -173,7 +173,7 @@ private function itemOrderLines($couponCodeAmount, $discountAllItems, $memo) if ($qty > 0 && $productType != 'bundle') { $discountAmount = $item->getDiscountAmount(); $originalPrice = $item->getOrderItem()->getOriginalPrice(); - + $totalPrice = $originalPrice * $qty; if ($originalPrice == 0) { $originalPrice = $item->getPriceInclTax(); } @@ -190,11 +190,12 @@ private function itemOrderLines($couponCodeAmount, $discountAllItems, $memo) $taxAmount = $this->priceHandler->calculateTaxAmount($unitPrice, $taxPercent, $qty); } $itemDiscountInformation = $this->discountHandler->getItemDiscountInformation( - $originalPrice, + $totalPrice, $price, $discountAmount, $qty, - $discountAllItems + $discountAllItems, + $item ); if ($item->getPriceInclTax()) { $discountedAmount = $itemDiscountInformation['discount']; @@ -205,7 +206,8 @@ private function itemOrderLines($couponCodeAmount, $discountAllItems, $memo) $discountedAmount, $taxAmount, $memo->getOrder(), - false + false, + $discountAllItems ); // Gateway and cms rounding amount $roundingCompensation = $this->priceHandler->compensationAmountCal( From be0ab7af96d3458412feaa52862a2eb813616e2e Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Thu, 25 Aug 2022 17:22:12 +0500 Subject: [PATCH 04/31] Product stock not updating when order status change from cancel to processing --- CHANGELOG.md | 1 + Model/Generator.php | 50 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f1f836ed..15d3d171 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to this project will be documented in this file. **Fixes** - Cancel order issues when there is no transaction - Order failing issue when applying a fixed discount on the cart +- Product stock not updating when order status change from cancel to processing ## [2.0.5] **Fixes** diff --git a/Model/Generator.php b/Model/Generator.php index 57f0b739..b4051785 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -39,6 +39,9 @@ use Magento\Sales\Model\OrderFactory; use Altapay\Response\PaymentRequestResponse; use Magento\Payment\Model\MethodInterface; +use Magento\Checkout\Model\Cart; +use Magento\CatalogInventory\Api\StockStateInterface; +use Magento\CatalogInventory\Api\StockRegistryInterface; /** * Class Generator @@ -118,6 +121,18 @@ class Generator * @var OrderFactory */ private $orderFactory; + /** + * @var StockStateInterface + */ + private $stockItem; + /** + * @var StockRegistryInterface + */ + private $stockRegistry; + /** + * @var Cart + */ + private $modelCart; /** * @@ -139,6 +154,9 @@ class Generator * @param DiscountHandler $discountHandler * @param CreatePaymentHandler $paymentHandler * @param TokenFactory $dataToken + * @param StockStateInterface $stockItem + * @param StockRegistryInterface $stockRegistry + * @param Cart $modelCart */ public function __construct( Quote $quote, @@ -158,7 +176,10 @@ public function __construct( PriceHandler $priceHandler, DiscountHandler $discountHandler, CreatePaymentHandler $paymentHandler, - TokenFactory $dataToken + TokenFactory $dataToken, + StockStateInterface $stockItem, + StockRegistryInterface $stockRegistry, + Cart $modelCart ) { $this->quote = $quote; $this->urlInterface = $urlInterface; @@ -178,6 +199,9 @@ public function __construct( $this->discountHandler = $discountHandler; $this->paymentHandler = $paymentHandler; $this->dataToken = $dataToken; + $this->stockItem = $stockItem; + $this->stockRegistry = $stockRegistry; + $this->modelCart = $modelCart; } /** @@ -471,6 +495,8 @@ private function completeCheckout($comment, RequestInterface $request) $order->addStatusHistoryComment($comment); $order->addStatusHistoryComment($this->getTransactionInfoFromResponse($response)); $order->setIsNotified(false); + //Update stock quantity + $this->updateStockQty($order); $order->getResource()->save($order); if (strtolower($paymentStatus) == 'paymentandcapture') { @@ -480,6 +506,28 @@ private function completeCheckout($comment, RequestInterface $request) } } + /** + * @param $order + * return void + */ + public function updateStockQty($order) + { + $cart = $this->modelCart; + $quoteItems = $this->checkoutSession->getQuote()->getItemsCollection(); + foreach ($order->getAllItems() as $item) { + $stockQty = $this->stockItem->getStockQty($item->getProductId(), $item->getStore()->getWebsiteId()); + $qty = $stockQty - $item->getQtyOrdered(); + $stockItem = $this->stockRegistry->getStockItemBySku($item['sku']); + $stockItem->setQty($qty); + $stockItem->setIsInStock((bool)$qty); + $this->stockRegistry->updateStockItemBySku($item['sku'], $stockItem); + } + foreach($quoteItems as $item) + { + $cart->removeItem($item->getId())->save(); + } + } + /** * @param $response * From fea9d63e5999357b163c08247bd9a3f8ee0718b9 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 09:53:11 +0500 Subject: [PATCH 05/31] Saved credit cards grid styling for mobile view --- CHANGELOG.md | 1 + view/frontend/templates/saved_credit_card.phtml | 13 +++++++------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 15d3d171..a5936f3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project will be documented in this file. - Cancel order issues when there is no transaction - Order failing issue when applying a fixed discount on the cart - Product stock not updating when order status change from cancel to processing +- Saved credit cards grid styling for mobile view ## [2.0.5] **Fixes** diff --git a/view/frontend/templates/saved_credit_card.phtml b/view/frontend/templates/saved_credit_card.phtml index f5b24b80..8b8f5495 100644 --- a/view/frontend/templates/saved_credit_card.phtml +++ b/view/frontend/templates/saved_credit_card.phtml @@ -21,17 +21,18 @@ if ($collection->getSize() > 0) { escapeHtml(__('Card type')); ?> escapeHtml(__('Masked pan')); ?> escapeHtml(__('Expires')); ?> - escapeHtml(__('Primary')); ?> + escapeHtml(__('Primary')); ?> escapeHtml(__('Action')); ?> - escapeHtml($item->getCardType()); ?> - escapeHtml($item->getMaskedPan()); ?> - escapeHtml($item->getExpires()); ?> - + escapeHtml($item->getCardType()); ?> + escapeHtml($item->getMaskedPan()); ?> + escapeHtml($item->getExpires()); ?> + getSize() > 0) { getPrimary()): ?>checked="checked" /> - + From cdc7021f13164ccf7ee72bf9beffafcb2dd24a5e Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 10:04:48 +0500 Subject: [PATCH 06/31] Capitalize the first letter of the configuration field --- etc/adminhtml/system.xml | 16 ++++++++-------- etc/adminhtml/system/terminal1.xml | 12 ++++++------ etc/adminhtml/system/terminal2.xml | 10 +++++----- etc/adminhtml/system/terminal3.xml | 10 +++++----- etc/adminhtml/system/terminal4.xml | 10 +++++----- etc/adminhtml/system/terminal5.xml | 10 +++++----- 6 files changed, 34 insertions(+), 34 deletions(-) diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 342b0a82..e97461cf 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -14,7 +14,7 @@
- + 1 @@ -22,7 +22,7 @@ 0 - + You can find your Api Keys in your AltaPay Merchnat Account]]> SDM\Altapay\Block\Adminhtml\Render\Version @@ -41,19 +41,19 @@ - - payment/altapay_config/productionurl + + payment/altapay_config/productionurl - - Can we connect to Altapay + + Can we connect to AltaPay SDM\Altapay\Model\Config\Source\Connection - - Can we authenticate to Altapay - Remember to save after you have typed your API login and password + + Can we authenticate to AltaPay - Remember to save after you have typed your API login and password SDM\Altapay\Model\Config\Source\Authentication diff --git a/etc/adminhtml/system/terminal1.xml b/etc/adminhtml/system/terminal1.xml index 5a45339a..6b1b5e96 100755 --- a/etc/adminhtml/system/terminal1.xml +++ b/etc/adminhtml/system/terminal1.xml @@ -22,20 +22,20 @@ payment/terminal1/title - + Select terminal - Remember to save configuration after you have added your API login and password, to get your terminals payment/terminal1/terminalname SDM\Altapay\Model\Config\Source\Terminals altapay-terminal-name - + Force the language of the payment page SDM\Altapay\Model\Config\Source\Languages payment/terminal1/language - + If you only sell download products, which are delivered immediately you can turn this on Magento\Config\Model\Config\Source\Yesno payment/terminal1/capture @@ -47,7 +47,7 @@ SDM\Altapay\Model\Config\Source\TerminalLogo - + If you want to show both terminal logo and title Magento\Config\Model\Config\Source\Yesno payment/terminal1/showlogoandtitle @@ -60,7 +60,7 @@ altapay-terminal-token-control - + Address Verification System Magento\Config\Model\Config\Source\Yesno payment/terminal1/avscontrol @@ -72,7 +72,7 @@ payment/terminal1/enforceavs - + All codes upercase, comma separated payment/terminal1/avs_acceptance diff --git a/etc/adminhtml/system/terminal2.xml b/etc/adminhtml/system/terminal2.xml index a79a8bb4..bb95a85b 100755 --- a/etc/adminhtml/system/terminal2.xml +++ b/etc/adminhtml/system/terminal2.xml @@ -22,20 +22,20 @@ payment/terminal2/title - + Select terminal - Remember to save configuration after you have added your API login and password, to get your terminals payment/terminal2/terminalname SDM\Altapay\Model\Config\Source\Terminals altapay-terminal-name - + Force the language of the payment page SDM\Altapay\Model\Config\Source\Languages payment/terminal2/language - + If you only sell download products, which are delivered immediately you can turn this on Magento\Config\Model\Config\Source\Yesno payment/terminal2/capture @@ -47,7 +47,7 @@ SDM\Altapay\Model\Config\Source\TerminalLogo - + If you want to show both terminal logo and title Magento\Config\Model\Config\Source\Yesno payment/terminal2/showlogoandtitle @@ -72,7 +72,7 @@ payment/terminal2/enforceavs - + All codes upercase, comma separated payment/terminal2/avs_acceptance diff --git a/etc/adminhtml/system/terminal3.xml b/etc/adminhtml/system/terminal3.xml index 44c63b10..c793b9bb 100755 --- a/etc/adminhtml/system/terminal3.xml +++ b/etc/adminhtml/system/terminal3.xml @@ -22,20 +22,20 @@ payment/terminal3/title - + Select terminal - Remember to save configuration after you have added your API login and password, to get your terminals payment/terminal3/terminalname SDM\Altapay\Model\Config\Source\Terminals altapay-terminal-name - + Force the language of the payment page SDM\Altapay\Model\Config\Source\Languages payment/terminal3/language - + If you only sell download products, which are delivered immediately you can turn this on Magento\Config\Model\Config\Source\Yesno payment/terminal3/capture @@ -47,7 +47,7 @@ SDM\Altapay\Model\Config\Source\TerminalLogo - + If you want to show both terminal logo and title Magento\Config\Model\Config\Source\Yesno payment/terminal3/showlogoandtitle @@ -72,7 +72,7 @@ payment/terminal3/enforceavs - + All codes upercase, comma separated payment/terminal3/avs_acceptance diff --git a/etc/adminhtml/system/terminal4.xml b/etc/adminhtml/system/terminal4.xml index d88dad41..e13906f9 100755 --- a/etc/adminhtml/system/terminal4.xml +++ b/etc/adminhtml/system/terminal4.xml @@ -22,20 +22,20 @@ payment/terminal4/title - + Select terminal - Remember to save configuration after you have added your API login and password, to get your terminals payment/terminal4/terminalname SDM\Altapay\Model\Config\Source\Terminals altapay-terminal-name - + Force the language of the payment page SDM\Altapay\Model\Config\Source\Languages payment/terminal4/language - + If you only sell download products, which are delivered immediately you can turn this on Magento\Config\Model\Config\Source\Yesno payment/terminal4/capture @@ -47,7 +47,7 @@ SDM\Altapay\Model\Config\Source\TerminalLogo - + If you want to show both terminal logo and title Magento\Config\Model\Config\Source\Yesno payment/terminal4/showlogoandtitle @@ -72,7 +72,7 @@ payment/terminal4/enforceavs - + All codes upercase, comma separated payment/terminal4/avs_acceptance diff --git a/etc/adminhtml/system/terminal5.xml b/etc/adminhtml/system/terminal5.xml index 15a3d04b..0092404d 100755 --- a/etc/adminhtml/system/terminal5.xml +++ b/etc/adminhtml/system/terminal5.xml @@ -22,20 +22,20 @@ payment/terminal5/title - + Select terminal - Remember to save configuration after you have added your API login and password, to get your terminals payment/terminal5/terminalname SDM\Altapay\Model\Config\Source\Terminals altapay-terminal-name - + Force the language of the payment page SDM\Altapay\Model\Config\Source\Languages payment/terminal5/language - + If you only sell download products, which are delivered immediately you can turn this on Magento\Config\Model\Config\Source\Yesno payment/terminal5/capture @@ -47,7 +47,7 @@ SDM\Altapay\Model\Config\Source\TerminalLogo - + If you want to show both terminal logo and title Magento\Config\Model\Config\Source\Yesno payment/terminal5/showlogoandtitle @@ -72,7 +72,7 @@ payment/terminal5/enforceavs - + All codes upercase, comma separated payment/terminal5/avs_acceptance From 55529c414755100a45e9872916fedffc26942067 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 10:13:53 +0500 Subject: [PATCH 07/31] Success page rendering issue when placing an order in incognito mode with the MobilePay --- CHANGELOG.md | 1 + Controller/Index.php | 32 ++++++- Controller/Index/Ok.php | 3 +- .../Checkout/Controller/Onepage/Success.php | 85 +++++++++++++++++++ Setup/UpgradeSchema.php | 15 ++++ etc/frontend/di.xml | 3 + 6 files changed, 137 insertions(+), 2 deletions(-) create mode 100644 Plugin/Checkout/Controller/Onepage/Success.php diff --git a/CHANGELOG.md b/CHANGELOG.md index a5936f3b..1bfdc70f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to this project will be documented in this file. - Order failing issue when applying a fixed discount on the cart - Product stock not updating when order status change from cancel to processing - Saved credit cards grid styling for mobile view +- Success page rendering issue when placing an order in incognito mode with the MobilePay ## [2.0.5] **Fixes** diff --git a/Controller/Index.php b/Controller/Index.php index 2da1466b..5a469aef 100755 --- a/Controller/Index.php +++ b/Controller/Index.php @@ -17,6 +17,9 @@ use Magento\Sales\Model\Order; use Psr\Log\LoggerInterface; use SDM\Altapay\Model\Generator; +use Magento\Framework\Controller\Result\RedirectFactory; +use Magento\Framework\Encryption\EncryptorInterface; +use Magento\Framework\Math\Random; abstract class Index extends Action { @@ -69,7 +72,10 @@ public function __construct( Quote $quote, Session $checkoutSession, Generator $generator, - LoggerInterface $logger + Logger $altapayLogger, + EncryptorInterface $encryptor, + Random $random, + RedirectFactory $redirectFactory ) { parent::__construct($context); $this->order = $order; @@ -78,6 +84,9 @@ public function __construct( $this->generator = $generator; $this->logger = $logger; $this->pageFactory = $pageFactory; + $this->encryptor = $encryptor; + $this->random = $random; + $this->redirectFactory = $redirectFactory; } /** @@ -103,4 +112,25 @@ protected function writeLog() $this->logger->debug(print_r($this->getRequest()->getParams(), true)); $this->logger->debug('- END: ' . $calledClass); } + + /** + * @param string $orderId + * + * @return mixed + */ + protected function setSuccessPath($orderId) + { + $resultRedirect = $this->redirectFactory->create(); + if ($orderId) { + $order = $this->order->loadByIncrementId($orderId); + $uniqueHash = $this->random->getUniqueHash(); + $order->setAltapayOrderHash($uniqueHash); + $order->getResource()->save($order); + $resultRedirect->setPath('checkout/onepage/success',['success_token' => $uniqueHash]); + } else { + $resultRedirect->setPath('checkout/onepage/success'); + } + + return $resultRedirect; + } } diff --git a/Controller/Index/Ok.php b/Controller/Index/Ok.php index ad635316..043a0f86 100755 --- a/Controller/Index/Ok.php +++ b/Controller/Index/Ok.php @@ -27,6 +27,7 @@ public function execute() $this->writeLog(); $checkAvs = false; $post = $this->getRequest()->getPostValue(); + $orderId = $post['shop_orderid']; if (isset($post['avs_code']) && isset($post['avs_text'])) { $checkAvs = $this->generator->avsCheck( $this->getRequest(), @@ -37,7 +38,7 @@ public function execute() if ($this->checkPost() && $checkAvs == false) { $this->generator->handleOkAction($this->getRequest()); - return $this->_redirect('checkout/onepage/success'); + return $this->setSuccessPath($orderId); } else { $this->_eventManager->dispatch('order_cancel_after', ['order' => $this->order]); diff --git a/Plugin/Checkout/Controller/Onepage/Success.php b/Plugin/Checkout/Controller/Onepage/Success.php new file mode 100644 index 00000000..95b7ce6c --- /dev/null +++ b/Plugin/Checkout/Controller/Onepage/Success.php @@ -0,0 +1,85 @@ +coreRegistry = $coreRegistry; + $this->checkoutSession = $checkoutSession; + $this->orderFactory = $orderFactory; + $this->orderColl = $orderColl; + } + + /** + * @param \Magento\Checkout\Controller\Onepage\Success $subject + */ + public function beforeExecute(\Magento\Checkout\Controller\Onepage\Success $subject) + { + $hash = $subject->getRequest()->getParam('success_token', false); + if (!$hash) { + return; + } + $collectionData = $this->orderColl->create()->addFieldToSelect( + 'increment_id' + )->addFieldToFilter( + 'altapay_order_hash', + $hash + ); + $collectionInfo = $collectionData->getData(); + foreach ($collectionInfo as $data) { + $orderId = $data['increment_id']; + if ($orderId && is_numeric($orderId)) { + $order = $this->orderFactory->loadByIncrementId($orderId); + if ($order && $order->getId() && $order->getAltapayOrderHash() !== null) { + $this->checkoutSession->setLastQuoteId($order->getQuoteId()); + $this->checkoutSession->setLastSuccessQuoteId($order->getQuoteId()); + $this->checkoutSession->setLastOrderId($order->getId()); + $this->checkoutSession->setLastRealOrderId($order->getIncrementId()); + $this->checkoutSession->setLastOrderStatus($order->getStatus()); + $order->setAltapayOrderHash(null); + $order->getResource()->save($order); + } + + } + } + } +} \ No newline at end of file diff --git a/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php index d98c6be8..3997fbba 100644 --- a/Setup/UpgradeSchema.php +++ b/Setup/UpgradeSchema.php @@ -171,6 +171,21 @@ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $con )->setComment('Altapay Tokens'); $setup->getConnection()->createTable($altapayTokenTableName); } + $orderHash = "altapay_order_hash"; + if (!$setup->getConnection()->tableColumnExists($setup->getTable($orderTable), $orderHash)) { + $setup->getConnection()->addColumn( + $setup->getTable($orderTable), + $orderHash, + [ + 'type' => Table::TYPE_TEXT, + 'length' => 65536, + 'nullable' => true, + 'visible' => false, + 'comment' => 'Alapay Order Hash', + ] + ); + } + $setup->endSetup(); } } \ No newline at end of file diff --git a/etc/frontend/di.xml b/etc/frontend/di.xml index 1ae8c3e8..b4d29543 100755 --- a/etc/frontend/di.xml +++ b/etc/frontend/di.xml @@ -17,4 +17,7 @@ + + + From d7484a6034be07d9b3360f32ecd02060020d1547 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 10:27:31 +0500 Subject: [PATCH 08/31] Add a button to trigger the sync of the terminals with the gateway --- Block/System/Config/Button.php | 78 +++++ CHANGELOG.md | 1 + Controller/Adminhtml/System/Config/Button.php | 296 ++++++++++++++++++ etc/adminhtml/routes.xml | 18 ++ etc/adminhtml/system.xml | 13 +- .../templates/system/config/button.phtml | 35 +++ 6 files changed, 439 insertions(+), 2 deletions(-) create mode 100644 Block/System/Config/Button.php create mode 100644 Controller/Adminhtml/System/Config/Button.php create mode 100644 etc/adminhtml/routes.xml create mode 100644 view/adminhtml/templates/system/config/button.phtml diff --git a/Block/System/Config/Button.php b/Block/System/Config/Button.php new file mode 100644 index 00000000..4c430255 --- /dev/null +++ b/Block/System/Config/Button.php @@ -0,0 +1,78 @@ +request = $request; + } + + /** + * @param AbstractElement $element + * + * @return mixed + */ + protected function _getElementHtml(AbstractElement $element) + { + return $this->_toHtml(); + } + + /** + * @return string + */ + public function getCustomUrl() + { + return $this->getUrl('sdmaltapay/system_config/button'); + } + + /** + * @return string + */ + public function getButtonHtml() + { + $button = $this->getLayout()->createBlock( + 'Magento\Backend\Block\Widget\Button' + )->setData( + [ + 'id' => 'sync_button', + 'label' => __('Synchronize Terminals') + ] + ); + + return $button->toHtml(); + } + + /** + * @return int + */ + public function getUrlInterfaceData() + { + $request = $this->_request; + + return (int) $request->getParam('store', 0); + } +} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bfdc70f..70e3ea1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to this project will be documented in this file. **Improvements** - Add support when cart and catalog rules are applied simultaneously - Make text "No saved credit cards" translatable +- Add a button to trigger the sync of the terminals with the gateway **Fixes** - Cancel order issues when there is no transaction diff --git a/Controller/Adminhtml/System/Config/Button.php b/Controller/Adminhtml/System/Config/Button.php new file mode 100644 index 00000000..1f652721 --- /dev/null +++ b/Controller/Adminhtml/System/Config/Button.php @@ -0,0 +1,296 @@ +resultJsonFactory = $resultJsonFactory; + $this->systemConfig = $systemConfig; + $this->resourceConfig = $resourceConfig; + $this->storeConfig = $storeConfig; + $this->_response = $response; + $this->cacheTypeList = $cacheTypeList; + $this->storeManager = $storeManager; + $this->_state = $state; + $this->_resource = $resource; + parent::__construct($context); + } + + /** + * @return Json + */ + public function execute() + { + + $currentStoreID = (int)$this->getRequest()->getParam('storeid'); + if ($currentStoreID == 0) { + $scopeCode = ScopeConfigInterface::SCOPE_TYPE_DEFAULT; + } else { + $scopeCode = ScopeInterface::SCOPE_STORES; + } + $currentCurrency = $this->storeConfig->getValue( + self::COUNTRY_CODE_PATH, + $scopeCode, + $currentStoreID + ); + + try { + $call = new Terminals($this->systemConfig->getAuth()); + /** @var TerminalsResponse $response */ + $response = $call->call(); + $terminalList = $this->getTerminal($response, $currentCurrency); + + if (count($terminalList) <= 5) { + + if ($this->checkConfigAlreadyExist($terminalList, $scopeCode, $currentStoreID)) { + $message = __('Terminals are already configured, please check the dropdown manually.'); + } else { + $this->saveTerminalConfig($terminalList, $currentStoreID, $scopeCode); + $this->cacheTypeList->cleanType(cacheConfig::TYPE_IDENTIFIER); + $message = __('Terminals successfully configured!'); + } + } else { + $message = __('We could not match terminals to this store. Too many terminals exist, please check the dropdown manually.'); + } + + } catch (ClientException $e) { + $message = __("Error:" . $e->getMessage()); + } catch (Exception $e) { + $message = __("Error:" . $e->getMessage()); + } + + /** @var Json $result */ + $result = $this->resultJsonFactory->create(); + + return $result->setData(['message' => $message]); + } + + /** + * @param $response array + * @param $currentCurrency string + * + * @return array + */ + public function getTerminal($response, $currentCurrency) + { + $terminals = []; + foreach ($response->Terminals as $terminal) { + if ($terminal->Country == $currentCurrency) { + $terminals[] = $terminal->Title; + } + } + + return $terminals; + } + + /** + * @param $terminals array + * @param $currentStoreID int + * @param $scopeCode string + */ + public function saveTerminalConfig($terminals, $currentStoreID, $scopeCode) + { + $i = 1; + foreach ($terminals as $terminal) { + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/active', + 1, + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/title', + $terminal, + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/language', + null, + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/capture', + 0, + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/terminallogo', + '', + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/showlogoandtitle', + 0, + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/savecardtoken', + 0, + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/avscontrol', + 0, + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/enforceavs', + 0, + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/avs_acceptance', + 0, + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/sort_order', + 0, + $scopeCode, + $currentStoreID + ); + + $this->resourceConfig->saveConfig( + 'payment/terminal' . $i . '/terminalname', + $terminal, + $scopeCode, + $currentStoreID + ); + + $i++; + } + } + + /** + * @param $terminalList array + * @param $scopeCode string + * + * @return bool + */ + public function checkConfigAlreadyExist($terminalList, $scopeCode, $scopeID) + { + $i = 1; + $terminalConfigured = false; + $tableName = $this->_resource->getTableName('core_config_data'); + foreach ($terminalList as $terminal) { + //Initiate Connection + $connection = $this->_resource->getConnection(); + $path = 'payment/terminal' . $i . '/active'; + $scope = $scopeCode; + $scopeId = $scopeID; + $select = $connection->select() + ->from( + ['c' => $tableName], + ['config_id'] + ) + ->where( + "c.path = :path" + )->where( + "c.scope = :scope" + )->where( + "c.scope_id = :scope_id" + ); + $bind = ['path' => $path, 'scope' => $scope, 'scope_id' => $scopeId]; + + if ($connection->fetchOne($select, $bind)) { + $terminalConfigured = true; + break; + } + $i++; + } + + return $terminalConfigured; + } +} \ No newline at end of file diff --git a/etc/adminhtml/routes.xml b/etc/adminhtml/routes.xml new file mode 100644 index 00000000..b3b7ae97 --- /dev/null +++ b/etc/adminhtml/routes.xml @@ -0,0 +1,18 @@ + + + + + + + + + + \ No newline at end of file diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index e97461cf..b343ca98 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -92,14 +92,23 @@ SDM\Altapay\Model\Config\Source\Order\Status\Cancel payment/altapay_status/cancel - + The status on the order if autocapture is enabled SDM\Altapay\Model\Config\Source\Order\Status\Autocapture payment/altapay_status/autocapture - + + 0 + + + + + SDM\Altapay\Block\System\Config\Button + + + diff --git a/view/adminhtml/templates/system/config/button.phtml b/view/adminhtml/templates/system/config/button.phtml new file mode 100644 index 00000000..0253afe0 --- /dev/null +++ b/view/adminhtml/templates/system/config/button.phtml @@ -0,0 +1,35 @@ + + +getButtonHtml(); ?> \ No newline at end of file From 24c7f094ce9f786b8f69b0f2ff867a7c1dd5c7db Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 10:52:34 +0500 Subject: [PATCH 09/31] Stock quantity calculation issue --- Model/Generator.php | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/Model/Generator.php b/Model/Generator.php index b4051785..1b90803f 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -435,8 +435,16 @@ private function completeCheckout($comment, RequestInterface $request) { $callback = new Callback($request->getParams()); $response = $callback->call(); - $paymentStatus = $response->type; + $paymentType = $response->type; $requireCapture = $response->requireCapture; + $paymentStatus = strtolower($response->paymentStatus); + $responseStatus = $response->status; + + if ($paymentStatus === 'released') { + $this->handleCancelStatusAction($request, $responseStatus); + return; + } + if ($response) { $order = $this->loadOrderFromCallback($response); $storeScope = ScopeInterface::SCOPE_STORE; @@ -461,6 +469,7 @@ private function completeCheckout($comment, RequestInterface $request) $payment->setAdditionalInformation('masked_credit_card', $response->maskedCreditCard); $payment->setAdditionalInformation('expires', $expires); $payment->setAdditionalInformation('card_type', $cardType); + $payment->setAdditionalInformation('payment_type', $paymentType); $payment->save(); //send order confirmation email $this->sendOrderConfirmationEmail($comment, $order); @@ -496,10 +505,12 @@ private function completeCheckout($comment, RequestInterface $request) $order->addStatusHistoryComment($this->getTransactionInfoFromResponse($response)); $order->setIsNotified(false); //Update stock quantity - $this->updateStockQty($order); + if($order->getState() == 'canceled') { + $this->updateStockQty($order); + } $order->getResource()->save($order); - if (strtolower($paymentStatus) == 'paymentandcapture') { + if (strtolower($paymentType) === 'paymentandcapture' || strtolower($paymentType) === 'subscriptionandcharge') { $this->createInvoice($order, $requireCapture); } } @@ -516,7 +527,7 @@ public function updateStockQty($order) $quoteItems = $this->checkoutSession->getQuote()->getItemsCollection(); foreach ($order->getAllItems() as $item) { $stockQty = $this->stockItem->getStockQty($item->getProductId(), $item->getStore()->getWebsiteId()); - $qty = $stockQty - $item->getQtyOrdered(); + $qty = $stockQty - $item->getQtyOrdered(); $stockItem = $this->stockRegistry->getStockItemBySku($item['sku']); $stockItem->setQty($qty); $stockItem->setIsInStock((bool)$qty); From 5e22289a43d3947c2a207ccb29cd6a3cdd7d5ded Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 10:52:44 +0500 Subject: [PATCH 10/31] Add configurations section to setup cron scheduler to change the status of the pending order to cancel --- .../System/Config/ChangeOrderStatusButton.php | 78 ++++++++++++ CHANGELOG.md | 4 + Controller/Adminhtml/System/Config/Button.php | 3 +- .../System/Config/ChangeOrderStatusButton.php | 119 ++++++++++++++++++ Model/Config/Source/CronConfig.php | 117 +++++++++++++++++ Model/Cron/UpdateOrderStatus.php | 107 ++++++++++++++++ etc/adminhtml/system.xml | 23 +++- etc/crontab.xml | 18 +++ .../templates/system/config/button.phtml | 9 ++ .../system/config/changestatusbutton.phtml | 37 ++++++ 10 files changed, 512 insertions(+), 3 deletions(-) create mode 100644 Block/System/Config/ChangeOrderStatusButton.php create mode 100644 Controller/Adminhtml/System/Config/ChangeOrderStatusButton.php create mode 100644 Model/Config/Source/CronConfig.php create mode 100644 Model/Cron/UpdateOrderStatus.php create mode 100644 etc/crontab.xml create mode 100644 view/adminhtml/templates/system/config/changestatusbutton.phtml diff --git a/Block/System/Config/ChangeOrderStatusButton.php b/Block/System/Config/ChangeOrderStatusButton.php new file mode 100644 index 00000000..a24a0cb8 --- /dev/null +++ b/Block/System/Config/ChangeOrderStatusButton.php @@ -0,0 +1,78 @@ +request = $request; + } + + /** + * @param AbstractElement $element + * + * @return mixed + */ + protected function _getElementHtml(AbstractElement $element) + { + return $this->_toHtml(); + } + + /** + * @return string + */ + public function getCustomUrl() + { + return $this->getUrl('sdmaltapay/system_config/changeorderstatusbutton'); + } + + /** + * @return string + */ + public function getButtonHtml() + { + $button = $this->getLayout()->createBlock( + 'Magento\Backend\Block\Widget\Button' + )->setData( + [ + 'id' => 'change_order_status', + 'label' => __('Change Status Now') + ] + ); + + return $button->toHtml(); + } + + /** + * @return int + */ + public function getUrlInterfaceData() + { + $request = $this->_request; + + return (int) $request->getParam('store', 0); + } +} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 70e3ea1b..f75e851c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file. - Add support when cart and catalog rules are applied simultaneously - Make text "No saved credit cards" translatable - Add a button to trigger the sync of the terminals with the gateway +- Add configurations section to setup cron scheduler to change the status of the pending order to cancel **Fixes** - Cancel order issues when there is no transaction @@ -13,6 +14,9 @@ All notable changes to this project will be documented in this file. - Product stock not updating when order status change from cancel to processing - Saved credit cards grid styling for mobile view - Success page rendering issue when placing an order in incognito mode with the MobilePay +- Cancel order if payment_status is "released" in notification callback +- Handle empty synch button response +- Stock quantity calculation issue ## [2.0.5] **Fixes** diff --git a/Controller/Adminhtml/System/Config/Button.php b/Controller/Adminhtml/System/Config/Button.php index 1f652721..a555513d 100644 --- a/Controller/Adminhtml/System/Config/Button.php +++ b/Controller/Adminhtml/System/Config/Button.php @@ -113,8 +113,7 @@ public function execute() $response = $call->call(); $terminalList = $this->getTerminal($response, $currentCurrency); - if (count($terminalList) <= 5) { - + if (!empty($terminalList) && count($terminalList) <= 5) { if ($this->checkConfigAlreadyExist($terminalList, $scopeCode, $currentStoreID)) { $message = __('Terminals are already configured, please check the dropdown manually.'); } else { diff --git a/Controller/Adminhtml/System/Config/ChangeOrderStatusButton.php b/Controller/Adminhtml/System/Config/ChangeOrderStatusButton.php new file mode 100644 index 00000000..ab8079f3 --- /dev/null +++ b/Controller/Adminhtml/System/Config/ChangeOrderStatusButton.php @@ -0,0 +1,119 @@ +logger = $logger; + $this->resultJsonFactory = $resultJsonFactory; + $this->orderRepository = $orderRepository; + $this->searchCriteriaBuilder = $searchCriteriaBuilder; + $this->scopeConfig = $scopeConfig; + $this->orderCollection = $orderCollection; + parent::__construct($context); + } + + /** + * @return Json + */ + public function execute() + { + $completeStatus = 'canceled'; + try + { + $orderCollection = $this->orderCollection->create(); + $orderCollection->addAttributeToFilter('status','pending') + ->addAttributeToFilter('altapay_payment_form_url', ['neq' => 'NULL']); + + if (array_filter($orderCollection->getData())) { + foreach ($orderCollection as $order) { + $order = $this->orderRepository->get($order->getEntityId()); + $order->setStatus($completeStatus)->setState($completeStatus); + + $this->orderRepository->save($order); + } + + $message = __('Order status has been changed from pending to canceled'); + + } else { + $message = __('No order exist with pendng status'); + } + } catch (\Exception $e) + { + $message = __("Error:" . $e->getMessage()); + } + + /** @var Json $result */ + $result = $this->resultJsonFactory->create(); + + return $result->setData(['message' => $message]); + } +} \ No newline at end of file diff --git a/Model/Config/Source/CronConfig.php b/Model/Config/Source/CronConfig.php new file mode 100644 index 00000000..3ec8e061 --- /dev/null +++ b/Model/Config/Source/CronConfig.php @@ -0,0 +1,117 @@ +_runModelPath = $runModelPath; + $this->_configValueFactory = $configValueFactory; + $this->scopeConfig = $scopeConfig; + parent::__construct($context, $registry, $scopeConfig, $cacheTypeList, $resource, $resourceCollection, $data); + } + + /** + * @return mixed + * @throws \Exception + */ + public function afterSave() + { + $time = $this->getData('groups/sdm_altapay_config/groups/cronScheduled/fields/time/value'); + $frequency = $this->getData('groups/sdm_altapay_config/groups/cronScheduled/fields/frequency/value'); + $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; + $cronEnabled = $this->scopeConfig->getValue(self::CRON_ENABLED, $storeScope); + try + { + if($cronEnabled) { + $cronExprArray = [ + intval($time[1]), //Minute + intval($time[0]), //Hour + $frequency == \Magento\Cron\Model\Config\Source\Frequency::CRON_MONTHLY ? '1' : '*', + '*', + $frequency == \Magento\Cron\Model\Config\Source\Frequency::CRON_WEEKLY ? '1' : '*', + ]; + $cronExprString = join(' ', $cronExprArray); + + $this->_configValueFactory->create()->load( + self::CRON_STRING_PATH, + 'path' + )->setValue( + $cronExprString + )->setPath( + self::CRON_STRING_PATH + )->save(); + $this->_configValueFactory->create()->load( + self::CRON_MODEL_PATH, + 'path' + )->setValue( + $this->_runModelPath + )->setPath( + self::CRON_MODEL_PATH + )->save(); + } + } + catch (\Exception $e) + { + throw new \Exception(__('Something went wrong, Can\'t save the cron expression.')); + } + return parent::afterSave(); + } + } \ No newline at end of file diff --git a/Model/Cron/UpdateOrderStatus.php b/Model/Cron/UpdateOrderStatus.php new file mode 100644 index 00000000..b7d5784a --- /dev/null +++ b/Model/Cron/UpdateOrderStatus.php @@ -0,0 +1,107 @@ +logger = $logger; + $this->orderRepository = $orderRepository; + $this->searchCriteriaBuilder = $searchCriteriaBuilder; + $this->scopeConfig = $scopeConfig; + $this->orderCollection = $orderCollection; + } + + public function execute() + { + $completeStatus = 'canceled'; + $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; + $cronEnabled = $this->scopeConfig->getValue(self::CRON_ENABLED, $storeScope); + try + { + if (!$cronEnabled){ + $this->logger->info('Cron is not enabled'); + return; + } + $orderCollection = $this->orderCollection->create(); + $orderCollection->addAttributeToFilter('status','pending') + ->addAttributeToFilter('altapay_payment_form_url', ['neq' => 'NULL']); + + if (array_filter($orderCollection->getData())) { + foreach ($orderCollection as $order) { + + $order = $this->orderRepository->get($order->getEntityId()); + $order->setStatus($completeStatus)->setState($completeStatus); + + $this->orderRepository->save($order); + } + + $this->logger->info('Order status has been changed from pending to canceled'); + } else { + + $this->logger->info('No order exist with pending status'); + } + } + catch (\Exception $e) + { + throw new \Exception(__('Something went wrong , '.$e->getMessage())); + } + } + +} \ No newline at end of file diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index b343ca98..e74ff92b 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -12,12 +12,33 @@
- 1 + + + + + Magento\Config\Model\Config\Source\Yesno + + + + Magento\Cron\Model\Config\Source\Frequency + SDM\Altapay\Model\Config\CronConfig + + + + + + SDM\Altapay\Block\System\Config\ChangeOrderStatusButton + + + 0 diff --git a/etc/crontab.xml b/etc/crontab.xml new file mode 100644 index 00000000..933281e4 --- /dev/null +++ b/etc/crontab.xml @@ -0,0 +1,18 @@ + + + + + + + crontab/default/jobs/sdm_altapay_cron_job/schedule/cron_expr + + + \ No newline at end of file diff --git a/view/adminhtml/templates/system/config/button.phtml b/view/adminhtml/templates/system/config/button.phtml index 0253afe0..888aed82 100644 --- a/view/adminhtml/templates/system/config/button.phtml +++ b/view/adminhtml/templates/system/config/button.phtml @@ -1,3 +1,12 @@ + +getButtonHtml(); ?> \ No newline at end of file From f6361c8f75fae2fef15cdfeff73a88cc432974d7 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 10:56:18 +0500 Subject: [PATCH 11/31] Canceled order qty from item grid is missing --- CHANGELOG.md | 1 + Observer/CheckoutCartIndex.php | 18 +++++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f75e851c..05f9b8a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ All notable changes to this project will be documented in this file. - Cancel order if payment_status is "released" in notification callback - Handle empty synch button response - Stock quantity calculation issue +- Canceled order qty from item grid is missing ## [2.0.5] **Fixes** diff --git a/Observer/CheckoutCartIndex.php b/Observer/CheckoutCartIndex.php index 8676ec92..7b38d0a8 100755 --- a/Observer/CheckoutCartIndex.php +++ b/Observer/CheckoutCartIndex.php @@ -141,7 +141,8 @@ public function execute(Observer $observer) if ($order->getCouponCode()) { $this->resetCouponAfterCancellation($order); } - + //revert quantity when cancel order + $this->revertOrderQty($order); //revert quantity when cancel order $orderItems = $order->getAllItems(); foreach ($orderItems as $item) { @@ -214,4 +215,19 @@ public function verifyIfOrderStatus($orderStatusConfigBefore, $currentOrderStatu return false; } + + /** + * @param $order + */ + public function revertOrderQty($order) + { + foreach ($order->getAllItems() as $item) { + $item->setQtyCanceled($item['qty_ordered']); + $item->save(); + $qty = $item->getQtyOrdered() - max($item->getQtyShipped(), $item->getQtyInvoiced()); + if ($item->getId() && $item->getProductId() && empty($item->getChildrenItems()) && $qty) { + $this->stockManagement->backItemQty($item->getProductId(), $qty, $item->getStore()->getWebsiteId()); + } + } + } } From 6b4f8c6ab7c5111115025bea04d0627a447b0e84 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 11:03:08 +0500 Subject: [PATCH 12/31] Order status set to "closed" despite the orders being in a pre-auth state. --- CHANGELOG.md | 1 + Model/Generator.php | 15 +++++++++++++++ Observer/CheckoutCartIndex.php | 12 ++++++++---- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05f9b8a7..9d2d7913 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ All notable changes to this project will be documented in this file. - Handle empty synch button response - Stock quantity calculation issue - Canceled order qty from item grid is missing +- Order status set to "closed" despite the orders being in a pre-auth state. ## [2.0.5] **Fixes** diff --git a/Model/Generator.php b/Model/Generator.php index 1b90803f..2cd445ec 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -508,6 +508,7 @@ private function completeCheckout($comment, RequestInterface $request) if($order->getState() == 'canceled') { $this->updateStockQty($order); } + $this->resetCanceledQty($order); $order->getResource()->save($order); if (strtolower($paymentType) === 'paymentandcapture' || strtolower($paymentType) === 'subscriptionandcharge') { @@ -986,4 +987,18 @@ public function savePaymentData($response, $order) $payment->setLastTransId($response->transactionId); $payment->save(); } + + /** + * @param $order + * + * @return void + */ + public function resetCanceledQty($order) { + foreach ($order->getAllItems() as $item) { + if ($item->getQtyCanceled > 0) { + $item->setQtyCanceled($item->getQtyToCancel()); + $item->save(); + } + } + } } diff --git a/Observer/CheckoutCartIndex.php b/Observer/CheckoutCartIndex.php index 7b38d0a8..9014fde6 100755 --- a/Observer/CheckoutCartIndex.php +++ b/Observer/CheckoutCartIndex.php @@ -24,6 +24,7 @@ use Magento\Framework\Session\SessionManagerInterface; use SDM\Altapay\Model\ConstantConfig; use Magento\Store\Model\ScopeInterface; +use Magento\Catalog\Model\Indexer\Product\Price\Processor; class CheckoutCartIndex implements ObserverInterface { @@ -77,7 +78,8 @@ public function __construct( Coupon $coupon, CouponUsage $couponUsage, StockManagementInterface $stockManagement, - SystemConfig $systemConfig + SystemConfig $systemConfig, + Processor $priceIndexer ) { $this->session = $session; $this->quoteFactory = $quoteFactory; @@ -87,6 +89,7 @@ public function __construct( $this->couponUsage = $couponUsage; $this->stockManagement = $stockManagement; $this->systemConfig = $systemConfig; + $this->priceIndexer = $priceIndexer; } @@ -215,7 +218,7 @@ public function verifyIfOrderStatus($orderStatusConfigBefore, $currentOrderStatu return false; } - + /** * @param $order */ @@ -223,11 +226,12 @@ public function revertOrderQty($order) { foreach ($order->getAllItems() as $item) { $item->setQtyCanceled($item['qty_ordered']); - $item->save(); - $qty = $item->getQtyOrdered() - max($item->getQtyShipped(), $item->getQtyInvoiced()); + $item->save(); + $qty = $item->getQtyOrdered() - max($item->getQtyShipped(), $item->getQtyInvoiced()) - $item->getQtyCanceled(); if ($item->getId() && $item->getProductId() && empty($item->getChildrenItems()) && $qty) { $this->stockManagement->backItemQty($item->getProductId(), $qty, $item->getStore()->getWebsiteId()); } + $this->priceIndexer->reindexRow($item->getProductId()); } } } From 46617a7fe96c91353976fde0ba10a79c2cba36e9 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 12:00:10 +0500 Subject: [PATCH 13/31] Order status set to "closed" for "Vipps" payment method --- CHANGELOG.md | 1 + Model/Generator.php | 13 +++++++------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d2d7913..ffd6b5c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ All notable changes to this project will be documented in this file. - Stock quantity calculation issue - Canceled order qty from item grid is missing - Order status set to "closed" despite the orders being in a pre-auth state. +- Order status set to "closed" for "Vipps" payment method ## [2.0.5] **Fixes** diff --git a/Model/Generator.php b/Model/Generator.php index 2cd445ec..1d2d951c 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -452,6 +452,11 @@ private function completeCheckout($comment, RequestInterface $request) if ($order->getId()) { $cardType = ''; $expires = ''; + //Update stock quantity + if($order->getState() == 'canceled') { + $this->updateStockQty($order); + } + $this->resetCanceledQty($order); if (isset($response->Transactions[0])) { $transaction = $response->Transactions[0]; if (isset($transaction->CreditCardExpiry->Month) && isset($transaction->CreditCardExpiry->Year)) { @@ -504,11 +509,7 @@ private function completeCheckout($comment, RequestInterface $request) $order->addStatusHistoryComment($comment); $order->addStatusHistoryComment($this->getTransactionInfoFromResponse($response)); $order->setIsNotified(false); - //Update stock quantity - if($order->getState() == 'canceled') { - $this->updateStockQty($order); - } - $this->resetCanceledQty($order); + $order->getResource()->save($order); if (strtolower($paymentType) === 'paymentandcapture' || strtolower($paymentType) === 'subscriptionandcharge') { @@ -995,7 +996,7 @@ public function savePaymentData($response, $order) */ public function resetCanceledQty($order) { foreach ($order->getAllItems() as $item) { - if ($item->getQtyCanceled > 0) { + if ($item->getQtyCanceled() > 0) { $item->setQtyCanceled($item->getQtyToCancel()); $item->save(); } From 759b74ae69d2e331e63249a69ef2dd3c4103052f Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 12:10:52 +0500 Subject: [PATCH 14/31] Incorrect discount calculation --- CHANGELOG.md | 1 + Model/Handler/PriceHandler.php | 12 ++++++------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffd6b5c7..d53717a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ All notable changes to this project will be documented in this file. - Canceled order qty from item grid is missing - Order status set to "closed" despite the orders being in a pre-auth state. - Order status set to "closed" for "Vipps" payment method +- Incorrect discount calculation ## [2.0.5] **Fixes** diff --git a/Model/Handler/PriceHandler.php b/Model/Handler/PriceHandler.php index e5762a51..f5124132 100644 --- a/Model/Handler/PriceHandler.php +++ b/Model/Handler/PriceHandler.php @@ -62,15 +62,15 @@ public function dataForPrice($item, $unitPrice, $couponAmount, $itemDiscount, $d } else { $price = $item->getPrice(); } - if ($originalPrice > $price && !(float)$couponAmount) { - $data["catalogDiscount"] = true; - $data["discount"] = $this->discountHandler->catalogDiscount($originalPrice, $price); - } elseif ($originalPrice > $price && abs((float)$couponAmount) > 0 && !$discountAllItems) { + if ($originalPrice > $price && abs((float)$couponAmount) > 0 && !$discountAllItems) { $originalPrice = $originalPrice * $quantity; $data["catalogDiscount"] = true; $data["discount"] = $this->discountHandler->combinationDiscount($originalPrice, $rowTotal); + } else if ($originalPrice > $price && !(float)$couponAmount) { + $data["catalogDiscount"] = true; + $data["discount"] = $this->discountHandler->catalogDiscount($originalPrice, $price); } else { - $data["discount"] = $itemDiscount; + $data["discount"] = $itemDiscount; } return $data; @@ -140,7 +140,7 @@ public function compensationAmountCal( $gatewaySubTotal = ($unitPrice * $quantity) + $taxAmount; $gatewaySubTotal = $gatewaySubTotal - ($gatewaySubTotal * ($discountedAmount / 100)); // Magento calculation pattern - if (abs((float)$couponCodeAmount) > 0 && $storePriceIncTax && !$catalogDiscountCheck && $discountAllItems) { + if ((abs((float)$couponCodeAmount) > 0 && $storePriceIncTax && !$catalogDiscountCheck && $discountAllItems) || (abs((float)$couponCodeAmount) > 0 && $catalogDiscountCheck)) { $cmsPriceCal = $unitPriceWithoutTax * $quantity; $cmsTaxCal = $cmsPriceCal * ($taxPercent / 100); $cmsSubTotal = $cmsPriceCal + $cmsTaxCal; From ca089286ef78110078aa66c4b6e5758edb7b11db Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 16:45:36 +0500 Subject: [PATCH 15/31] Add support for Apple Pay --- CHANGELOG.md | 1 + Controller/Index/ApplePay.php | 122 +++++++++ Controller/Index/ApplePayResponse.php | 106 ++++++++ Controller/Index/Cancel.php | 83 ++++++ Model/ApplePayOrder.php | 249 ++++++++++++++++++ Model/ConfigProvider.php | 47 +++- Model/Generator.php | 106 ++++++-- etc/adminhtml/system/terminal1.xml | 5 + etc/adminhtml/system/terminal2.xml | 5 + etc/adminhtml/system/terminal3.xml | 5 + etc/adminhtml/system/terminal4.xml | 5 + etc/adminhtml/system/terminal5.xml | 5 + view/frontend/layout/checkout_index_index.xml | 3 + .../layout/sdmaltapay_index_applepay.xml | 8 + view/frontend/web/js/action/set-payment.js | 45 ++-- .../method-renderer/terminal-abstract.js | 143 +++++++++- .../web/template/payment/terminal.html | 2 +- 17 files changed, 881 insertions(+), 59 deletions(-) create mode 100644 Controller/Index/ApplePay.php create mode 100644 Controller/Index/ApplePayResponse.php create mode 100644 Controller/Index/Cancel.php create mode 100644 Model/ApplePayOrder.php create mode 100644 view/frontend/layout/sdmaltapay_index_applepay.xml diff --git a/CHANGELOG.md b/CHANGELOG.md index d53717a0..c9180a49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to this project will be documented in this file. - Make text "No saved credit cards" translatable - Add a button to trigger the sync of the terminals with the gateway - Add configurations section to setup cron scheduler to change the status of the pending order to cancel +- Add support for Apple Pay **Fixes** - Cancel order issues when there is no transaction diff --git a/Controller/Index/ApplePay.php b/Controller/Index/ApplePay.php new file mode 100644 index 00000000..08dd6277 --- /dev/null +++ b/Controller/Index/ApplePay.php @@ -0,0 +1,122 @@ +storeConfig = $storeConfig; + $this->systemConfig = $systemConfig; + $this->_storeManager = $storeManager; + $this->_urlInterface = $urlInterface; + } + + /** + * Dispatch request + * + * @return \Magento\Framework\Controller\ResultInterface|ResponseInterface + * @throws \Magento\Framework\Exception\NotFoundException + */ + /** + * @inheritDoc + */ + public function createCsrfValidationException( + RequestInterface $request + ): ?InvalidRequestException { + return null; + } + + /** + * @inheritDoc + */ + public function validateForCsrf(RequestInterface $request): ?bool + { + return true; + } + + /** + * @return void + */ + public function execute() + { + $storeCode = $this->getStoreCode(); + $validationUrl = $this->getRequest()->getParam('validationUrl'); + $terminalName = $this->getRequest()->getParam('termminalid'); + $currentUrl = $this->_urlInterface->getBaseUrl(); + $domain = parse_url($currentUrl, PHP_URL_HOST); + $auth = $this->systemConfig->getAuth($storeCode); + $api = new TestAuthentication($auth); + $response = $api->call(); + if (!$response) { + return false; + } + $request = new CardWalletSession($auth); + $request->setTerminal($terminalName) + ->setValidationUrl($validationUrl) + ->setDomain($domain); + + $response = $request->call(); + if ($response->Result === 'Success') { + echo json_encode($response->ApplePaySession); + } + } + + /** + * Get Store code + * + * @return string + */ + public function getStoreCode() + { + return $this->_storeManager->getStore()->getCode(); + } +} \ No newline at end of file diff --git a/Controller/Index/ApplePayResponse.php b/Controller/Index/ApplePayResponse.php new file mode 100644 index 00000000..7f6f9ed5 --- /dev/null +++ b/Controller/Index/ApplePayResponse.php @@ -0,0 +1,106 @@ +_checkoutSession = $checkoutSession; + $this->gateway = $gateway; + $this->redirectFactory = $redirectFactory; + $this->order = $order; + $this->random = $random; + $this->_orderRepository = $orderRepository; + } + + /** + * Dispatch request + * + * @return \Magento\Framework\Controller\ResultInterface|ResponseInterface + * @throws \Magento\Framework\Exception\NotFoundException + */ + /** + * @inheritDoc + */ + public function createCsrfValidationException( + RequestInterface $request + ): ?InvalidRequestException { + return null; + } + + /** + * @inheritDoc + */ + public function validateForCsrf(RequestInterface $request): ?bool + { + return true; + } + + public function execute() + { + $orderId = $this->_checkoutSession->getLastOrderId(); + if ($this->checkPost()) { + $params = $this->gateway->createRequestApplepay( + $this->getRequest()->getParam('paytype'), + $orderId, + $this->getRequest()->getParam('providerData') + ); + + echo json_encode($params); + } + } + + /** + * @return mixed + */ + public function checkPost() + { + return $this->getRequest()->isPost(); + } + +} \ No newline at end of file diff --git a/Controller/Index/Cancel.php b/Controller/Index/Cancel.php new file mode 100644 index 00000000..fa2998fa --- /dev/null +++ b/Controller/Index/Cancel.php @@ -0,0 +1,83 @@ +_checkoutSession = $checkoutSession; + $this->order = $order; + $this->paymentHandler = $paymentHandler; + } + + /** + * @inheritDoc + */ + public function createCsrfValidationException( + RequestInterface $request + ): ?InvalidRequestException { + return null; + } + + /** + * @inheritDoc + */ + public function validateForCsrf(RequestInterface $request): ?bool + { + return true; + } + + /** + * @return void + */ + public function execute() + { + $orderId = $this->_checkoutSession->getLastOrderId(); + $order = $this->order->load($orderId); + $this->paymentHandler->setCustomOrderStatus($order, Order::STATE_CANCELED, 'cancel'); + $order->addStatusHistoryComment("ApplePay payment status - ". $order->getStatus()); + $order->setIsNotified(false); + $order->getResource()->save($order); + } +} \ No newline at end of file diff --git a/Model/ApplePayOrder.php b/Model/ApplePayOrder.php new file mode 100644 index 00000000..2009c356 --- /dev/null +++ b/Model/ApplePayOrder.php @@ -0,0 +1,249 @@ +orderLoader = $orderLoader; + $this->checkoutSession = $checkoutSession; + $this->stockItem = $stockItem; + $this->stockRegistry = $stockRegistry; + $this->transactionRepository = $transactionRepository; + $this->systemConfig = $systemConfig; + $this->order = $order; + $this->paymentHandler = $paymentHandler; + $this->transactionFactory = $transactionFactory; + } + + /** + * @param $comment + * @param RequestInterface $request + * + * @throws AlreadyExistsException + */ + public function handleCardWalletPayment($response, $order) + { + $max_date = ''; + $latestTransKey = ''; + foreach ($response->Transactions as $key=>$value) { + if ($value->CreatedDate > $max_date) { + $max_date = $value->CreatedDate; + $latestTransKey = $key; + } + } + if ($response && $response->Result === 'Success' && isset($response->Transactions[$latestTransKey])) { + $transaction = $response->Transactions[$latestTransKey]; + $paymentType = $transaction->AuthType; + $responseStatus = $transaction->TransactionStatus; + $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; + $storeCode = $order->getStore()->getCode(); + if ($order->getId()) { + $cardType = ''; + $expires = ''; + //Update stock quantity + if($order->getState() == 'canceled') { + $this->updateStockQty($order); + } + $this->resetCanceledQty($order); + if (isset($transaction->CreditCardExpiry->Month) && isset($transaction->CreditCardExpiry->Year)) { + $expires = $transaction->CreditCardExpiry->Month . '/' . $transaction->CreditCardExpiry->Year; + } + if (isset($transaction->PaymentSchemeName)) { + $cardType = $transaction->PaymentSchemeName; + } + $payment = $order->getPayment(); + $payment->setPaymentId($transaction->PaymentId); + $payment->setLastTransId($transaction->TransactionId); + $payment->setCcTransId($transaction->CreditCardToken); + $payment->setAdditionalInformation('cc_token', $transaction->CreditCardToken); + $payment->setAdditionalInformation('expires', $expires); + $payment->setAdditionalInformation('card_type', $cardType); + $payment->setAdditionalInformation('payment_type', $paymentType); + $payment->save(); + //save transaction data + $parametersData = null; + $transactionData = json_encode($response); + $this->transactionRepository->addTransactionData( + $order->getIncrementId(), + $transaction->TransactionId, + $transaction->PaymentId, + $transactionData, + $parametersData + ); + $orderStatusAfterPayment = $this->systemConfig->getStatusConfig('process', $storeScope, $storeCode); + $orderStatusCapture = $this->systemConfig->getStatusConfig('autocapture', $storeScope, $storeCode); + $setOrderStatus = true; + $orderState = Order::STATE_PROCESSING; + $statusKey = 'process'; + + if ($this->isCaptured($response, $storeCode, $storeScope, $latestTransKey) && $orderStatusCapture == "complete") { + if ($this->orderLines->sendShipment($order)) { + $orderState = Order::STATE_COMPLETE; + $statusKey = 'autocapture'; + $order->addStatusHistoryComment(__(ConstantConfig::PAYMENT_COMPLETE)); + } else { + $setOrderStatus = false; + $order->addStatusToHistory($orderStatusCapture, ConstantConfig::PAYMENT_COMPLETE, false); + } + } else { + if ($orderStatusAfterPayment) { + $orderState = $orderStatusAfterPayment; + } + } + if ($setOrderStatus) { + $this->paymentHandler->setCustomOrderStatus($order, $orderState, $statusKey); + } + $order->addStatusHistoryComment("ApplePay Status: ". $response->Result); + $order->setIsNotified(false); + $order->getResource()->save($order); + + } + } else { + $this->paymentHandler->setCustomOrderStatus($order, Order::STATE_CANCELED, 'cancel'); + $order->addStatusHistoryComment("Order status: ". $response->Result); + $order->setIsNotified(false); + $order->getResource()->save($order); + } + } + + public function sortFunction($a, $b) { + return strtotime($b["date"]) - strtotime($a["date"]); + } + + protected function updateStockQty($order) + { + $cart = $this->modelCart; + $quoteItems = $this->checkoutSession->getQuote()->getItemsCollection(); + foreach ($order->getAllItems() as $item) { + $stockQty = $this->stockItem->getStockQty($item->getProductId(), $item->getStore()->getWebsiteId()); + $qty = $stockQty - $item->getQtyOrdered(); + $stockItem = $this->stockRegistry->getStockItemBySku($item['sku']); + $stockItem->setQty($qty); + $stockItem->setIsInStock((bool)$qty); + $this->stockRegistry->updateStockItemBySku($item['sku'], $stockItem); + } + foreach($quoteItems as $item) + { + $cart->removeItem($item->getId())->save(); + } + } + + /** + * @param $order + * + * @return void + */ + public function resetCanceledQty($order) { + foreach ($order->getAllItems() as $item) { + if ($item->getQtyCanceled() > 0) { + $item->setQtyCanceled($item->getQtyToCancel()); + $item->save(); + } + } + } + /** + * @param $response + * @param $storeCode + * @param $storeScope + * + * @return bool|\Magento\Payment\Model\MethodInterface + */ + private function isCaptured($response, $storeCode, $storeScope, $latestTransKey) + { + $isCaptured = false; + foreach (SystemConfig::getTerminalCodes() as $terminalName) { + $terminalConfig = $this->systemConfig->getTerminalConfigFromTerminalName( + $terminalName, + 'terminalname', + $storeScope, + $storeCode + ); + if ($terminalConfig === $response->Transactions[$latestTransKey]->Terminal) { + $isCaptured = $this->systemConfig->getTerminalConfigFromTerminalName( + $terminalName, + 'capture', + $storeScope, + $storeCode + ); + break; + } + } + + return $isCaptured; + } + +} \ No newline at end of file diff --git a/Model/ConfigProvider.php b/Model/ConfigProvider.php index 7055a751..286c977e 100755 --- a/Model/ConfigProvider.php +++ b/Model/ConfigProvider.php @@ -2,7 +2,7 @@ /** * Altapay Module for Magento 2.x. * - * Copyright © 2020 Altapay. All rights reserved. + * Copyright © 2018 Altapay. All rights reserved. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ @@ -13,23 +13,26 @@ use Magento\Framework\Escaper; use Magento\Framework\UrlInterface; use Magento\Payment\Helper\Data; -use Altapay\Api\Test\TestAuthentication; -use Altapay\Api\Test\TestConnection; -use Magento\Store\Model\ScopeInterface; +use SDM\Altapay\Api\Test\TestAuthentication; +use SDM\Altapay\Api\Test\TestConnection; use SDM\Altapay\Model\SystemConfig; -use Altapay\Authentication; +use SDM\Altapay\Authentication; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Payment\Model\Config; use Magento\Payment\Model\Config\Source\Allmethods; use Magento\Framework\View\Asset\Repository; use SDM\Altapay\Model\TokenFactory; use Magento\Customer\Model\Session; -use Magento\Payment\Model\MethodInterface; +use Magento\Checkout\Model\Session as CheckoutSession; +use Magento\Store\Model\StoreManagerInterface; class ConfigProvider implements ConfigProviderInterface { const CODE = 'sdm_altapay'; + protected $_checkoutSession; + + protected $_storeManager; /** * @var Data */ @@ -89,7 +92,9 @@ public function __construct( ScopeConfigInterface $scopeConfig, Repository $assetRepository, TokenFactory $dataToken, - Session $customerSession + Session $customerSession, + CheckoutSession $checkoutSession, + StoreManagerInterface $storeManager ) { $this->data = $data; $this->escaper = $escaper; @@ -100,6 +105,8 @@ public function __construct( $this->assetRepository = $assetRepository; $this->dataToken = $dataToken; $this->customerSession = $customerSession; + $this->_checkoutSession = $checkoutSession; + $this->_storeManager = $storeManager; } /** @@ -111,7 +118,12 @@ public function getConfig() { $store = null; $activePaymentMethod = $this->getActivePaymentMethod(); - + $getCurrentQuote = $this->_checkoutSession->getQuote(); + $config = []; + $baseUrl = $this->_storeManager->getStore()->getBaseUrl(); + $grandTotal = $getCurrentQuote->getGrandTotal(); + $countryCode = $this->scopeConfig->getValue('general/country/default', + \Magento\Store\Model\ScopeInterface::SCOPE_STORE); return [ 'payment' => [ self::CODE => [ @@ -120,7 +132,11 @@ public function getConfig() ), 'auth' => $this->checkAuth(), 'connection' => $this->checkConn(), - 'terminaldata' => $activePaymentMethod + 'terminaldata' => $activePaymentMethod, + 'grandTotalAmount' => $grandTotal, + 'countryCode' => $countryCode, + 'currencyCode' => $this->_storeManager->getStore()->getBaseCurrencyCode(), + 'baseUrl' => $baseUrl ] ] ]; @@ -128,7 +144,7 @@ public function getConfig() public function getActivePaymentMethod() { - $storeScope = ScopeInterface::SCOPE_STORE; + $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; $storeCode = $this->systemConfig->resolveCurrentStoreCode(); $methods = []; $allPaymentMethod = $this->data->getPaymentMethods(); @@ -172,6 +188,8 @@ public function getActivePaymentMethod() } $showBoth = $this->scopeConfig->getValue($paymentCode . '/showlogoandtitle', $storeScope, $storeCode); $saveCardToken = $this->scopeConfig->getValue($paymentCode . '/savecardtoken', $storeScope, $storeCode); + $isApplePay = $this->scopeConfig->getValue($paymentCode . '/isapplepay', $storeScope, $storeCode); + if ($terminalStatus == 1) { $methods[$key] = [ 'label' => $label, @@ -180,7 +198,8 @@ public function getActivePaymentMethod() 'terminalstatus' => $terminalStatus, 'terminallogo' => $logoURL, 'showlogoandtitle' => $showBoth, - 'enabledsavetokens' => $saveCardToken + 'enabledsavetokens' => $saveCardToken, + 'isapplepay' => $isApplePay ]; if ($saveCardToken == 1 && !empty($savedTokenList)) { $methods[$key]['savedtokenlist'] = json_encode($savedTokenList); @@ -242,7 +261,7 @@ public function checkConn() } /** - * @return MethodInterface + * @return \Magento\Payment\Model\MethodInterface */ protected function getData() { @@ -250,7 +269,7 @@ protected function getData() } /** - * @param array $collection + * @param $collection * * @return string */ @@ -267,4 +286,4 @@ private function ccTokenPrimaryOption($collection) return $primaryOptionId; } -} +} \ No newline at end of file diff --git a/Model/Generator.php b/Model/Generator.php index 1d2d951c..28aa7bb4 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -36,8 +36,10 @@ use SDM\Altapay\Model\Handler\DiscountHandler; use SDM\Altapay\Model\Handler\CreatePaymentHandler; use SDM\Altapay\Model\TokenFactory; +use SDM\Altapay\Model\ApplePayOrder; use Magento\Sales\Model\OrderFactory; use Altapay\Response\PaymentRequestResponse; +use Altapay\Api\Payments\CardWalletAuthorize; use Magento\Payment\Model\MethodInterface; use Magento\Checkout\Model\Cart; use Magento\CatalogInventory\Api\StockStateInterface; @@ -179,7 +181,8 @@ public function __construct( TokenFactory $dataToken, StockStateInterface $stockItem, StockRegistryInterface $stockRegistry, - Cart $modelCart + Cart $modelCart, + ApplePayOrder $applePayOrder ) { $this->quote = $quote; $this->urlInterface = $urlInterface; @@ -199,9 +202,10 @@ public function __construct( $this->discountHandler = $discountHandler; $this->paymentHandler = $paymentHandler; $this->dataToken = $dataToken; - $this->stockItem = $stockItem; - $this->stockRegistry = $stockRegistry; - $this->modelCart = $modelCart; + $this->stockItem = $stockItem; + $this->stockRegistry = $stockRegistry; + $this->modelCart = $modelCart; + $this->applePayOrder = $applePayOrder; } /** @@ -229,7 +233,7 @@ public function createRequest($terminalId, $orderId) if (!empty($this->fixedProductTax($order))) { $orderLines[] = $this->orderLines->fixedProductTaxOrderLine($this->fixedProductTax($order)); } - $request = $this->preparePaymentRequest($order, $orderLines, $orderId, $terminalId); + $request = $this->preparePaymentRequest($order, $orderLines, $orderId, $terminalId, null); if ($request) { return $this->sendPaymentRequest($order, $request); } @@ -439,6 +443,8 @@ private function completeCheckout($comment, RequestInterface $request) $requireCapture = $response->requireCapture; $paymentStatus = strtolower($response->paymentStatus); $responseStatus = $response->status; + $max_date = ''; + $latestTransKey = ''; if ($paymentStatus === 'released') { $this->handleCancelStatusAction($request, $responseStatus); @@ -449,6 +455,12 @@ private function completeCheckout($comment, RequestInterface $request) $order = $this->loadOrderFromCallback($response); $storeScope = ScopeInterface::SCOPE_STORE; $storeCode = $order->getStore()->getCode(); + foreach ($response->Transactions as $key=>$value) { + if ($value->CreatedDate > $max_date) { + $max_date = $value->CreatedDate; + $latestTransKey = $key; + } + } if ($order->getId()) { $cardType = ''; $expires = ''; @@ -457,8 +469,8 @@ private function completeCheckout($comment, RequestInterface $request) $this->updateStockQty($order); } $this->resetCanceledQty($order); - if (isset($response->Transactions[0])) { - $transaction = $response->Transactions[0]; + if (isset($response->Transactions[$latestTransKey])) { + $transaction = $response->Transactions[$latestTransKey]; if (isset($transaction->CreditCardExpiry->Month) && isset($transaction->CreditCardExpiry->Year)) { $expires = $transaction->CreditCardExpiry->Month . '/' . $transaction->CreditCardExpiry->Year; } @@ -487,7 +499,7 @@ private function completeCheckout($comment, RequestInterface $request) $orderState = Order::STATE_PROCESSING; $statusKey = 'process'; - if ($this->isCaptured($response, $storeCode, $storeScope)) { + if ($this->isCaptured($response, $storeCode, $storeScope, $latestTransKey)) { if ($orderStatusCapture == "complete") { if ($this->orderLines->sendShipment($order)) { $orderState = Order::STATE_COMPLETE; @@ -698,9 +710,9 @@ private function restoreOrderAndReturnError($order) * @param $orderId * @param $terminalId * - * @return mixed + * @return bool|PaymentRequest|CardWalletAuthorize */ - private function preparePaymentRequest($order, $orderLines, $orderId, $terminalId) + private function preparePaymentRequest($order, $orderLines, $orderId, $terminalId, $providerData) { $storeScope = $this->storeConfig->getStoreScope(); $storeCode = $order->getStore()->getCode(); @@ -712,9 +724,14 @@ private function preparePaymentRequest($order, $orderLines, $orderId, $terminalI return false; } $terminalName = $this->systemConfig->getTerminalConfig($terminalId, 'terminalname', $storeScope, $storeCode); + $isApplePay = $this->systemConfig->getTerminalConfig($terminalId, 'isapplepay', $storeScope, $storeCode); //Transaction Info $transactionDetail = $this->helper->transactionDetail($orderId); $request = new PaymentRequest($auth); + if ($isApplePay) { + $request = new CardWalletAuthorize($auth); + $request->setProviderData($providerData); + } $request->setTerminal($terminalName) ->setShopOrderId($order->getIncrementId()) ->setAmount((float)number_format($order->getGrandTotal(), 2, '.', '')) @@ -723,7 +740,7 @@ private function preparePaymentRequest($order, $orderLines, $orderId, $terminalI ->setConfig($this->setConfig()) ->setTransactionInfo($transactionDetail) ->setSalesTax((float)number_format($order->getTaxAmount(), 2, '.', '')) - ->setCookie($_SERVER['HTTP_COOKIE']); + ->setCookie($this->request->getServer('HTTP_COOKIE')); $post = $this->request->getPostValue(); @@ -818,7 +835,7 @@ private function sendPaymentRequest($order, $request) * * @return bool|MethodInterface */ - private function isCaptured($response, $storeCode, $storeScope) + private function isCaptured($response, $storeCode, $storeScope, $latestTransKey) { $isCaptured = false; foreach (SystemConfig::getTerminalCodes() as $terminalName) { @@ -828,7 +845,7 @@ private function isCaptured($response, $storeCode, $storeScope) $storeScope, $storeCode ); - if ($terminalConfig === $response->Transactions[0]->Terminal) { + if ($terminalConfig === $response->Transactions[$latestTransKey]->Terminal) { $isCaptured = $this->systemConfig->getTerminalConfigFromTerminalName( $terminalName, 'capture', @@ -932,7 +949,7 @@ public function checkAvsConfig($response, $storeCode, $storeScope, $configField) $storeScope, $storeCode ); - if ($terminalConfig === $response->Transactions[0]->Terminal) { + if ($terminalConfig === $response->Transactions[$this->getLatestTransaction($response)]->Terminal) { $isEnabled = $this->systemConfig->getTerminalConfigFromTerminalName( $terminalName, $configField, @@ -963,7 +980,7 @@ public function getAcceptedAvsResults($response, $storeCode, $storeScope) $storeScope, $storeCode ); - if ($terminalConfig === $response->Transactions[0]->Terminal) { + if ($terminalConfig === $response->Transactions[$this->getLatestTransaction($response)]->Terminal) { $acceptedAvsResults = $this->systemConfig->getTerminalConfigFromTerminalName( $terminalName, 'avs_acceptance', @@ -1002,4 +1019,63 @@ public function resetCanceledQty($order) { } } } + + public function getLatestTransaction($response) { + $max_date = ''; + $latestTransKey = ''; + foreach ($response->Transactions as $key=>$value) { + if ($value->CreatedDate > $max_date) { + $max_date = $value->CreatedDate; + $latestTransKey = $key; + } + } + return $latestTransKey; + } + /** + * @param $terminalId + * @param $orderId + * @param $providerData + * + * @return mixed + */ + public function createRequestApplepay($terminalId, $orderId, $providerData) + { + $storeScope = $this->storeConfig->getStoreScope(); + $order = $this->order->load($orderId); + $storeCode = $order->getStore()->getCode(); + if ($order->getId()) { + $couponCode = $order->getDiscountDescription(); + $couponCodeAmount = $order->getDiscountAmount(); + $discountAllItems = $this->discountHandler->allItemsHaveDiscount($order->getAllItems()); + $orderLines = $this->itemOrderLines($couponCodeAmount, $order, $discountAllItems); + if ($this->orderLines->sendShipment($order) && !empty($order->getShippingMethod(true))) { + $orderLines[] = $this->orderLines->handleShipping($order, $discountAllItems, true); + //Shipping Discount Tax Compensation Amount + $compAmount = $this->discountHandler->hiddenTaxDiscountCompensation($order, $discountAllItems, true); + if ($compAmount > 0 && $discountAllItems == false) { + $orderLines[] = $this->orderLines->compensationOrderLine( + "Shipping compensation", + "comp-ship", + $compAmount + ); + } + } + if ($discountAllItems && abs($couponCodeAmount) > 0) { + $orderLines[] = $this->orderLines->discountOrderLine($couponCodeAmount, $couponCode); + } + if(!empty($this->fixedProductTax($order))){ + $orderLines[] = $this->orderLines->fixedProductTaxOrderLine($this->fixedProductTax($order)); + } + $request = $this->preparePaymentRequest($order, $orderLines, $orderId, $terminalId, $providerData); + if ($request) { + $response = $request->call(); + $this->applePayOrder->handleCardWalletPayment($response, $order); + + return $response; + } + } + + return $this->restoreOrderAndReturnError($order); + } + } diff --git a/etc/adminhtml/system/terminal1.xml b/etc/adminhtml/system/terminal1.xml index 6b1b5e96..a5c5b145 100755 --- a/etc/adminhtml/system/terminal1.xml +++ b/etc/adminhtml/system/terminal1.xml @@ -28,6 +28,11 @@ SDM\Altapay\Model\Config\Source\Terminals altapay-terminal-name + + + Magento\Config\Model\Config\Source\Yesno + payment/terminal1/isapplepay + Force the language of the payment page diff --git a/etc/adminhtml/system/terminal2.xml b/etc/adminhtml/system/terminal2.xml index bb95a85b..c1489df9 100755 --- a/etc/adminhtml/system/terminal2.xml +++ b/etc/adminhtml/system/terminal2.xml @@ -28,6 +28,11 @@ SDM\Altapay\Model\Config\Source\Terminals altapay-terminal-name + + + Magento\Config\Model\Config\Source\Yesno + payment/terminal2/isapplepay + Force the language of the payment page diff --git a/etc/adminhtml/system/terminal3.xml b/etc/adminhtml/system/terminal3.xml index c793b9bb..6765758c 100755 --- a/etc/adminhtml/system/terminal3.xml +++ b/etc/adminhtml/system/terminal3.xml @@ -28,6 +28,11 @@ SDM\Altapay\Model\Config\Source\Terminals altapay-terminal-name + + + Magento\Config\Model\Config\Source\Yesno + payment/terminal3/isapplepay + Force the language of the payment page diff --git a/etc/adminhtml/system/terminal4.xml b/etc/adminhtml/system/terminal4.xml index e13906f9..52b5fd19 100755 --- a/etc/adminhtml/system/terminal4.xml +++ b/etc/adminhtml/system/terminal4.xml @@ -28,6 +28,11 @@ SDM\Altapay\Model\Config\Source\Terminals altapay-terminal-name + + + Magento\Config\Model\Config\Source\Yesno + payment/terminal4/isapplepay + Force the language of the payment page diff --git a/etc/adminhtml/system/terminal5.xml b/etc/adminhtml/system/terminal5.xml index 0092404d..0773935b 100755 --- a/etc/adminhtml/system/terminal5.xml +++ b/etc/adminhtml/system/terminal5.xml @@ -28,6 +28,11 @@ SDM\Altapay\Model\Config\Source\Terminals altapay-terminal-name + + + Magento\Config\Model\Config\Source\Yesno + payment/terminal5/isapplepay + Force the language of the payment page diff --git a/view/frontend/layout/checkout_index_index.xml b/view/frontend/layout/checkout_index_index.xml index 0e8761d7..891c82d7 100755 --- a/view/frontend/layout/checkout_index_index.xml +++ b/view/frontend/layout/checkout_index_index.xml @@ -10,6 +10,9 @@ --> + + + diff --git a/view/frontend/layout/sdmaltapay_index_applepay.xml b/view/frontend/layout/sdmaltapay_index_applepay.xml new file mode 100644 index 00000000..7fb1b25f --- /dev/null +++ b/view/frontend/layout/sdmaltapay_index_applepay.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/view/frontend/web/js/action/set-payment.js b/view/frontend/web/js/action/set-payment.js index 524a88ae..7f625ca0 100755 --- a/view/frontend/web/js/action/set-payment.js +++ b/view/frontend/web/js/action/set-payment.js @@ -61,26 +61,33 @@ define( tokenId = $(".payment-method._active select[name='ccToken']").val(); } - $.ajax({ - method: "POST", - url: window.checkoutConfig.payment['sdm_altapay'].url, - data: { - paytype: method, - cartid: quote.getQuoteId(), - orderid: data, - tokenid: tokenId - }, - dataType: 'json' - }).done(function (jsonResponse) { - if (jsonResponse.result == 'success') { - window.location.href = jsonResponse.formurl; - } else { - fullScreenLoader.stopLoader(); - $(".payment-method._active").find('#altapay-error-message').css('display', 'block'); - $(".payment-method._active").find('#altapay-error-message').text(jsonResponse.message); - return false; + var paymentMethod = window.checkoutConfig.payment['sdm_altapay'].terminaldata; + for (var obj in paymentMethod) { + if (obj === paymentData.method) { + if(paymentMethod[obj].isapplepay !== '1' ) { + $.ajax({ + method: "POST", + url: window.checkoutConfig.payment['sdm_altapay'].url, + data: { + paytype: method, + cartid: quote.getQuoteId(), + orderid: data, + tokenid: tokenId + }, + dataType: 'json' + }).done(function (jsonResponse) { + if (jsonResponse.result == 'success') { + window.location.href = jsonResponse.formurl; + } else { + fullScreenLoader.stopLoader(); + $(".payment-method._active").find('#altapay-error-message').css('display', 'block'); + $(".payment-method._active").find('#altapay-error-message').text(jsonResponse.message); + return false; + } + }); + } } - }); + } }).fail(function (response) { errorProcessor.process(response, messageContainer); fullScreenLoader.stopLoader(); diff --git a/view/frontend/web/js/view/payment/method-renderer/terminal-abstract.js b/view/frontend/web/js/view/payment/method-renderer/terminal-abstract.js index ec3d3a25..f16a1350 100755 --- a/view/frontend/web/js/view/payment/method-renderer/terminal-abstract.js +++ b/view/frontend/web/js/view/payment/method-renderer/terminal-abstract.js @@ -1,7 +1,7 @@ /** * Altapay Module for Magento 2.x. * - * Copyright © 2020 Altapay. All rights reserved. + * Copyright © 2018 Altapay. All rights reserved. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ @@ -14,9 +14,10 @@ define( 'jquery', 'Magento_Checkout/js/view/payment/default', 'Magento_Customer/js/customer-data', - 'SDM_Altapay/js/action/set-payment' + 'SDM_Altapay/js/action/set-payment', + 'Magento_Checkout/js/action/redirect-on-success' ], - function ($, Component, storage, Action) { + function ($, Component, storage, Action, redirectOnSuccessAction) { 'use strict'; return Component.extend({ @@ -28,6 +29,15 @@ define( redirectAfterPlaceOrder: false, placeOrder: function () { + var self = this; + var paymentMethod = window.checkoutConfig.payment['sdm_altapay'].terminaldata; + for (var obj in paymentMethod) { + if (obj === self.getCode()) { + if(paymentMethod[obj].isapplepay === '1' ) { + this.onApplePayButtonClicked(); + } + } + } $('#altapay-error-message').text(''); var auth = window.checkoutConfig.payment[this.getDefaultCode()].auth; var connection = window.checkoutConfig.payment[this.getDefaultCode()].connection; @@ -50,17 +60,18 @@ define( var self = this; var terminalname; var paymentMethod = window.checkoutConfig.payment[this.getDefaultCode()].terminaldata; + var isSafari = (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)); for (var obj in paymentMethod) { if (obj === self.getCode()) { - if (paymentMethod[obj].terminallogo != "" && paymentMethod[obj].showlogoandtitle == false) { + if ((paymentMethod[obj].terminallogo != "" && paymentMethod[obj].showlogoandtitle == false) || (paymentMethod[obj].isapplepay ==1 && isSafari === false)) { terminalname = ""; } else { if (paymentMethod[obj].terminalname != " ") { - if (paymentMethod[obj].label != null) { - terminalname = paymentMethod[obj].label - } else { - terminalname = paymentMethod[obj].terminalname; - } + if (paymentMethod[obj].label != null) { + terminalname = paymentMethod[obj].label + } else { + terminalname = paymentMethod[obj].terminalname; + } } } } @@ -81,6 +92,118 @@ define( } }, + onApplePayButtonClicked: function() { + var configData = window.checkoutConfig.payment[this.getDefaultCode()]; + var baseurl = configData.baseUrl; + + if (!ApplePaySession) { + return; + } + + // Define ApplePayPaymentRequest + const request = { + "countryCode": configData.countryCode, + "currencyCode": configData.currencyCode, + "merchantCapabilities": [ + "supports3DS" + ], + "supportedNetworks": [ + "visa", + "masterCard", + "amex", + "discover" + ], + "total": { + "label": "Demo (Card is not charged)", + "type": "final", + "amount": configData.grandTotalAmount + } + }; + + // Create ApplePaySession + const session = new ApplePaySession(3, request); + + session.onvalidatemerchant = async event => { + var url = baseurl+"sdmaltapay/index/applepay"; + // Call your own server to request a new merchant session. + $.ajax({ + url: url, + data: { + validationUrl: event.validationURL, + termminalid: this.terminalName() + }, + type: 'post', + dataType: 'JSON', + success: function(response) { + var responsedata = jQuery.parseJSON(response); + session.completeMerchantValidation(responsedata); + } + }); + }; + + session.onpaymentmethodselected = event => { + let total = { + "label": "AltaPay ApplePay Charge", + "type": "final", + "amount": configData.grandTotalAmount + } + + const update = { "newTotal": total }; + session.completePaymentMethodSelection(update); + }; + + session.onshippingmethodselected = event => { + // Define ApplePayShippingMethodUpdate based on the selected shipping method. + // No updates or errors are needed, pass an empty object. + const update = {}; + session.completeShippingMethodSelection(update); + }; + + session.onshippingcontactselected = event => { + // Define ApplePayShippingContactUpdate based on the selected shipping contact. + const update = {}; + session.completeShippingContactSelection(update); + }; + + session.onpaymentauthorized = event => { + var method = this.terminal.substr(this.terminal.indexOf(" ") + 1); + var url = baseurl + "sdmaltapay/index/applepayresponse"; + $.ajax({ + url: url, + data: { + providerData: JSON.stringify(event.payment.token), + paytype: method + }, + type: 'post', + dataType: 'JSON', + complete: function(response) { + var status; + var responsestatus = response.responseJSON.Result.toLowerCase(); + if (responsestatus === 'success') { + status = ApplePaySession.STATUS_SUCCESS; + session.completePayment(status); + redirectOnSuccessAction.execute(); + } else { + status = ApplePaySession.STATUS_FAILURE; + session.completePayment(status); + } + } + }); + }; + session.oncancel = event => { + var url = baseurl + "sdmaltapay/index/cancel"; + $.ajax({ + url: url, + type: 'post', + success: function(data, status, xhr) { + window.location.reload(); + } + }); + + }; + + session.begin(); + }, getDefaultCode: function () { return 'sdm_altapay'; }, @@ -132,4 +255,4 @@ define( } }); } -); +); \ No newline at end of file diff --git a/view/frontend/web/template/payment/terminal.html b/view/frontend/web/template/payment/terminal.html index 04254861..91ce0d37 100755 --- a/view/frontend/web/template/payment/terminal.html +++ b/view/frontend/web/template/payment/terminal.html @@ -7,7 +7,7 @@ * file that was distributed with this source code. */ --> -
+
Date: Fri, 26 Aug 2022 18:03:21 +0500 Subject: [PATCH 16/31] Support tax exclusive configurations. --- CHANGELOG.md | 1 + Model/Generator.php | 7 +---- Model/Handler/DiscountHandler.php | 9 +++++- Model/Handler/PriceHandler.php | 41 ++++++++++----------------- Observer/CaptureObserver.php | 11 ++----- Observer/CreditmemoRefundObserver.php | 10 ++----- 6 files changed, 31 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c9180a49..c0f0d6ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ All notable changes to this project will be documented in this file. - Order status set to "closed" despite the orders being in a pre-auth state. - Order status set to "closed" for "Vipps" payment method - Incorrect discount calculation +- Support tax exclusive configurations. ## [2.0.5] **Fixes** diff --git a/Model/Generator.php b/Model/Generator.php index 28aa7bb4..9ec947db 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -599,7 +599,7 @@ public function fixedProductTax($order) $weeTaxAmount = 0; foreach ($order->getAllItems() as $item) { - $weeTaxAmount += $item->getWeeeTaxAppliedRowAmount(); + $weeTaxAmount += $item->getWeeeTaxAppliedRowAmount(); } return $weeTaxAmount; @@ -637,7 +637,6 @@ private function itemOrderLines($couponCodeAmount, $order, $discountAllItems) $unitPrice = bcdiv($unitPriceWithoutTax, 1, 2); } else { $unitPrice = $productOriginalPrice; - $unitPriceWithoutTax = $productOriginalPrice; } $dataForPrice = $this->priceHandler->dataForPrice( $item, @@ -666,12 +665,8 @@ private function itemOrderLines($couponCodeAmount, $order, $discountAllItems) $roundingCompensation = $this->priceHandler->compensationAmountCal( $item, $unitPrice, - $unitPriceWithoutTax, $taxAmount, $discount, - $couponCodeAmount, - $catalogDiscount, - $storePriceIncTax, true ); // check if rounding compensation amount, send in the separate orderline diff --git a/Model/Handler/DiscountHandler.php b/Model/Handler/DiscountHandler.php index a73a45c9..6ff7c6d4 100644 --- a/Model/Handler/DiscountHandler.php +++ b/Model/Handler/DiscountHandler.php @@ -176,6 +176,7 @@ public function getItemDiscountInformation( ) { $rowTotal = $item->getRowTotal()-$item->getDiscountAmount()+$item->getTaxAmount()+$item->getDiscountTaxCompensationAmount(); $discount = ['discount' => 0, 'catalogDiscount' => false]; + $originalPriceWithTax = $originalPrice + $taxAmount; if ($discountAmount && $originalPrice == $priceInclTax) { $discountAmount = ($discountAmount * 100) / ($originalPrice * $quantity); } elseif ($originalPrice > 0 && $originalPrice > $priceInclTax && empty($discountAmount)) { @@ -183,7 +184,13 @@ public function getItemDiscountInformation( $discountAmount = $this->catalogDiscount($originalPrice, $priceInclTax); } elseif ($originalPrice > 0 && $originalPrice > $priceInclTax && $discountAmount) { $discount['catalogDiscount'] = true; - $discountAmount = $this->combinationDiscount($originalPrice, $rowTotal); + if (!$this->storeConfig->storePriceIncTax()) { + $discountAmount = $originalPriceWithTax - $rowTotal; + $discountPercentage = ($discountAmount * 100) / $originalPriceWithTax; + $discountAmount = $discountPercentage; + } else { + $discountAmount = $this->combinationDiscount($originalPrice, $rowTotal); + } } $discount['discount'] = $this->orderLineDiscount($discountOnAllItems, $discountAmount, $discount['catalogDiscount']); diff --git a/Model/Handler/PriceHandler.php b/Model/Handler/PriceHandler.php index f5124132..59e191f2 100644 --- a/Model/Handler/PriceHandler.php +++ b/Model/Handler/PriceHandler.php @@ -64,11 +64,18 @@ public function dataForPrice($item, $unitPrice, $couponAmount, $itemDiscount, $d } if ($originalPrice > $price && abs((float)$couponAmount) > 0 && !$discountAllItems) { $originalPrice = $originalPrice * $quantity; + $originalPriceWithTax = $originalPrice + $data["taxAmount"]; $data["catalogDiscount"] = true; - $data["discount"] = $this->discountHandler->combinationDiscount($originalPrice, $rowTotal); + if (!$this->storeConfig->storePriceIncTax()) { + $discountAmount = $originalPriceWithTax - $rowTotal; + $discountPercentage = ($discountAmount * 100) / $originalPriceWithTax; + $data["discount"] = $discountPercentage; + } else { + $data["discount"] = $this->discountHandler->combinationDiscount($originalPrice, $rowTotal); + } } else if ($originalPrice > $price && !(float)$couponAmount) { $data["catalogDiscount"] = true; - $data["discount"] = $this->discountHandler->catalogDiscount($originalPrice, $price); + $data["discount"] = $this->discountHandler->catalogDiscount($originalPrice, $price); } else { $data["discount"] = $itemDiscount; } @@ -118,38 +125,20 @@ public function getPriceWithoutTax($price, $taxPercentage) public function compensationAmountCal( $item, $unitPrice, - $unitPriceWithoutTax, $taxAmount, $discountedAmount, - $couponCodeAmount, - $catalogDiscountCheck, - $storePriceIncTax, - $newOrder, - $discountAllItems - ) { + $newOrder) + { if ($newOrder) { - $quantity = $item->getQtyOrdered(); - $taxPercent = $item->getTaxPercent(); + $quantity = $item->getQtyOrdered(); } else { - $quantity = $item->getQty(); - $taxPercent = $item->getOrderItem()->getTaxPercent(); + $quantity = $item->getQty(); } - - $compensation = 0; //Discount compensation calculation - Gateway calculation pattern $gatewaySubTotal = ($unitPrice * $quantity) + $taxAmount; $gatewaySubTotal = $gatewaySubTotal - ($gatewaySubTotal * ($discountedAmount / 100)); - // Magento calculation pattern - if ((abs((float)$couponCodeAmount) > 0 && $storePriceIncTax && !$catalogDiscountCheck && $discountAllItems) || (abs((float)$couponCodeAmount) > 0 && $catalogDiscountCheck)) { - $cmsPriceCal = $unitPriceWithoutTax * $quantity; - $cmsTaxCal = $cmsPriceCal * ($taxPercent / 100); - $cmsSubTotal = $cmsPriceCal + $cmsTaxCal; - $cmsSubTotal = $cmsSubTotal - ($cmsSubTotal * ($discountedAmount / 100)); - $compensation = $cmsSubTotal - $gatewaySubTotal; - } else { - $cmsSubTotal = $item->getRowTotal()-$item->getDiscountAmount()+$item->getTaxAmount()+$item->getDiscountTaxCompensationAmount(); - $compensation = $cmsSubTotal - $gatewaySubTotal; - } + $cmsSubTotal = $item->getRowTotal() - $item->getDiscountAmount() + $item->getTaxAmount() + $item->getDiscountTaxCompensationAmount(); + $compensation = $cmsSubTotal - $gatewaySubTotal; return $compensation; } diff --git a/Observer/CaptureObserver.php b/Observer/CaptureObserver.php index 032a2f89..5ca4a82c 100755 --- a/Observer/CaptureObserver.php +++ b/Observer/CaptureObserver.php @@ -181,7 +181,6 @@ private function itemOrderLines($couponCodeAmount, $invoice, $discountAllItems) } else { $price = $item->getPrice(); $unitPrice = $originalPrice; - $priceWithoutTax = $originalPrice; $taxAmount = $this->priceHandler->calculateTaxAmount($unitPrice, $taxPercent, $qty); } $itemDiscountInformation = $this->discountHandler->getItemDiscountInformation( @@ -190,10 +189,10 @@ private function itemOrderLines($couponCodeAmount, $invoice, $discountAllItems) $discountAmount, $qty, $discountAllItems, - $item + $item, + $taxAmount ); $discountedAmount = $itemDiscountInformation['discount']; - $catalogDiscountCheck = $itemDiscountInformation['catalogDiscount']; $orderLines[] = $this->orderLines->itemOrderLine( $item, $unitPrice, @@ -206,12 +205,8 @@ private function itemOrderLines($couponCodeAmount, $invoice, $discountAllItems) $roundingCompensation = $this->priceHandler->compensationAmountCal( $item, $unitPrice, - $priceWithoutTax, $taxAmount, $discountedAmount, - $couponCodeAmount, - $catalogDiscountCheck, - $storePriceIncTax, false ); // check if rounding compensation amount, send in the separate orderline @@ -320,7 +315,7 @@ public function fixedProductTax($invoice) $weeTaxAmount = 0; foreach ($invoice->getAllItems() as $item) { - $weeTaxAmount += $item->getWeeeTaxAppliedRowAmount(); + $weeTaxAmount += $item->getWeeeTaxAppliedRowAmount(); } return $weeTaxAmount; diff --git a/Observer/CreditmemoRefundObserver.php b/Observer/CreditmemoRefundObserver.php index cf51c4c5..df05f163 100755 --- a/Observer/CreditmemoRefundObserver.php +++ b/Observer/CreditmemoRefundObserver.php @@ -186,7 +186,6 @@ private function itemOrderLines($couponCodeAmount, $discountAllItems, $memo) } else { $price = $item->getPrice(); $unitPrice = $originalPrice; - $priceWithoutTax = $originalPrice; $taxAmount = $this->priceHandler->calculateTaxAmount($unitPrice, $taxPercent, $qty); } $itemDiscountInformation = $this->discountHandler->getItemDiscountInformation( @@ -195,7 +194,8 @@ private function itemOrderLines($couponCodeAmount, $discountAllItems, $memo) $discountAmount, $qty, $discountAllItems, - $item + $item, + $taxAmount ); if ($item->getPriceInclTax()) { $discountedAmount = $itemDiscountInformation['discount']; @@ -213,12 +213,8 @@ private function itemOrderLines($couponCodeAmount, $discountAllItems, $memo) $roundingCompensation = $this->priceHandler->compensationAmountCal( $item, $unitPrice, - $priceWithoutTax, $taxAmount, $discountedAmount, - $couponCodeAmount, - $catalogDiscount, - $storePriceIncTax, false ); //send the rounding mismatch value into separate orderline if any @@ -291,7 +287,7 @@ public function fixedProductTax($memo) $weeTaxAmount = 0; foreach ($memo->getAllItems() as $item) { - $weeTaxAmount += $item->getWeeeTaxAppliedRowAmount(); + $weeTaxAmount += $item->getWeeeTaxAppliedRowAmount(); } return $weeTaxAmount; From 3e5789bf4dac079c969b43d57a139d4968100347 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 18:09:05 +0500 Subject: [PATCH 17/31] Order status set to "pending" on "incomplete" response --- CHANGELOG.md | 3 ++- Controller/Index/Fail.php | 3 ++- Controller/Index/Notification.php | 1 + Observer/CaptureObserver.php | 2 +- Observer/CreditmemoRefundObserver.php | 2 +- view/frontend/web/css/ordersummary.css | 4 ++++ 6 files changed, 11 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c0f0d6ac..e2e8dccc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,8 @@ All notable changes to this project will be documented in this file. - Order status set to "closed" despite the orders being in a pre-auth state. - Order status set to "closed" for "Vipps" payment method - Incorrect discount calculation -- Support tax exclusive configurations. +- Support tax exclusive configurations +- Order status set to "pending" on "incomplete" response ## [2.0.5] **Fixes** diff --git a/Controller/Index/Fail.php b/Controller/Index/Fail.php index ab8c293d..5b79e75e 100755 --- a/Controller/Index/Fail.php +++ b/Controller/Index/Fail.php @@ -60,6 +60,7 @@ public function execute() break; case "failed": case "error": + case "incomplete": $this->generator->handleFailedStatusAction($this->getRequest(), $msg, $merchantError, $status); break; default: @@ -69,7 +70,7 @@ public function execute() $msg = $e->getMessage(); } - if ($status == 'failed' || $status == 'error' || $status == 'cancelled') { + if ($status == 'failed' || $status == 'error' || $status == 'cancelled' || $status == 'incomplete') { $resultRedirect = $this->prepareRedirect('checkout/cart', [], $msg); } else { $resultRedirect = $this->prepareRedirect('checkout', ['_fragment' => 'payment'], $msg); diff --git a/Controller/Index/Notification.php b/Controller/Index/Notification.php index 73f53ff3..96611303 100755 --- a/Controller/Index/Notification.php +++ b/Controller/Index/Notification.php @@ -84,6 +84,7 @@ private function handleNotification($status, $msg, $merchantError) break; case "error": case "failed": + case "incomplete": $this->generator->handleFailedStatusAction($this->getRequest(), $msg, $merchantError, $status); break; case "succeeded": diff --git a/Observer/CaptureObserver.php b/Observer/CaptureObserver.php index 5ca4a82c..8f275ed7 100755 --- a/Observer/CaptureObserver.php +++ b/Observer/CaptureObserver.php @@ -288,7 +288,7 @@ private function sendInvoiceRequest($invoice, $orderLines, $orderObject, $paymen $this->logger->info('Response body', json_decode($xml, true)); //Update comments if capture fail $xml = simplexml_load_string($body); - if ($xml->Body->Result == 'Error' || $xml->Body->Result == 'Failed') { + if ($xml->Body->Result == 'Error' || $xml->Body->Result == 'Failed' || $xml->Body->Result == 'Incomplete') { $orderObject->addStatusHistoryComment('Capture failed: ' . $xml->Body->MerchantErrorMessage) ->setIsCustomerNotified(false); $orderObject->getResource()->save($orderObject); diff --git a/Observer/CreditmemoRefundObserver.php b/Observer/CreditmemoRefundObserver.php index df05f163..b78ad819 100755 --- a/Observer/CreditmemoRefundObserver.php +++ b/Observer/CreditmemoRefundObserver.php @@ -266,7 +266,7 @@ private function sendRefundRequest($memo, $orderLines, $orderObject, $payment, $ //Update comments if refund fail $xml = simplexml_load_string($body); - if ($xml->Body->Result == 'Error' || $xml->Body->Result == 'Failed') { + if ($xml->Body->Result == 'Error' || $xml->Body->Result == 'Failed' || $xml->Body->Result == 'Incomplete') { $orderObject->addStatusHistoryComment('Refund failed: ' . $xml->Body->MerchantErrorMessage) ->setIsCustomerNotified(false); $orderObject->getResource()->save($orderObject); diff --git a/view/frontend/web/css/ordersummary.css b/view/frontend/web/css/ordersummary.css index 0950d02e..1375c342 100755 --- a/view/frontend/web/css/ordersummary.css +++ b/view/frontend/web/css/ordersummary.css @@ -22,6 +22,10 @@ input#pensioCreditCardPaymentSubmitButton { margin-bottom: 5%; } +#notice-cookie-block { + display: none; +} + select#emonth { width: 50%; } From 6f61700bc87f93e899acd53c638e7316f4f3c7d3 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Fri, 26 Aug 2022 18:15:55 +0500 Subject: [PATCH 18/31] Release stock qty on order cancellation --- CHANGELOG.md | 1 + Model/Generator.php | 3 +++ Observer/CheckoutCartIndex.php | 4 ++-- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2e8dccc..0e175b56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ All notable changes to this project will be documented in this file. - Incorrect discount calculation - Support tax exclusive configurations - Order status set to "pending" on "incomplete" response +- Release stock qty on order cancellation ## [2.0.5] **Fixes** diff --git a/Model/Generator.php b/Model/Generator.php index 9ec947db..49d9cd6e 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -407,6 +407,9 @@ public function handleOrderStateAction( $response = $callback->call(); if ($response) { $order = $this->loadOrderFromCallback($response); + if ($orderStatus === 'canceled') { + $order->cancel(); + } $order->setState($orderState); $order->setIsNotified(false); if ($transactionInfo !== null) { diff --git a/Observer/CheckoutCartIndex.php b/Observer/CheckoutCartIndex.php index 9014fde6..491dac9f 100755 --- a/Observer/CheckoutCartIndex.php +++ b/Observer/CheckoutCartIndex.php @@ -225,12 +225,12 @@ public function verifyIfOrderStatus($orderStatusConfigBefore, $currentOrderStatu public function revertOrderQty($order) { foreach ($order->getAllItems() as $item) { - $item->setQtyCanceled($item['qty_ordered']); - $item->save(); $qty = $item->getQtyOrdered() - max($item->getQtyShipped(), $item->getQtyInvoiced()) - $item->getQtyCanceled(); if ($item->getId() && $item->getProductId() && empty($item->getChildrenItems()) && $qty) { $this->stockManagement->backItemQty($item->getProductId(), $qty, $item->getStore()->getWebsiteId()); } + $item->setQtyCanceled($item['qty_ordered']); + $item->save(); $this->priceIndexer->reindexRow($item->getProductId()); } } From 306ff2b8b519b2aa6a76e2be0ee8e0bfbade7d25 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Mon, 29 Aug 2022 09:58:18 +0500 Subject: [PATCH 19/31] Add configuration field for "ApplePay popup label" --- CHANGELOG.md | 1 + Model/ConfigProvider.php | 26 +++++----- etc/adminhtml/system/terminal1.xml | 7 ++- etc/adminhtml/system/terminal2.xml | 7 ++- etc/adminhtml/system/terminal3.xml | 7 ++- etc/adminhtml/system/terminal4.xml | 7 ++- etc/adminhtml/system/terminal5.xml | 7 ++- .../method-renderer/terminal-abstract.js | 49 ++++++++++++++----- .../web/template/payment/terminal.html | 2 +- 9 files changed, 84 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e175b56..93874cc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project will be documented in this file. - Add a button to trigger the sync of the terminals with the gateway - Add configurations section to setup cron scheduler to change the status of the pending order to cancel - Add support for Apple Pay +- Support multiple logos/icons option for terminals. **Fixes** - Cancel order issues when there is no transaction diff --git a/Model/ConfigProvider.php b/Model/ConfigProvider.php index 286c977e..17afaf77 100755 --- a/Model/ConfigProvider.php +++ b/Model/ConfigProvider.php @@ -182,14 +182,15 @@ public function getActivePaymentMethod() $terminalStatus = $this->scopeConfig->getValue($paymentCode . '/active', $storeScope, $storeCode); $terminalLogo = $this->scopeConfig->getValue($paymentCode . '/terminallogo', $storeScope, $storeCode); if (!empty($terminalLogo)) { - $logoURL = $this->getLogoFilePath($terminalLogo); + $logoURL = $this->getLogoPath($terminalLogo); } else { $logoURL = ''; } $showBoth = $this->scopeConfig->getValue($paymentCode . '/showlogoandtitle', $storeScope, $storeCode); $saveCardToken = $this->scopeConfig->getValue($paymentCode . '/savecardtoken', $storeScope, $storeCode); $isApplePay = $this->scopeConfig->getValue($paymentCode . '/isapplepay', $storeScope, $storeCode); - + $applePayLabel = $this->scopeConfig->getValue($paymentCode . '/applepaylabel', $storeScope, $storeCode); + if ($terminalStatus == 1) { $methods[$key] = [ 'label' => $label, @@ -199,7 +200,8 @@ public function getActivePaymentMethod() 'terminallogo' => $logoURL, 'showlogoandtitle' => $showBoth, 'enabledsavetokens' => $saveCardToken, - 'isapplepay' => $isApplePay + 'isapplepay' => $isApplePay, + 'applepaylabel' => $applePayLabel ]; if ($saveCardToken == 1 && !empty($savedTokenList)) { $methods[$key]['savedtokenlist'] = json_encode($savedTokenList); @@ -216,16 +218,18 @@ public function getActivePaymentMethod() * * @return mixed|null */ - public function getLogoFilePath($name) + public function getLogoPath($name) { - $fileId = 'SDM_Altapay::images/' . $name . '.png'; - $params = ['area' => 'frontend']; - $asset = $this->assetRepository->createAsset($fileId, $params); - try { - return $asset->getUrl(); - } catch (\Exception $e) { - return null; + $path = []; + $terminalLogo = explode(",",$name); + foreach ($terminalLogo as $logoName) { + $fileId = 'SDM_Altapay::images/' . $logoName . '.png'; + $params = ['area' => 'frontend']; + $asset = $this->assetRepository->createAsset($fileId, $params); + $path[] = $asset->getUrl(); } + + return $path; } public function checkAuth() diff --git a/etc/adminhtml/system/terminal1.xml b/etc/adminhtml/system/terminal1.xml index a5c5b145..0013bc20 100755 --- a/etc/adminhtml/system/terminal1.xml +++ b/etc/adminhtml/system/terminal1.xml @@ -33,6 +33,11 @@ Magento\Config\Model\Config\Source\Yesno payment/terminal1/isapplepay + + + Add custom text for the Apple Pay popup label + payment/terminal1/applepaylabel + Force the language of the payment page @@ -45,7 +50,7 @@ Magento\Config\Model\Config\Source\Yesno payment/terminal1/capture -
From 898ff0961ff67348f72b36169bcdcfecaec1366d Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Mon, 29 Aug 2022 11:55:50 +0500 Subject: [PATCH 20/31] Remove unused classes --- Controller/Index.php | 1 + Controller/Index/ApplePay.php | 28 +------------------ Controller/Index/ApplePayResponse.php | 32 +++------------------- Controller/Index/Cancel.php | 22 +-------------- Model/ApplePayOrder.php | 39 +++++++++++++++------------ Model/Generator.php | 2 +- 6 files changed, 29 insertions(+), 95 deletions(-) diff --git a/Controller/Index.php b/Controller/Index.php index 5a469aef..4a637b89 100755 --- a/Controller/Index.php +++ b/Controller/Index.php @@ -16,6 +16,7 @@ use Magento\Quote\Model\Quote; use Magento\Sales\Model\Order; use Psr\Log\LoggerInterface; +use SDM\Altapay\Logger\Logger; use SDM\Altapay\Model\Generator; use Magento\Framework\Controller\Result\RedirectFactory; use Magento\Framework\Encryption\EncryptorInterface; diff --git a/Controller/Index/ApplePay.php b/Controller/Index/ApplePay.php index 08dd6277..c1abb9cf 100644 --- a/Controller/Index/ApplePay.php +++ b/Controller/Index/ApplePay.php @@ -16,14 +16,11 @@ use Magento\Framework\App\ResponseInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\App\Action\Action; -use Magento\Framework\App\CsrfAwareActionInterface; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\App\Request\InvalidRequestException; use Magento\Store\Model\StoreManagerInterface; use Magento\Framework\App\Action\Context; use Magento\Framework\UrlInterface; -class ApplePay extends Action implements CsrfAwareActionInterface +class ApplePay extends Action { /** * @var Helper Config @@ -60,29 +57,6 @@ public function __construct( $this->_urlInterface = $urlInterface; } - /** - * Dispatch request - * - * @return \Magento\Framework\Controller\ResultInterface|ResponseInterface - * @throws \Magento\Framework\Exception\NotFoundException - */ - /** - * @inheritDoc - */ - public function createCsrfValidationException( - RequestInterface $request - ): ?InvalidRequestException { - return null; - } - - /** - * @inheritDoc - */ - public function validateForCsrf(RequestInterface $request): ?bool - { - return true; - } - /** * @return void */ diff --git a/Controller/Index/ApplePayResponse.php b/Controller/Index/ApplePayResponse.php index 7f6f9ed5..b0f490e2 100644 --- a/Controller/Index/ApplePayResponse.php +++ b/Controller/Index/ApplePayResponse.php @@ -9,20 +9,17 @@ namespace SDM\Altapay\Controller\Index; -use SDM\Altapay\Model\Gateway; +use SDM\Altapay\Model\Generator; use Magento\Checkout\Model\Session; use Magento\Framework\App\ResponseInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\App\Action\Action; -use Magento\Framework\App\CsrfAwareActionInterface; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\App\Request\InvalidRequestException; use Magento\Framework\App\Action\Context; use Magento\Sales\Model\Order; use Magento\Framework\Controller\Result\RedirectFactory; use Magento\Framework\Math\Random; -class ApplePayResponse extends Action implements CsrfAwareActionInterface +class ApplePayResponse extends Action { /** * @var Order @@ -44,7 +41,7 @@ public function __construct( Context $context, Session $checkoutSession, Order $orderRepository, - Gateway $gateway, + Generator $gateway, RedirectFactory $redirectFactory, Order $order, Random $random @@ -58,29 +55,6 @@ public function __construct( $this->_orderRepository = $orderRepository; } - /** - * Dispatch request - * - * @return \Magento\Framework\Controller\ResultInterface|ResponseInterface - * @throws \Magento\Framework\Exception\NotFoundException - */ - /** - * @inheritDoc - */ - public function createCsrfValidationException( - RequestInterface $request - ): ?InvalidRequestException { - return null; - } - - /** - * @inheritDoc - */ - public function validateForCsrf(RequestInterface $request): ?bool - { - return true; - } - public function execute() { $orderId = $this->_checkoutSession->getLastOrderId(); diff --git a/Controller/Index/Cancel.php b/Controller/Index/Cancel.php index fa2998fa..32b40340 100644 --- a/Controller/Index/Cancel.php +++ b/Controller/Index/Cancel.php @@ -10,15 +10,12 @@ namespace SDM\Altapay\Controller\Index; use SDM\Altapay\Model\Handler\CreatePaymentHandler; -use Magento\Framework\App\CsrfAwareActionInterface; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\App\Request\InvalidRequestException; use Magento\Framework\App\Action\Context; use Magento\Checkout\Model\Session; use Magento\Framework\App\Action\Action; use Magento\Sales\Model\Order; -class Cancel extends Action implements CsrfAwareActionInterface +class Cancel extends Action { /** * @var Session @@ -51,23 +48,6 @@ public function __construct( $this->paymentHandler = $paymentHandler; } - /** - * @inheritDoc - */ - public function createCsrfValidationException( - RequestInterface $request - ): ?InvalidRequestException { - return null; - } - - /** - * @inheritDoc - */ - public function validateForCsrf(RequestInterface $request): ?bool - { - return true; - } - /** * @return void */ diff --git a/Model/ApplePayOrder.php b/Model/ApplePayOrder.php index 2009c356..483eaad1 100644 --- a/Model/ApplePayOrder.php +++ b/Model/ApplePayOrder.php @@ -9,11 +9,9 @@ namespace SDM\Altapay\Model; -use SDM\Altapay\Api\OrderLoaderInterface; use Magento\Checkout\Model\Session; use Magento\CatalogInventory\Api\StockStateInterface; use Magento\CatalogInventory\Api\StockRegistryInterface; -use SDM\Altapay\Api\TransactionRepositoryInterface; use SDM\Altapay\Model\SystemConfig; use Magento\Sales\Model\Order; use SDM\Altapay\Model\ConstantConfig; @@ -22,11 +20,6 @@ class ApplePayOrder { - /** - * @var OrderLoaderInterface - */ - private $orderLoader; - /** * @var Session */ @@ -42,11 +35,6 @@ class ApplePayOrder { */ private $stockRegistry; - /** - * @var TransactionRepositoryInterface - */ - private $transactionRepository; - /** * @var SystemConfig */ @@ -68,21 +56,17 @@ class ApplePayOrder { private $transactionFactory; public function __construct( - OrderLoaderInterface $orderLoader, Session $checkoutSession, StockStateInterface $stockItem, StockRegistryInterface $stockRegistry, - TransactionRepositoryInterface $transactionRepository, SystemConfig $systemConfig, Order $order, CreatePaymentHandler $paymentHandler, TransactionFactory $transactionFactory ) { - $this->orderLoader = $orderLoader; $this->checkoutSession = $checkoutSession; $this->stockItem = $stockItem; $this->stockRegistry = $stockRegistry; - $this->transactionRepository = $transactionRepository; $this->systemConfig = $systemConfig; $this->order = $order; $this->paymentHandler = $paymentHandler; @@ -137,7 +121,7 @@ public function handleCardWalletPayment($response, $order) //save transaction data $parametersData = null; $transactionData = json_encode($response); - $this->transactionRepository->addTransactionData( + $this->addTransactionData( $order->getIncrementId(), $transaction->TransactionId, $transaction->PaymentId, @@ -246,4 +230,25 @@ private function isCaptured($response, $storeCode, $storeScope, $latestTransKey) return $isCaptured; } + /** + * It creates the entity and saves the JSON request. + * + * @param string $orderid + * @param string $transactionid + * @param string $paymentid + * @param string $transactiondata + * @param string $parametersdata + */ + public function addTransactionData($orderid, $transactionid, $paymentid, $transactiondata, $parametersdata) + { + /** @var Transaction $transaction */ + $transaction = $this->transactionFactory->create(); + $transaction->setOrderid($orderid); + $transaction->setTransactionid($transactionid); + $transaction->setPaymentid($paymentid); + $transaction->setTransactiondata($transactiondata); + $transaction->setParametersdata($parametersdata); + $transaction->getResource()->save($transaction); + } + } \ No newline at end of file diff --git a/Model/Generator.php b/Model/Generator.php index 49d9cd6e..c3ee0b72 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -249,7 +249,7 @@ public function createRequest($terminalId, $orderId) */ public function restoreOrderFromOrderId($orderId) { - $order = $this->orderLoader->getOrderByOrderIncrementId($orderId); + $order = $this->loadOrderFromCallback($orderId); if ($order->getId()) { $quote = $this->quote->loadByIdWithoutStore($order->getQuoteId()); $quote->setIsActive(1)->setReservedOrderId(null); From 3e52349a9c0d3cb2c6b4fb378612ba063e90f194 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Mon, 29 Aug 2022 15:09:02 +0500 Subject: [PATCH 21/31] Version update --- etc/module.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/module.xml b/etc/module.xml index 62d3814e..920dbb3b 100755 --- a/etc/module.xml +++ b/etc/module.xml @@ -10,6 +10,6 @@ --> - + From 251619e40e000dd73bb2c94c5d2f609846002b4b Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Mon, 29 Aug 2022 16:49:03 +0500 Subject: [PATCH 22/31] Fix typo --- etc/adminhtml/system/terminal1.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/adminhtml/system/terminal1.xml b/etc/adminhtml/system/terminal1.xml index 0013bc20..04ba526d 100755 --- a/etc/adminhtml/system/terminal1.xml +++ b/etc/adminhtml/system/terminal1.xml @@ -70,7 +70,7 @@ altapay-terminal-token-control - + Address Verification System Magento\Config\Model\Config\Source\Yesno payment/terminal1/avscontrol From d5220dcef8cd50eddbd6a9ffc6b4913c2d338c1b Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Mon, 29 Aug 2022 17:54:16 +0500 Subject: [PATCH 23/31] Add missing CronConfig file --- Model/Config/CronConfig.php | 117 ++++++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 Model/Config/CronConfig.php diff --git a/Model/Config/CronConfig.php b/Model/Config/CronConfig.php new file mode 100644 index 00000000..3ec8e061 --- /dev/null +++ b/Model/Config/CronConfig.php @@ -0,0 +1,117 @@ +_runModelPath = $runModelPath; + $this->_configValueFactory = $configValueFactory; + $this->scopeConfig = $scopeConfig; + parent::__construct($context, $registry, $scopeConfig, $cacheTypeList, $resource, $resourceCollection, $data); + } + + /** + * @return mixed + * @throws \Exception + */ + public function afterSave() + { + $time = $this->getData('groups/sdm_altapay_config/groups/cronScheduled/fields/time/value'); + $frequency = $this->getData('groups/sdm_altapay_config/groups/cronScheduled/fields/frequency/value'); + $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; + $cronEnabled = $this->scopeConfig->getValue(self::CRON_ENABLED, $storeScope); + try + { + if($cronEnabled) { + $cronExprArray = [ + intval($time[1]), //Minute + intval($time[0]), //Hour + $frequency == \Magento\Cron\Model\Config\Source\Frequency::CRON_MONTHLY ? '1' : '*', + '*', + $frequency == \Magento\Cron\Model\Config\Source\Frequency::CRON_WEEKLY ? '1' : '*', + ]; + $cronExprString = join(' ', $cronExprArray); + + $this->_configValueFactory->create()->load( + self::CRON_STRING_PATH, + 'path' + )->setValue( + $cronExprString + )->setPath( + self::CRON_STRING_PATH + )->save(); + $this->_configValueFactory->create()->load( + self::CRON_MODEL_PATH, + 'path' + )->setValue( + $this->_runModelPath + )->setPath( + self::CRON_MODEL_PATH + )->save(); + } + } + catch (\Exception $e) + { + throw new \Exception(__('Something went wrong, Can\'t save the cron expression.')); + } + return parent::afterSave(); + } + } \ No newline at end of file From 9deba14482bb122b25e575c6cee2877a136c61d8 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Tue, 30 Aug 2022 16:48:02 +0500 Subject: [PATCH 24/31] Fix typo and update dependency classes path --- Controller/Index.php | 3 +-- Controller/Index/ApplePay.php | 2 +- Model/ConfigProvider.php | 4 ++-- Model/Generator.php | 14 ++++++++++---- Model/Handler/DiscountHandler.php | 3 ++- Observer/CaptureObserver.php | 2 +- 6 files changed, 17 insertions(+), 11 deletions(-) diff --git a/Controller/Index.php b/Controller/Index.php index 4a637b89..009ce687 100755 --- a/Controller/Index.php +++ b/Controller/Index.php @@ -16,7 +16,6 @@ use Magento\Quote\Model\Quote; use Magento\Sales\Model\Order; use Psr\Log\LoggerInterface; -use SDM\Altapay\Logger\Logger; use SDM\Altapay\Model\Generator; use Magento\Framework\Controller\Result\RedirectFactory; use Magento\Framework\Encryption\EncryptorInterface; @@ -73,7 +72,7 @@ public function __construct( Quote $quote, Session $checkoutSession, Generator $generator, - Logger $altapayLogger, + LoggerInterface $logger, EncryptorInterface $encryptor, Random $random, RedirectFactory $redirectFactory diff --git a/Controller/Index/ApplePay.php b/Controller/Index/ApplePay.php index c1abb9cf..703995bb 100644 --- a/Controller/Index/ApplePay.php +++ b/Controller/Index/ApplePay.php @@ -10,7 +10,7 @@ namespace SDM\Altapay\Controller\Index; use SDM\Altapay\Model\SystemConfig; -use SDM\Altapay\Api\Test\TestAuthentication; +use Altapay\Api\Test\TestAuthentication; use SDM\Altapay\Api\Payments\CardWalletSession; use SDM\Altapay\Helper\Config as storeConfig; use Magento\Framework\App\ResponseInterface; diff --git a/Model/ConfigProvider.php b/Model/ConfigProvider.php index 17afaf77..ec4fbddf 100755 --- a/Model/ConfigProvider.php +++ b/Model/ConfigProvider.php @@ -13,8 +13,8 @@ use Magento\Framework\Escaper; use Magento\Framework\UrlInterface; use Magento\Payment\Helper\Data; -use SDM\Altapay\Api\Test\TestAuthentication; -use SDM\Altapay\Api\Test\TestConnection; +use Altapay\Api\Test\TestAuthentication; +use Altapay\Api\Test\TestConnection; use SDM\Altapay\Model\SystemConfig; use SDM\Altapay\Authentication; use Magento\Framework\App\Config\ScopeConfigInterface; diff --git a/Model/Generator.php b/Model/Generator.php index c3ee0b72..1f4c0458 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -44,6 +44,7 @@ use Magento\Checkout\Model\Cart; use Magento\CatalogInventory\Api\StockStateInterface; use Magento\CatalogInventory\Api\StockRegistryInterface; +use Psr\Log\LoggerInterface; /** * Class Generator @@ -51,6 +52,10 @@ */ class Generator { + /** + * @var LoggerInterface + */ + protected $logger; /** * @var Helper Data */ @@ -182,7 +187,8 @@ public function __construct( StockStateInterface $stockItem, StockRegistryInterface $stockRegistry, Cart $modelCart, - ApplePayOrder $applePayOrder + ApplePayOrder $applePayOrder, + LoggerInterface $logger ) { $this->quote = $quote; $this->urlInterface = $urlInterface; @@ -206,6 +212,7 @@ public function __construct( $this->stockRegistry = $stockRegistry; $this->modelCart = $modelCart; $this->applePayOrder = $applePayOrder; + $this->logger = $logger; } /** @@ -645,7 +652,7 @@ private function itemOrderLines($couponCodeAmount, $order, $discountAllItems) $item, $unitPrice, $couponCodeAmount, - $this->discountHandler->getItemDiscount($discountAmount, $originalPrice, $item->getQtyOrdered()), + $this->discountHandler->getItemDiscount($discountAmount, $productOriginalPrice, $item->getQtyOrdered()), $discountAllItems ); $taxAmount = $dataForPrice["taxAmount"]; @@ -662,8 +669,7 @@ private function itemOrderLines($couponCodeAmount, $order, $discountAllItems) $discount, $itemTaxAmount, $order, - true, - $discountAllItems + true ); $roundingCompensation = $this->priceHandler->compensationAmountCal( $item, diff --git a/Model/Handler/DiscountHandler.php b/Model/Handler/DiscountHandler.php index 6ff7c6d4..9a8b8a89 100644 --- a/Model/Handler/DiscountHandler.php +++ b/Model/Handler/DiscountHandler.php @@ -172,7 +172,8 @@ public function getItemDiscountInformation( $discountAmount, $quantity, $discountOnAllItems, - $item + $item, + $taxAmount ) { $rowTotal = $item->getRowTotal()-$item->getDiscountAmount()+$item->getTaxAmount()+$item->getDiscountTaxCompensationAmount(); $discount = ['discount' => 0, 'catalogDiscount' => false]; diff --git a/Observer/CaptureObserver.php b/Observer/CaptureObserver.php index 8f275ed7..38833040 100755 --- a/Observer/CaptureObserver.php +++ b/Observer/CaptureObserver.php @@ -184,7 +184,7 @@ private function itemOrderLines($couponCodeAmount, $invoice, $discountAllItems) $taxAmount = $this->priceHandler->calculateTaxAmount($unitPrice, $taxPercent, $qty); } $itemDiscountInformation = $this->discountHandler->getItemDiscountInformation( - $$totalPrice, + $totalPrice, $price, $discountAmount, $qty, From 5ffa1bded72dbedc799acb5eb75ff3280f901bfa Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Thu, 1 Sep 2022 13:28:40 +0500 Subject: [PATCH 25/31] Fix logo src path --- view/frontend/web/template/payment/terminal.html | 2 ++ 1 file changed, 2 insertions(+) diff --git a/view/frontend/web/template/payment/terminal.html b/view/frontend/web/template/payment/terminal.html index 2c14514b..b563f223 100755 --- a/view/frontend/web/template/payment/terminal.html +++ b/view/frontend/web/template/payment/terminal.html @@ -17,8 +17,10 @@
From cb3628499f99cd3455b7b3d9a6df2f3d38832984 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Thu, 1 Sep 2022 17:31:32 +0500 Subject: [PATCH 26/31] Fix order id issue --- Model/Generator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Model/Generator.php b/Model/Generator.php index 1f4c0458..a0b13559 100755 --- a/Model/Generator.php +++ b/Model/Generator.php @@ -256,7 +256,7 @@ public function createRequest($terminalId, $orderId) */ public function restoreOrderFromOrderId($orderId) { - $order = $this->loadOrderFromCallback($orderId); + $order = $this->orderFactory->create()->loadByIncrementId($orderId); if ($order->getId()) { $quote = $this->quote->loadByIdWithoutStore($order->getQuoteId()); $quote->setIsActive(1)->setReservedOrderId(null); From 3a83b00d0a44d25a390083c9939b2a42608e8f72 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Mon, 5 Sep 2022 14:19:43 +0500 Subject: [PATCH 27/31] Update namespace for Api classes --- Controller/Adminhtml/System/Config/Button.php | 2 +- Controller/Index/ApplePay.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Controller/Adminhtml/System/Config/Button.php b/Controller/Adminhtml/System/Config/Button.php index a555513d..e5dbaaa2 100644 --- a/Controller/Adminhtml/System/Config/Button.php +++ b/Controller/Adminhtml/System/Config/Button.php @@ -16,7 +16,7 @@ use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Store\Model\StoreManagerInterface; -use SDM\Altapay\Api\Others\Terminals; +use Altapay\Api\Others\Terminals; use SDM\Altapay\Model\SystemConfig; use Magento\Config\Model\ResourceModel\Config; use Magento\Framework\App\Config\ScopeConfigInterface; diff --git a/Controller/Index/ApplePay.php b/Controller/Index/ApplePay.php index 703995bb..9c0f577c 100644 --- a/Controller/Index/ApplePay.php +++ b/Controller/Index/ApplePay.php @@ -11,7 +11,7 @@ use SDM\Altapay\Model\SystemConfig; use Altapay\Api\Test\TestAuthentication; -use SDM\Altapay\Api\Payments\CardWalletSession; +use Altapay\Api\Payments\CardWalletSession; use SDM\Altapay\Helper\Config as storeConfig; use Magento\Framework\App\ResponseInterface; use Magento\Framework\Controller\ResultFactory; From 4e2aab9be4509ccbce21b824807d17bfd5ff129a Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Mon, 5 Sep 2022 14:20:39 +0500 Subject: [PATCH 28/31] Remove undeclared parameter from the method --- Observer/CreditmemoRefundObserver.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Observer/CreditmemoRefundObserver.php b/Observer/CreditmemoRefundObserver.php index b78ad819..7cdd85a0 100755 --- a/Observer/CreditmemoRefundObserver.php +++ b/Observer/CreditmemoRefundObserver.php @@ -206,8 +206,7 @@ private function itemOrderLines($couponCodeAmount, $discountAllItems, $memo) $discountedAmount, $taxAmount, $memo->getOrder(), - false, - $discountAllItems + false ); // Gateway and cms rounding amount $roundingCompensation = $this->priceHandler->compensationAmountCal( From 3a567ff9f4192970be859108d1f1be767c6a811f Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Mon, 5 Sep 2022 14:21:10 +0500 Subject: [PATCH 29/31] Make a text translatable --- view/frontend/templates/saved_credit_card.phtml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/view/frontend/templates/saved_credit_card.phtml b/view/frontend/templates/saved_credit_card.phtml index 8b8f5495..6e6cc851 100644 --- a/view/frontend/templates/saved_credit_card.phtml +++ b/view/frontend/templates/saved_credit_card.phtml @@ -58,5 +58,5 @@ if ($collection->getSize() > 0) { -
No saved credit cards.
+
escapeHtml(__('No saved credit cards.')); ?>
From e359f5ae6f6154adfac2561956754cb8a8fdbe4f Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Wed, 7 Sep 2022 12:02:52 +0500 Subject: [PATCH 30/31] Remove custom logs and use magento logs --- Controller/Index/Failmessage.php | 2 +- Logger/Handler.php | 26 ----------- Logger/Logger.php | 78 -------------------------------- 3 files changed, 1 insertion(+), 105 deletions(-) delete mode 100755 Logger/Handler.php delete mode 100755 Logger/Logger.php diff --git a/Controller/Index/Failmessage.php b/Controller/Index/Failmessage.php index 8a48dfb7..54547be5 100755 --- a/Controller/Index/Failmessage.php +++ b/Controller/Index/Failmessage.php @@ -28,7 +28,7 @@ public function execute() { $this->writeLog(); $msg = $this->getRequest()->getParam('msg'); - $this->altapayLogger->addDebugLog('messageManager - Error message', $msg); + $this->logger->debug('messageManager - Error message: ' . $msg); $this->messageManager->addErrorMessage($msg); return $this->_redirect('checkout', ['_fragment' => 'payment']); diff --git a/Logger/Handler.php b/Logger/Handler.php deleted file mode 100755 index 16c939a5..00000000 --- a/Logger/Handler.php +++ /dev/null @@ -1,26 +0,0 @@ -addInfo($type . ': ' . json_encode($data)); - } elseif (is_object($data)) { - $this->addInfo($type . ': ' . json_encode($data)); - } else { - $this->addInfo($type . ': ' . $data); - } - } - - /** - * @param $type - * @param $data - */ - public function addErrorLog($type, $data) - { - if (is_array($data)) { - $this->addError($type . ': ' . json_encode($data)); - } elseif (is_object($data)) { - $this->addError($type . ': ' . json_encode($data)); - } else { - $this->addError($type . ': ' . $data); - } - } - - /** - * @param $type - * @param $data - */ - public function addCriticalLog($type, $data) - { - if (is_array($data)) { - $this->addCritical($type . ': ' . json_encode($data)); - } elseif (is_object($data)) { - $this->addCritical($type . ': ' . json_encode($data)); - } else { - $this->addCritical($type . ': ' . $data); - } - } - - /** - * @param $type - * @param $data - */ - public function addDebugLog($type, $data) - { - if (is_array($data)) { - $this->addCritical($type . ': ' . json_encode($data)); - } elseif (is_object($data)) { - $this->addCritical($type . ': ' . json_encode($data)); - } else { - $this->addCritical($type . ': ' . $data); - } - } -} From ec22f7483f9bd55aaf7b121ef2e85aad0a8b0d83 Mon Sep 17 00:00:00 2001 From: BushraAsif Date: Wed, 7 Sep 2022 12:03:11 +0500 Subject: [PATCH 31/31] Typo issue --- etc/adminhtml/system.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index e74ff92b..6f1e19c4 100755 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -43,7 +43,7 @@ 0 - You can find your Api Keys in your AltaPay Merchnat Account]]> + You can find your Api Keys in your AltaPay Merchnat Account]]> SDM\Altapay\Block\Adminhtml\Render\Version