Skip to content

Commit cb8cd50

Browse files
Release version 4.1.0
1 parent 658009e commit cb8cd50

File tree

26 files changed

+573
-133
lines changed

26 files changed

+573
-133
lines changed

Block/Adminhtml/System/Config/Form/Field/CBTAvailableCurrencies.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,47 @@
44

55
namespace Afterpay\Afterpay\Block\Adminhtml\System\Config\Form\Field;
66

7+
use Magento\Backend\Block\Template\Context;
8+
use Magento\Framework\Serialize\SerializerInterface;
9+
use Psr\Log\LoggerInterface;
10+
711
class CBTAvailableCurrencies extends \Magento\Config\Block\System\Config\Form\Field
812
{
13+
private $serializer;
14+
private $logger;
15+
16+
public function __construct(
17+
LoggerInterface $logger,
18+
SerializerInterface $serializer,
19+
Context $context,
20+
array $data = []
21+
) {
22+
$this->serializer = $serializer;
23+
$this->logger = $logger;
24+
parent::__construct($context, $data);
25+
}
26+
27+
protected function _renderValue(\Magento\Framework\Data\Form\Element\AbstractElement $element)
28+
{
29+
try {
30+
$CbtAvailableCurrencies = $this->serializer->unserialize($element->getValue());
31+
$newValue = '';
32+
if (!$CbtAvailableCurrencies) {
33+
return parent::_renderValue($element);
34+
}
35+
36+
foreach ($CbtAvailableCurrencies as $currencyCode => $currency) {
37+
$newValue .= $currencyCode . '(min:' . $currency['minimumAmount']['amount']
38+
. ',max:' . $currency['maximumAmount']['amount'] . ') ';
39+
}
40+
$element->setValue($newValue);
41+
} catch (\Exception $e) {
42+
$this->logger->critical($e);
43+
}
44+
45+
return parent::_renderValue($element);
46+
}
47+
948
public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
1049
{
1150
/** @phpstan-ignore-next-line */

Controller/Express/PlaceOrder.php

Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,20 @@
22

33
namespace Afterpay\Afterpay\Controller\Express;
44

5-
class PlaceOrder implements \Magento\Framework\App\Action\HttpPostActionInterface
6-
{
7-
const CANCELLED_STATUS = 'CANCELLED';
5+
use Afterpay\Afterpay\Controller\Payment\Capture;
6+
use Afterpay\Afterpay\Gateway\Config\Config;
7+
use Afterpay\Afterpay\Model\Payment\Capture\PlaceOrderProcessor;
8+
use Magento\Checkout\Model\Session;
9+
use Magento\Framework\App\Action\HttpPostActionInterface;
10+
use Magento\Framework\App\RequestInterface;
11+
use Magento\Framework\Controller\Result\JsonFactory;
12+
use Magento\Framework\Exception\LocalizedException;
13+
use Magento\Framework\Message\ManagerInterface;
14+
use Magento\Framework\UrlInterface;
15+
use Magento\Payment\Gateway\CommandInterface;
816

17+
class PlaceOrder implements HttpPostActionInterface
18+
{
919
private $request;
1020
private $messageManager;
1121
private $checkoutSession;
@@ -15,13 +25,13 @@ class PlaceOrder implements \Magento\Framework\App\Action\HttpPostActionInterfac
1525
private $syncCheckoutDataCommand;
1626

1727
public function __construct(
18-
\Magento\Framework\App\RequestInterface $request,
19-
\Magento\Framework\Message\ManagerInterface $messageManager,
20-
\Magento\Checkout\Model\Session $checkoutSession,
21-
\Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
22-
\Magento\Framework\UrlInterface $url,
23-
\Afterpay\Afterpay\Model\Payment\Capture\PlaceOrderProcessor $placeOrderProcessor,
24-
\Magento\Payment\Gateway\CommandInterface $syncCheckoutDataCommand
28+
RequestInterface $request,
29+
ManagerInterface $messageManager,
30+
Session $checkoutSession,
31+
JsonFactory $jsonFactory,
32+
UrlInterface $url,
33+
PlaceOrderProcessor $placeOrderProcessor,
34+
CommandInterface $syncCheckoutDataCommand
2535
) {
2636
$this->request = $request;
2737
$this->messageManager = $messageManager;
@@ -40,25 +50,29 @@ public function execute()
4050
$afterpayOrderToken = $this->request->getParam('orderToken');
4151
$status = $this->request->getParam('status');
4252

43-
if ($status === static::CANCELLED_STATUS) {
53+
if ($status === Capture::CHECKOUT_STATUS_CANCELLED) {
4454
return $jsonResult;
4555
}
4656

57+
if ($status !== Capture::CHECKOUT_STATUS_SUCCESS) {
58+
$errorMessage = (string)__('Afterpay payment is declined. Please select an alternative payment method.');
59+
$this->messageManager->addErrorMessage($errorMessage);
60+
61+
return $jsonResult->setData(['redirectUrl' => $this->url->getUrl('checkout/cart')]);
62+
}
63+
4764
try {
4865
$quote->getPayment()
49-
->setMethod(\Afterpay\Afterpay\Gateway\Config\Config::CODE)
66+
->setMethod(Config::CODE)
5067
->setAdditionalInformation('afterpay_express', true);
5168
$this->placeOrderProcessor->execute($quote, $this->syncCheckoutDataCommand, $afterpayOrderToken);
5269
} catch (\Throwable $e) {
53-
$errorMessage = $e instanceof \Magento\Framework\Exception\LocalizedException
70+
$errorMessage = $e instanceof LocalizedException
5471
? $e->getMessage()
55-
: (string)__('Afterpay payment declined. Please select an alternative payment method.');
72+
: (string)__('Afterpay payment is declined. Please select an alternative payment method.');
73+
$this->messageManager->addErrorMessage($errorMessage);
5674

57-
return $jsonResult->setData(['error' => $errorMessage, 'redirectUrl' => $this->url->getUrl(
58-
'checkout/cart',
59-
['_scope' => $quote->getStore()]
60-
)]
61-
);
75+
return $jsonResult->setData(['redirectUrl' => $this->url->getUrl('checkout/cart')]);
6276
}
6377

6478
return $jsonResult->setData(['redirectUrl' => $this->url->getUrl('checkout/onepage/success')]);

Gateway/Request/Checkout/CheckoutDataBuilder.php

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -101,18 +101,26 @@ protected function getItems(\Magento\Quote\Model\Quote $quote): array
101101

102102
foreach ($quoteItems as $item) {
103103
$productId = $item->getProduct()->getId();
104+
$amount = $isCBTCurrencyAvailable ? $item->getPriceInclTax() : $item->getBasePriceInclTax();
105+
$currencyCode = $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode();
106+
$qty = $item->getQty();
107+
$isIntQty = floor($qty) == $qty;
108+
if ($isIntQty) {
109+
$qty = (int)$item->getQty();
110+
} else {
111+
$amount *= $item->getQty();
112+
$qty = 1;
113+
}
104114

105115
$formattedItem = [
106116
'name' => $item->getName(),
107117
'sku' => $item->getSku(),
108-
'quantity' => $item->getQty(),
118+
'quantity' => $qty,
109119
'pageUrl' => $item->getProduct()->getProductUrl(),
110120
'categories' => [array_values($this->getQuoteItemCategoriesNames($item))],
111121
'price' => [
112-
'amount' => $this->formatPrice(
113-
$isCBTCurrencyAvailable ? $item->getPriceInclTax() : $item->getBasePriceInclTax()
114-
),
115-
'currency' => $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode()
122+
'amount' => $this->formatPrice($amount),
123+
'currency' => $currencyCode
116124
]
117125
];
118126

@@ -132,10 +140,7 @@ protected function getQuoteItemCategoriesNames(\Magento\Quote\Model\Quote\Item $
132140
/** @var \Magento\Catalog\Model\ResourceModel\AbstractCollection $categoryCollection */
133141
$categoryCollection = $item->getProduct()->getCategoryCollection();
134142
$itemCategories = $categoryCollection->addAttributeToSelect('name')->getItems();
135-
return array_map(
136-
function ($cat) {return $cat->getData('name');},
137-
$itemCategories
138-
);
143+
return array_map(static function ($cat) {return $cat->getData('name');}, $itemCategories);
139144
}
140145

141146
/**
@@ -146,11 +151,8 @@ protected function getItemsImages(array $items): array
146151
{
147152
$itemsImages = [];
148153
$searchCriteria = $this->searchCriteriaBuilder
149-
->addFilter(
150-
'entity_id',
151-
array_map(function ($item) {return $item->getProduct()->getId();}, $items),
152-
'in'
153-
)->create();
154+
->addFilter('entity_id', array_map(static function ($item) {return $item->getProduct()->getId();}, $items), 'in')
155+
->create();
154156
$products = $this->productRepository->getList($searchCriteria)->getItems();
155157

156158
foreach ($products as $product) {
@@ -184,13 +186,14 @@ protected function getShippingAmount(\Magento\Quote\Model\Quote $quote): ?array
184186
return null;
185187
}
186188
$isCBTCurrencyAvailable = $this->checkCBTCurrencyAvailability->checkByQuote($quote);
189+
$amount = $isCBTCurrencyAvailable
190+
? $quote->getShippingAddress()->getShippingAmount()
191+
: $quote->getShippingAddress()->getBaseShippingAmount();
192+
$currencyCode = $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode();
187193

188194
return [
189-
'amount' => $this->formatPrice($isCBTCurrencyAvailable
190-
? $quote->getShippingAddress()->getShippingAmount()
191-
: $quote->getShippingAddress()->getBaseShippingAmount()
192-
),
193-
'currency' => $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode()
195+
'amount' => $this->formatPrice($amount),
196+
'currency' => $currencyCode
194197
];
195198
}
196199

@@ -211,13 +214,16 @@ protected function getDiscounts(\Magento\Quote\Model\Quote $quote): ?array
211214
return null;
212215
}
213216
$isCBTCurrencyAvailable = $this->checkCBTCurrencyAvailability->checkByQuote($quote);
217+
$amount = $isCBTCurrencyAvailable
218+
? $quote->getDiscountAmount()
219+
: $quote->getBaseDiscountAmount();
220+
$currencyCode = $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode();
221+
214222
return [
215223
'displayName' => __('Discount'),
216224
'amount' => [
217-
'amount' => $this->formatPrice($isCBTCurrencyAvailable
218-
? $quote->getDiscountAmount()
219-
: $quote->getBaseDiscountAmount()),
220-
'currency' => $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode()
225+
'amount' => $this->formatPrice($amount),
226+
'currency' => $currencyCode
221227
]
222228
];
223229
}

Gateway/Response/Checkout/CheckoutItemsAmountValidationHandler.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ public function handle(array $handlingSubject, array $response)
3535
throw new \Magento\Framework\Exception\LocalizedException($invalidCartItemsExceptionMessage);
3636
}
3737
if ($item->getQty() != $responseItems[$itemIndex]['quantity']) {
38+
$qty = $item->getQty();
39+
$isIntQty = floor($qty) == $qty;
40+
if (!$isIntQty && $responseItems[$itemIndex]['quantity'] == 1) {
41+
$amount = $isCBTCurrency ? $item->getPriceInclTax() : $item->getBasePriceInclTax();
42+
if ($amount * $qty == $responseItems[$itemIndex]['price']['amount']) {
43+
continue;
44+
}
45+
}
3846
throw new \Magento\Framework\Exception\LocalizedException($invalidCartItemsExceptionMessage);
3947
}
4048
}

Gateway/Response/MerchantConfiguration/CBTAvailableCurrenciesConfigurationHandler.php

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,35 @@
22

33
namespace Afterpay\Afterpay\Gateway\Response\MerchantConfiguration;
44

5-
class CBTAvailableCurrenciesConfigurationHandler implements \Magento\Payment\Gateway\Response\HandlerInterface
5+
use Afterpay\Afterpay\Model\Config;
6+
use Magento\Payment\Gateway\Response\HandlerInterface;
7+
use Magento\Framework\Serialize\SerializerInterface;
8+
9+
class CBTAvailableCurrenciesConfigurationHandler implements HandlerInterface
610
{
711
private $config;
12+
private $serializer;
813

914
public function __construct(
10-
\Afterpay\Afterpay\Model\Config $config
15+
Config $config,
16+
SerializerInterface $serializer
1117
) {
1218
$this->config = $config;
19+
$this->serializer = $serializer;
1320
}
1421

1522
public function handle(array $handlingSubject, array $response): void
1623
{
1724
$websiteId = (int)$handlingSubject['websiteId'];
18-
$cbtAvailableCurrencies = [];
25+
$cbtAvailableCurrencies = '';
26+
1927
if (isset($response['CBT']['enabled']) &&
2028
isset($response['CBT']['limits']) &&
2129
is_array($response['CBT']['limits'])
2230
) {
23-
foreach ($response['CBT']['limits'] as $limit) {
24-
if (isset($limit['maximumAmount']['currency']) && isset($limit['maximumAmount']['amount'])) {
25-
$cbtAvailableCurrencies[] = $limit['maximumAmount']['currency'] . ':' . $limit['maximumAmount']['amount'];
26-
}
27-
}
31+
$cbtAvailableCurrencies = $this->serializer->serialize($response['CBT']['limits']);
2832
}
29-
$this->config->setCbtCurrencyLimits(implode(",", $cbtAvailableCurrencies), $websiteId);
33+
34+
$this->config->setCbtCurrencyLimits($cbtAvailableCurrencies, $websiteId);
3035
}
3136
}

Gateway/Validator/Method/CurrencyValidator.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public function __construct(
2020
public function validate(array $validationSubject): \Magento\Payment\Gateway\Validator\ResultInterface
2121
{
2222
$quote = $this->checkoutSession->getQuote();
23-
$currentCurrency = $quote->getQuoteCurrencyCode();
23+
$currentCurrency = $quote->getStore()->getCurrentCurrencyCode();
2424
$allowedCurrencies = $this->config->getAllowedCurrencies();
2525
$cbtCurrencies = array_keys($this->config->getCbtCurrencyLimits());
2626

Model/Checks/IsCBTAvailable.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public function checkByQuote(\Magento\Quote\Model\Quote $quote): bool
3030
return $this->canUseCurrentCurrency;
3131
}
3232

33-
$currentCurrencyCode = $quote->getQuoteCurrencyCode();
33+
$currentCurrencyCode = $quote->getQuoteCurrencyCode() ?? $quote->getStore()->getCurrentCurrencyCode();
3434
$amount = (float) $quote->getGrandTotal();
3535
$this->canUseCurrentCurrency = $this->check($currentCurrencyCode, $amount);
3636

0 commit comments

Comments
 (0)