Skip to content

Commit ea33c5f

Browse files
Release version 5.0.1
1 parent 7ce79e0 commit ea33c5f

38 files changed

+455
-130
lines changed

Block/Adminhtml/System/Config/Fieldset/Payment.php renamed to Block/Adminhtml/System/Config/Fieldset/AllowedByCountry.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22

33
namespace Afterpay\Afterpay\Block\Adminhtml\System\Config\Fieldset;
44

5-
class Payment extends \Magento\Config\Block\System\Config\Form\Fieldset
5+
class AllowedByCountry extends \Magento\Config\Block\System\Config\Form\Fieldset
66
{
77
private \Magento\Payment\Model\MethodInterface $afterpay;
88
private \Afterpay\Afterpay\Model\Config $config;
9+
private string $allowedCountriesConfigPath;
910

1011
public function __construct(
1112
\Magento\Backend\Block\Context $context,
@@ -14,16 +15,18 @@ public function __construct(
1415
\Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer,
1516
\Magento\Payment\Model\MethodInterface $afterpay,
1617
\Afterpay\Afterpay\Model\Config $config,
18+
string $allowedCountriesConfigPath = '',
1719
array $data = []
1820
) {
1921
parent::__construct($context, $authSession, $jsHelper, $data, $secureRenderer);
2022
$this->afterpay = $afterpay;
2123
$this->config = $config;
24+
$this->allowedCountriesConfigPath = $allowedCountriesConfigPath;
2225
}
2326

2427
public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element): string
2528
{
26-
$allowedMerchantCountries = explode(',', $this->afterpay->getConfigData('allowed_merchant_countries'));
29+
$allowedMerchantCountries = explode(',', $this->afterpay->getConfigData($this->allowedCountriesConfigPath));
2730
if (in_array($this->getMerchantCountry(), $allowedMerchantCountries)) {
2831
return parent::render($element);
2932
}

Controller/Adminhtml/MerchantConfiguration/Update.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ public function execute()
4040
(string)__('Afterpay merchant configuration fetching is failed. See logs.')
4141
);
4242
}
43-
return $this->resultJsonFactory->create();
43+
return $this->resultJsonFactory->create()->setData([
44+
'done' => true
45+
]);
4446
}
4547
}

Controller/Express/PlaceOrder.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ public function execute()
5454
? $e->getMessage()
5555
: (string)__('Payment is failed');
5656
$this->messageManager->addErrorMessage($errorMessage);
57-
return $jsonResult;
57+
return $jsonResult->setData(['redirectUrl' => $this->url->getUrl('checkout/cart')]);
5858
}
5959

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

Gateway/Command/GetMerchantConfigurationCommandWrapper.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,12 @@ public function execute(array $commandSubject)
4747
return null;
4848
}
4949
$this->checkCountry($scope, $websiteId);
50+
$this->checkCurrency($scope, $websiteId);
5051
$this->debugLogger->setForceDebug($this->afterpayConfig->getIsDebug($websiteId));
5152
return $this->merchantConfigurationCommand->execute($commandSubject);
5253
} catch (\Magento\Payment\Gateway\Command\CommandException $e) {
5354
$this->eraseMerchantConfiguration($websiteId, $websiteHasOwnConfig);
55+
$this->logger->notice($e->getMessage());
5456
throw $e;
5557
} catch (\Exception $e) {
5658
$this->logger->critical($e->getMessage());
@@ -83,7 +85,26 @@ private function checkCountry(string $scope, int $websiteId): void
8385
if (!in_array($merchantCountry, $allowedCountries)) {
8486
throw new \Magento\Payment\Gateway\Command\CommandException(
8587
// @codingStandardsIgnoreLine
86-
__('Unable to fetch Afterpay merchant configuration due to unsupported merchant country. Supported countries: AU, CA, NZ, US.')
88+
__('Unable to fetch Afterpay merchant configuration due to unsupported merchant country. Supported countries: %1.', implode(', ', $allowedCountries))
89+
);
90+
}
91+
}
92+
93+
/**
94+
* @throws \Magento\Payment\Gateway\Command\CommandException
95+
*/
96+
private function checkCurrency(string $scope, int $websiteId): void
97+
{
98+
99+
$merchantCurrency = $this->afterpayConfig->getMerchantCurrency(
100+
$scope,
101+
$websiteId
102+
);
103+
$allowedCurrencies = $this->afterpayConfig->getAllowedCurrencies($websiteId);
104+
if (!in_array($merchantCurrency, $allowedCurrencies)) {
105+
throw new \Magento\Payment\Gateway\Command\CommandException(
106+
// @codingStandardsIgnoreLine
107+
__('Unable to fetch Afterpay merchant configuration due to unsupported merchant currency. Supported currencies: %1.', implode(', ', $allowedCurrencies))
87108
);
88109
}
89110
}

Gateway/Request/Checkout/CheckoutDataBuilder.php

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ public function build(array $buildSubject): array
3939
'consumer' => [
4040
'givenNames' => $quote->getCustomerFirstname() ?: $billingAddress->getFirstname(),
4141
'surname' => $quote->getCustomerLastname() ?: $billingAddress->getLastname(),
42-
'email' => $quote->getCustomerEmail() ?: $billingAddress->getEmail()
42+
'email' => $quote->getCustomerEmail() ?: $billingAddress->getEmail(),
43+
'phoneNumber' => $billingAddress->getTelephone()
4344
],
4445
'billing' => [
4546
'name' => $billingAddress->getFirstname() . ' ' . $billingAddress->getLastname(),
@@ -48,7 +49,8 @@ public function build(array $buildSubject): array
4849
'area1' => $billingAddress->getCity(),
4950
'region' => $billingAddress->getRegion(),
5051
'postcode' => $billingAddress->getPostcode(),
51-
'countryCode' => $billingAddress->getCountryId()
52+
'countryCode' => $billingAddress->getCountryId(),
53+
'phoneNumber' => $billingAddress->getTelephone()
5254
],
5355
'items' => $this->getItems($quote),
5456
'merchant' => [
@@ -61,7 +63,8 @@ public function build(array $buildSubject): array
6163
$billingAddress->getBaseTaxAmount() ?: $shippingAddress->getBaseTaxAmount()
6264
),
6365
'currency' => $quote->getBaseCurrencyCode()
64-
]
66+
],
67+
'purchaseCountry' => $billingAddress->getCountryId()
6568
];
6669

6770
if ($shippingAddress = $this->getShippingAddress($quote)) {
@@ -129,9 +132,7 @@ protected function getItemsImages(array $items): array
129132
->create();
130133
$products = $this->productRepository->getList($searchCriteria)->getItems();
131134

132-
foreach ($items as $item) {
133-
/** @var \Magento\Catalog\Model\Product $product */
134-
$product = $products[$item->getProduct()->getId()];
135+
foreach ($products as $product) {
135136
$medialGalleryImages = $product->getMediaGalleryImages();
136137
$itemsImages[$product->getId()] = $medialGalleryImages->getFirstItem();
137138
}
@@ -151,7 +152,8 @@ protected function getShippingAddress(\Magento\Quote\Model\Quote $quote): ?array
151152
'area1' => $shippingAddress->getCity(),
152153
'region' => $shippingAddress->getRegion(),
153154
'postcode' => $shippingAddress->getPostcode(),
154-
'countryCode' => $shippingAddress->getCountryId()
155+
'countryCode' => $shippingAddress->getCountryId(),
156+
'phoneNumber' => $shippingAddress->getTelephone()
155157
];
156158
}
157159

Gateway/Request/PaymentAction/AuthCaptureDataBuilder.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public function build(array $buildSubject): array
2424
'orderId' => $afterpayOrderId,
2525
'amount' => [
2626
'amount' => $this->formatPrice(SubjectReader::readAmount($buildSubject)),
27-
'currency' => $payment->getOrder()->getOrderCurrencyCode()
27+
'currency' => $payment->getOrder()->getBaseCurrencyCode()
2828
]
2929
];
3030
}

Gateway/Request/PaymentAction/CaptureDataBuilder.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public function build(array $buildSubject): array
1818
if ($payment->getAdditionalInformation('afterpay_express')) {
1919
$data['amount'] = [
2020
'amount' => \Magento\Payment\Gateway\Helper\SubjectReader::readAmount($buildSubject),
21-
'currency' => $payment->getOrder()->getOrderCurrencyCode()
21+
'currency' => $payment->getOrder()->getBaseCurrencyCode()
2222
];
2323
}
2424

Gateway/Response/Checkout/CheckoutDataToQuoteHandler.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,9 @@ public function handle(array $handlingSubject, array $response): void
5353

5454
$shippingInformation->setBillingAddress($address);
5555
if (!$quote->isVirtual()) {
56-
[$carrierCode, $methodCode] = explode('_', $response['shippingOptionIdentifier']);
56+
$explodedShippingOption = explode('_', $response['shippingOptionIdentifier']);
57+
$carrierCode = array_shift($explodedShippingOption);
58+
$methodCode = implode('_', $explodedShippingOption);
5759
$shippingInformation->setShippingAddress($address);
5860
$shippingInformation->setShippingCarrierCode($carrierCode);
5961
$shippingInformation->setShippingMethodCode($methodCode);

Gateway/Response/Checkout/CheckoutItemsAmountValidationHandler.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public function handle(array $handlingSubject, array $response)
1111
/** @var \Magento\Quote\Model\Quote $quote */
1212
$quote = $paymentDO->getPayment()->getQuote();
1313

14-
if (round($quote->getBaseGrandTotal(), 2) != round($response['amount']['amount'], 2)) {
14+
if (round(1 * $quote->getBaseGrandTotal(), 2) != round(1 * $response['amount']['amount'], 2)) {
1515
throw new \Magento\Framework\Exception\LocalizedException(
1616
__('There are issues when processing your payment. Invalid Amount')
1717
);
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Afterpay\Afterpay\Gateway\Validator;
4+
5+
class StockItemsValidator implements \Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface
6+
{
7+
private \Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface $isSingleSourceMode;
8+
private \Magento\InventorySourceDeductionApi\Model\SourceDeductionServiceInterface $sourceValidatorService;
9+
private \Magento\InventoryShipping\Model\SourceDeductionRequestFromShipmentFactory $sourceDeductionRequestFromShipmentFactory;
10+
private \Magento\InventoryShipping\Model\GetItemsToDeductFromShipment $getItemsToDeductFromShipment;
11+
private \Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface $defaultSourceProvider;
12+
13+
public function __construct(
14+
\Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface $isSingleSourceMode,
15+
\Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface $defaultSourceProvider,
16+
\Magento\InventoryShipping\Model\GetItemsToDeductFromShipment $getItemsToDeductFromShipment,
17+
\Magento\InventoryShipping\Model\SourceDeductionRequestFromShipmentFactory $sourceDeductionRequestFromShipmentFactory,
18+
\Magento\InventorySourceDeductionApi\Model\SourceDeductionServiceInterface $sourceValidatorService
19+
) {
20+
$this->isSingleSourceMode = $isSingleSourceMode;
21+
$this->defaultSourceProvider = $defaultSourceProvider;
22+
$this->getItemsToDeductFromShipment = $getItemsToDeductFromShipment;
23+
$this->sourceDeductionRequestFromShipmentFactory = $sourceDeductionRequestFromShipmentFactory;
24+
$this->sourceValidatorService = $sourceValidatorService;
25+
}
26+
27+
/**
28+
* @inheridoc
29+
*/
30+
public function validate(\Magento\Sales\Model\Order\Shipment $shipment): void
31+
{
32+
if ($shipment->getOrigData('entity_id')) {
33+
return;
34+
}
35+
36+
if (!empty($shipment->getExtensionAttributes())
37+
&& !empty($shipment->getExtensionAttributes()->getSourceCode())) {
38+
$sourceCode = $shipment->getExtensionAttributes()->getSourceCode();
39+
} elseif ($this->isSingleSourceMode->execute()) {
40+
$sourceCode = $this->defaultSourceProvider->getCode();
41+
}
42+
43+
$shipmentItems = $this->getItemsToDeductFromShipment->execute($shipment);
44+
45+
if (!empty($shipmentItems)) {
46+
$sourceDeductionRequest = $this->sourceDeductionRequestFromShipmentFactory->execute(
47+
$shipment,
48+
$sourceCode,
49+
$shipmentItems
50+
);
51+
$this->sourceValidatorService->execute($sourceDeductionRequest);
52+
}
53+
}
54+
}

Model/CheckoutConfigProvider.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace Afterpay\Afterpay\Model;
4+
5+
class CheckoutConfigProvider implements \Magento\Checkout\Model\ConfigProviderInterface
6+
{
7+
private \Magento\Framework\Locale\Resolver $localeResolver;
8+
9+
public function __construct(
10+
\Magento\Framework\Locale\Resolver $localeResolver
11+
) {
12+
$this->localeResolver = $localeResolver;
13+
}
14+
15+
public function getConfig(): array
16+
{
17+
return [
18+
'payment' => [
19+
'afterpay' => [
20+
'locale' => $this->localeResolver->getLocale()
21+
]
22+
]
23+
];
24+
}
25+
}

Model/Config.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ class Config
2626
const XML_PATH_ALLOW_SPECIFIC_COUNTRIES = 'payment/afterpay/allowspecific';
2727
const XML_PATH_SPECIFIC_COUNTRIES = 'payment/afterpay/specificcountry';
2828
const XML_PATH_ALLOWED_MERCHANT_COUNTRIES = 'payment/afterpay/allowed_merchant_countries';
29+
const XML_PATH_ALLOWED_MERCHANT_CURRENCIES = 'payment/afterpay/allowed_merchant_currencies';
2930
const XML_PATH_PAYPAL_MERCHANT_COUNTRY = 'paypal/general/merchant_country';
3031

3132
private \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig;
@@ -241,6 +242,22 @@ public function getAllowedCountries(?int $scopeCode = null): array
241242
return [];
242243
}
243244

245+
/**
246+
* @return string[]
247+
*/
248+
public function getAllowedCurrencies(?int $scopeCode = null): array
249+
{
250+
$specificCountries = $this->scopeConfig->getValue(
251+
self::XML_PATH_ALLOWED_MERCHANT_CURRENCIES,
252+
ScopeInterface::SCOPE_WEBSITE,
253+
$scopeCode
254+
);
255+
if ($specificCountries != null) {
256+
return explode(",", $specificCountries);
257+
}
258+
return [];
259+
}
260+
244261
/**
245262
* @return string[]
246263
*/
@@ -301,6 +318,17 @@ public function getMerchantCountry(
301318
return null;
302319
}
303320

321+
public function getMerchantCurrency(
322+
string $scope = ScopeInterface::SCOPE_WEBSITES,
323+
?int $scopeCode = null
324+
): ?string {
325+
return $this->scopeConfig->getValue(
326+
\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE,
327+
$scope,
328+
$scopeCode
329+
);
330+
}
331+
304332
public function getByConfigPath(?string $path, ?int $scopeCode = null): ?string
305333
{
306334
if (!$path) {

Model/Order/Shipment/CaptureProcessor.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,19 @@ class CaptureProcessor
1111
private \Magento\Payment\Gateway\Data\PaymentDataObjectFactoryInterface $paymentDataObjectFactory;
1212
private \Afterpay\Afterpay\Model\Order\Payment\Auth\ExpiryDate $authExpiryDate;
1313
private \Afterpay\Afterpay\Model\Payment\AmountProcessor\Shipment $shipmentAmountProcessor;
14+
private \Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface $stockItemsValidator;
1415

1516
public function __construct(
1617
\Magento\Payment\Gateway\CommandInterface $authCaptureCommand,
1718
\Magento\Payment\Gateway\Data\PaymentDataObjectFactoryInterface $paymentDataObjectFactory,
1819
\Afterpay\Afterpay\Model\Order\Payment\Auth\ExpiryDate $authExpiryDate,
20+
\Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface $stockItemsValidator,
1921
\Afterpay\Afterpay\Model\Payment\AmountProcessor\Shipment $shipmentAmountProcessor
2022
) {
2123
$this->authCaptureCommand = $authCaptureCommand;
2224
$this->paymentDataObjectFactory = $paymentDataObjectFactory;
2325
$this->authExpiryDate = $authExpiryDate;
26+
$this->stockItemsValidator = $stockItemsValidator;
2427
$this->shipmentAmountProcessor = $shipmentAmountProcessor;
2528
}
2629

@@ -43,7 +46,7 @@ public function execute(\Magento\Sales\Model\Order\Shipment $shipment): void
4346

4447
if ($amountToCaptureExists && $correctStateForAuthCapture) {
4548
$this->validateAuthExpiryDate($additionalInfo[AdditionalInformationInterface::AFTERPAY_AUTH_EXPIRY_DATE]);
46-
49+
$this->stockItemsValidator->validate($shipment);
4750
$amountToCapture = $this->shipmentAmountProcessor->process($shipment->getItemsCollection(), $payment);
4851

4952
if ($amountToCapture > 0) {

Model/Payment/AmountProcessor/CreditMemo.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ private function processRolloverDiscountForVoidAmount(
160160
private function calculateItemPrice(\Magento\Sales\Model\Order\Creditmemo\Item $item, float $qty): float
161161
{
162162
$discountPerItem = $item->getBaseDiscountAmount() / $item->getQty();
163-
$pricePerItem = $item->getBaseRowTotalInclTax() / $item->getQty();
163+
$pricePerItem = ($item->getBaseRowTotal() + $item->getBaseTaxAmount()) / $item->getQty();
164164
return $qty * ($pricePerItem - $discountPerItem);
165165
}
166166

Model/Payment/AmountProcessor/Order.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public function process(array $items, \Magento\Sales\Model\Order\Payment $paymen
2323
protected function calculateItemPrice(\Magento\Sales\Model\Order\Item $item, float $qty): float
2424
{
2525
$discountPerItem = $item->getBaseDiscountAmount() / $item->getQtyOrdered();
26-
$pricePerItem = $item->getBaseRowTotalInclTax() / $item->getQtyOrdered();
26+
$pricePerItem = ($item->getBaseRowTotal() + $item->getBaseTaxAmount()) / $item->getQtyOrdered();
2727
return $qty * ($pricePerItem - $discountPerItem);
2828
}
2929

0 commit comments

Comments
 (0)