Skip to content

Commit

Permalink
Release version 5.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
afterpayplugins committed May 19, 2022
1 parent 7ce79e0 commit ea33c5f
Show file tree
Hide file tree
Showing 38 changed files with 455 additions and 130 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

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

class Payment extends \Magento\Config\Block\System\Config\Form\Fieldset
class AllowedByCountry extends \Magento\Config\Block\System\Config\Form\Fieldset
{
private \Magento\Payment\Model\MethodInterface $afterpay;
private \Afterpay\Afterpay\Model\Config $config;
private string $allowedCountriesConfigPath;

public function __construct(
\Magento\Backend\Block\Context $context,
Expand All @@ -14,16 +15,18 @@ public function __construct(
\Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer,
\Magento\Payment\Model\MethodInterface $afterpay,
\Afterpay\Afterpay\Model\Config $config,
string $allowedCountriesConfigPath = '',
array $data = []
) {
parent::__construct($context, $authSession, $jsHelper, $data, $secureRenderer);
$this->afterpay = $afterpay;
$this->config = $config;
$this->allowedCountriesConfigPath = $allowedCountriesConfigPath;
}

public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element): string
{
$allowedMerchantCountries = explode(',', $this->afterpay->getConfigData('allowed_merchant_countries'));
$allowedMerchantCountries = explode(',', $this->afterpay->getConfigData($this->allowedCountriesConfigPath));
if (in_array($this->getMerchantCountry(), $allowedMerchantCountries)) {
return parent::render($element);
}
Expand Down
4 changes: 3 additions & 1 deletion Controller/Adminhtml/MerchantConfiguration/Update.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ public function execute()
(string)__('Afterpay merchant configuration fetching is failed. See logs.')
);
}
return $this->resultJsonFactory->create();
return $this->resultJsonFactory->create()->setData([
'done' => true
]);
}
}
2 changes: 1 addition & 1 deletion Controller/Express/PlaceOrder.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function execute()
? $e->getMessage()
: (string)__('Payment is failed');
$this->messageManager->addErrorMessage($errorMessage);
return $jsonResult;
return $jsonResult->setData(['redirectUrl' => $this->url->getUrl('checkout/cart')]);
}

return $jsonResult->setData(['redirectUrl' => $this->url->getUrl('checkout/onepage/success')]);
Expand Down
23 changes: 22 additions & 1 deletion Gateway/Command/GetMerchantConfigurationCommandWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,12 @@ public function execute(array $commandSubject)
return null;
}
$this->checkCountry($scope, $websiteId);
$this->checkCurrency($scope, $websiteId);
$this->debugLogger->setForceDebug($this->afterpayConfig->getIsDebug($websiteId));
return $this->merchantConfigurationCommand->execute($commandSubject);
} catch (\Magento\Payment\Gateway\Command\CommandException $e) {
$this->eraseMerchantConfiguration($websiteId, $websiteHasOwnConfig);
$this->logger->notice($e->getMessage());
throw $e;
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
Expand Down Expand Up @@ -83,7 +85,26 @@ private function checkCountry(string $scope, int $websiteId): void
if (!in_array($merchantCountry, $allowedCountries)) {
throw new \Magento\Payment\Gateway\Command\CommandException(
// @codingStandardsIgnoreLine
__('Unable to fetch Afterpay merchant configuration due to unsupported merchant country. Supported countries: AU, CA, NZ, US.')
__('Unable to fetch Afterpay merchant configuration due to unsupported merchant country. Supported countries: %1.', implode(', ', $allowedCountries))
);
}
}

/**
* @throws \Magento\Payment\Gateway\Command\CommandException
*/
private function checkCurrency(string $scope, int $websiteId): void
{

$merchantCurrency = $this->afterpayConfig->getMerchantCurrency(
$scope,
$websiteId
);
$allowedCurrencies = $this->afterpayConfig->getAllowedCurrencies($websiteId);
if (!in_array($merchantCurrency, $allowedCurrencies)) {
throw new \Magento\Payment\Gateway\Command\CommandException(
// @codingStandardsIgnoreLine
__('Unable to fetch Afterpay merchant configuration due to unsupported merchant currency. Supported currencies: %1.', implode(', ', $allowedCurrencies))
);
}
}
Expand Down
16 changes: 9 additions & 7 deletions Gateway/Request/Checkout/CheckoutDataBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ public function build(array $buildSubject): array
'consumer' => [
'givenNames' => $quote->getCustomerFirstname() ?: $billingAddress->getFirstname(),
'surname' => $quote->getCustomerLastname() ?: $billingAddress->getLastname(),
'email' => $quote->getCustomerEmail() ?: $billingAddress->getEmail()
'email' => $quote->getCustomerEmail() ?: $billingAddress->getEmail(),
'phoneNumber' => $billingAddress->getTelephone()
],
'billing' => [
'name' => $billingAddress->getFirstname() . ' ' . $billingAddress->getLastname(),
Expand All @@ -48,7 +49,8 @@ public function build(array $buildSubject): array
'area1' => $billingAddress->getCity(),
'region' => $billingAddress->getRegion(),
'postcode' => $billingAddress->getPostcode(),
'countryCode' => $billingAddress->getCountryId()
'countryCode' => $billingAddress->getCountryId(),
'phoneNumber' => $billingAddress->getTelephone()
],
'items' => $this->getItems($quote),
'merchant' => [
Expand All @@ -61,7 +63,8 @@ public function build(array $buildSubject): array
$billingAddress->getBaseTaxAmount() ?: $shippingAddress->getBaseTaxAmount()
),
'currency' => $quote->getBaseCurrencyCode()
]
],
'purchaseCountry' => $billingAddress->getCountryId()
];

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

foreach ($items as $item) {
/** @var \Magento\Catalog\Model\Product $product */
$product = $products[$item->getProduct()->getId()];
foreach ($products as $product) {
$medialGalleryImages = $product->getMediaGalleryImages();
$itemsImages[$product->getId()] = $medialGalleryImages->getFirstItem();
}
Expand All @@ -151,7 +152,8 @@ protected function getShippingAddress(\Magento\Quote\Model\Quote $quote): ?array
'area1' => $shippingAddress->getCity(),
'region' => $shippingAddress->getRegion(),
'postcode' => $shippingAddress->getPostcode(),
'countryCode' => $shippingAddress->getCountryId()
'countryCode' => $shippingAddress->getCountryId(),
'phoneNumber' => $shippingAddress->getTelephone()
];
}

Expand Down
2 changes: 1 addition & 1 deletion Gateway/Request/PaymentAction/AuthCaptureDataBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function build(array $buildSubject): array
'orderId' => $afterpayOrderId,
'amount' => [
'amount' => $this->formatPrice(SubjectReader::readAmount($buildSubject)),
'currency' => $payment->getOrder()->getOrderCurrencyCode()
'currency' => $payment->getOrder()->getBaseCurrencyCode()
]
];
}
Expand Down
2 changes: 1 addition & 1 deletion Gateway/Request/PaymentAction/CaptureDataBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public function build(array $buildSubject): array
if ($payment->getAdditionalInformation('afterpay_express')) {
$data['amount'] = [
'amount' => \Magento\Payment\Gateway\Helper\SubjectReader::readAmount($buildSubject),
'currency' => $payment->getOrder()->getOrderCurrencyCode()
'currency' => $payment->getOrder()->getBaseCurrencyCode()
];
}

Expand Down
4 changes: 3 additions & 1 deletion Gateway/Response/Checkout/CheckoutDataToQuoteHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ public function handle(array $handlingSubject, array $response): void

$shippingInformation->setBillingAddress($address);
if (!$quote->isVirtual()) {
[$carrierCode, $methodCode] = explode('_', $response['shippingOptionIdentifier']);
$explodedShippingOption = explode('_', $response['shippingOptionIdentifier']);
$carrierCode = array_shift($explodedShippingOption);
$methodCode = implode('_', $explodedShippingOption);
$shippingInformation->setShippingAddress($address);
$shippingInformation->setShippingCarrierCode($carrierCode);
$shippingInformation->setShippingMethodCode($methodCode);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public function handle(array $handlingSubject, array $response)
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $paymentDO->getPayment()->getQuote();

if (round($quote->getBaseGrandTotal(), 2) != round($response['amount']['amount'], 2)) {
if (round(1 * $quote->getBaseGrandTotal(), 2) != round(1 * $response['amount']['amount'], 2)) {
throw new \Magento\Framework\Exception\LocalizedException(
__('There are issues when processing your payment. Invalid Amount')
);
Expand Down
54 changes: 54 additions & 0 deletions Gateway/Validator/StockItemsValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php declare(strict_types=1);

namespace Afterpay\Afterpay\Gateway\Validator;

class StockItemsValidator implements \Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface
{
private \Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface $isSingleSourceMode;
private \Magento\InventorySourceDeductionApi\Model\SourceDeductionServiceInterface $sourceValidatorService;
private \Magento\InventoryShipping\Model\SourceDeductionRequestFromShipmentFactory $sourceDeductionRequestFromShipmentFactory;
private \Magento\InventoryShipping\Model\GetItemsToDeductFromShipment $getItemsToDeductFromShipment;
private \Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface $defaultSourceProvider;

public function __construct(
\Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface $isSingleSourceMode,
\Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface $defaultSourceProvider,
\Magento\InventoryShipping\Model\GetItemsToDeductFromShipment $getItemsToDeductFromShipment,
\Magento\InventoryShipping\Model\SourceDeductionRequestFromShipmentFactory $sourceDeductionRequestFromShipmentFactory,
\Magento\InventorySourceDeductionApi\Model\SourceDeductionServiceInterface $sourceValidatorService
) {
$this->isSingleSourceMode = $isSingleSourceMode;
$this->defaultSourceProvider = $defaultSourceProvider;
$this->getItemsToDeductFromShipment = $getItemsToDeductFromShipment;
$this->sourceDeductionRequestFromShipmentFactory = $sourceDeductionRequestFromShipmentFactory;
$this->sourceValidatorService = $sourceValidatorService;
}

/**
* @inheridoc
*/
public function validate(\Magento\Sales\Model\Order\Shipment $shipment): void
{
if ($shipment->getOrigData('entity_id')) {
return;
}

if (!empty($shipment->getExtensionAttributes())
&& !empty($shipment->getExtensionAttributes()->getSourceCode())) {
$sourceCode = $shipment->getExtensionAttributes()->getSourceCode();
} elseif ($this->isSingleSourceMode->execute()) {
$sourceCode = $this->defaultSourceProvider->getCode();
}

$shipmentItems = $this->getItemsToDeductFromShipment->execute($shipment);

if (!empty($shipmentItems)) {
$sourceDeductionRequest = $this->sourceDeductionRequestFromShipmentFactory->execute(
$shipment,
$sourceCode,
$shipmentItems
);
$this->sourceValidatorService->execute($sourceDeductionRequest);
}
}
}
25 changes: 25 additions & 0 deletions Model/CheckoutConfigProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php declare(strict_types=1);

namespace Afterpay\Afterpay\Model;

class CheckoutConfigProvider implements \Magento\Checkout\Model\ConfigProviderInterface
{
private \Magento\Framework\Locale\Resolver $localeResolver;

public function __construct(
\Magento\Framework\Locale\Resolver $localeResolver
) {
$this->localeResolver = $localeResolver;
}

public function getConfig(): array
{
return [
'payment' => [
'afterpay' => [
'locale' => $this->localeResolver->getLocale()
]
]
];
}
}
28 changes: 28 additions & 0 deletions Model/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class Config
const XML_PATH_ALLOW_SPECIFIC_COUNTRIES = 'payment/afterpay/allowspecific';
const XML_PATH_SPECIFIC_COUNTRIES = 'payment/afterpay/specificcountry';
const XML_PATH_ALLOWED_MERCHANT_COUNTRIES = 'payment/afterpay/allowed_merchant_countries';
const XML_PATH_ALLOWED_MERCHANT_CURRENCIES = 'payment/afterpay/allowed_merchant_currencies';
const XML_PATH_PAYPAL_MERCHANT_COUNTRY = 'paypal/general/merchant_country';

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

/**
* @return string[]
*/
public function getAllowedCurrencies(?int $scopeCode = null): array
{
$specificCountries = $this->scopeConfig->getValue(
self::XML_PATH_ALLOWED_MERCHANT_CURRENCIES,
ScopeInterface::SCOPE_WEBSITE,
$scopeCode
);
if ($specificCountries != null) {
return explode(",", $specificCountries);
}
return [];
}

/**
* @return string[]
*/
Expand Down Expand Up @@ -301,6 +318,17 @@ public function getMerchantCountry(
return null;
}

public function getMerchantCurrency(
string $scope = ScopeInterface::SCOPE_WEBSITES,
?int $scopeCode = null
): ?string {
return $this->scopeConfig->getValue(
\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE,
$scope,
$scopeCode
);
}

public function getByConfigPath(?string $path, ?int $scopeCode = null): ?string
{
if (!$path) {
Expand Down
5 changes: 4 additions & 1 deletion Model/Order/Shipment/CaptureProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,19 @@ class CaptureProcessor
private \Magento\Payment\Gateway\Data\PaymentDataObjectFactoryInterface $paymentDataObjectFactory;
private \Afterpay\Afterpay\Model\Order\Payment\Auth\ExpiryDate $authExpiryDate;
private \Afterpay\Afterpay\Model\Payment\AmountProcessor\Shipment $shipmentAmountProcessor;
private \Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface $stockItemsValidator;

public function __construct(
\Magento\Payment\Gateway\CommandInterface $authCaptureCommand,
\Magento\Payment\Gateway\Data\PaymentDataObjectFactoryInterface $paymentDataObjectFactory,
\Afterpay\Afterpay\Model\Order\Payment\Auth\ExpiryDate $authExpiryDate,
\Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface $stockItemsValidator,
\Afterpay\Afterpay\Model\Payment\AmountProcessor\Shipment $shipmentAmountProcessor
) {
$this->authCaptureCommand = $authCaptureCommand;
$this->paymentDataObjectFactory = $paymentDataObjectFactory;
$this->authExpiryDate = $authExpiryDate;
$this->stockItemsValidator = $stockItemsValidator;
$this->shipmentAmountProcessor = $shipmentAmountProcessor;
}

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

if ($amountToCaptureExists && $correctStateForAuthCapture) {
$this->validateAuthExpiryDate($additionalInfo[AdditionalInformationInterface::AFTERPAY_AUTH_EXPIRY_DATE]);

$this->stockItemsValidator->validate($shipment);
$amountToCapture = $this->shipmentAmountProcessor->process($shipment->getItemsCollection(), $payment);

if ($amountToCapture > 0) {
Expand Down
2 changes: 1 addition & 1 deletion Model/Payment/AmountProcessor/CreditMemo.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ private function processRolloverDiscountForVoidAmount(
private function calculateItemPrice(\Magento\Sales\Model\Order\Creditmemo\Item $item, float $qty): float
{
$discountPerItem = $item->getBaseDiscountAmount() / $item->getQty();
$pricePerItem = $item->getBaseRowTotalInclTax() / $item->getQty();
$pricePerItem = ($item->getBaseRowTotal() + $item->getBaseTaxAmount()) / $item->getQty();
return $qty * ($pricePerItem - $discountPerItem);
}

Expand Down
2 changes: 1 addition & 1 deletion Model/Payment/AmountProcessor/Order.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function process(array $items, \Magento\Sales\Model\Order\Payment $paymen
protected function calculateItemPrice(\Magento\Sales\Model\Order\Item $item, float $qty): float
{
$discountPerItem = $item->getBaseDiscountAmount() / $item->getQtyOrdered();
$pricePerItem = $item->getBaseRowTotalInclTax() / $item->getQtyOrdered();
$pricePerItem = ($item->getBaseRowTotal() + $item->getBaseTaxAmount()) / $item->getQtyOrdered();
return $qty * ($pricePerItem - $discountPerItem);
}

Expand Down
Loading

0 comments on commit ea33c5f

Please sign in to comment.