Skip to content

Commit

Permalink
Release version 4.3.2
Browse files Browse the repository at this point in the history
  • Loading branch information
afterpayplugins committed Aug 7, 2024
1 parent e47b709 commit ab90df3
Show file tree
Hide file tree
Showing 18 changed files with 167 additions and 69 deletions.
4 changes: 0 additions & 4 deletions Block/Adminhtml/System/Config/Fieldset/AllowedByCountry.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,6 @@ private function getMerchantCountry(): ?string
$scope = $fieldSetForm->getScope();
$scopeCode = $fieldSetForm->getScopeCode();

if ($countryCode = $this->getRequest()->getParam('paypal_country')) {
return $countryCode;
}

return $this->config->getMerchantCountry($scope, (int)$scopeCode);
}
}
22 changes: 12 additions & 10 deletions Block/Adminhtml/System/Config/Form/Field/CBTAvailableCurrencies.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,19 @@ public function __construct(
protected function _renderValue(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
try {
$CbtAvailableCurrencies = $this->serializer->unserialize($element->getValue());
$newValue = '';
if (!$CbtAvailableCurrencies) {
return parent::_renderValue($element);
if (!empty($element->getValue())) {
$CbtAvailableCurrencies = $this->serializer->unserialize($element->getValue());
$newValue = '';
if (!$CbtAvailableCurrencies) {
return parent::_renderValue($element);
}

foreach ($CbtAvailableCurrencies as $currencyCode => $currency) {
$min = $currency['minimumAmount']['amount'] ?? '0';
$newValue .= $currencyCode . '(min:' . $min . ',max:' . $currency['maximumAmount']['amount'] . ') ';
}
$element->setValue($newValue);
}

foreach ($CbtAvailableCurrencies as $currencyCode => $currency) {
$min = $currency['minimumAmount']['amount'] ?? '0';
$newValue .= $currencyCode . '(min:' . $min . ',max:' . $currency['maximumAmount']['amount'] . ') ';
}
$element->setValue($newValue);
} catch (\Exception $e) {
$this->logger->critical($e);
}
Expand Down
19 changes: 12 additions & 7 deletions Gateway/Command/GetMerchantConfigurationCommandWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,21 @@ public function execute(array $commandSubject)
try {
if (!$websiteHasOwnConfig) {
$this->eraseMerchantConfiguration($websiteId, $websiteHasOwnConfig);

return null;
}
$this->checkCountry($scope, $websiteId);
$this->checkCurrency($scope, $websiteId);
// Disable Cash App Pay if Afterpay is disabled
if($this->afterpayConfig->getIsPaymentActive($websiteId)===false){
$this->afterpayConfig->setCashAppPayActive(0,$websiteId);

if ($this->afterpayConfig->getIsPaymentActive($websiteId) === true) {
$this->checkCountry($scope, $websiteId);
$this->checkCurrency($scope, $websiteId);
$this->debugLogger->setForceDebug($this->afterpayConfig->getIsDebug($websiteId));

return $this->merchantConfigurationCommand->execute($commandSubject);
}
$this->debugLogger->setForceDebug($this->afterpayConfig->getIsDebug($websiteId));
return $this->merchantConfigurationCommand->execute($commandSubject);
// Disable Cash App Pay if Afterpay is disabled
$this->afterpayConfig->setCashAppPayActive(0, $websiteId);

return null;
} catch (\Magento\Payment\Gateway\Command\CommandException $e) {
$this->eraseMerchantConfiguration($websiteId, $websiteHasOwnConfig);
$this->logger->notice($e->getMessage());
Expand Down
2 changes: 1 addition & 1 deletion Gateway/ErrorMessageMapper/CaptureErrorMessageMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

class CaptureErrorMessageMapper implements ErrorMessageMapperInterface
{
public const STATUS_DECLINED_ERROR_MESSAGE = 'Aftepay payment declined. Please select an alternative payment method.'; // @codingStandardsIgnoreLine
public const STATUS_DECLINED_ERROR_MESSAGE = 'Afterpay payment declined. Please select an alternative payment method.'; // @codingStandardsIgnoreLine

public function getMessage(string $code)
{
Expand Down
28 changes: 22 additions & 6 deletions Gateway/Response/Checkout/CheckoutDataToQuoteHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,36 @@ public function handle(array $handlingSubject, array $response): void
/** @var \Magento\Quote\Model\Quote $quote */
$quote = $paymentDO->getPayment()->getQuote();

$consumerEmail = $response['consumer']['email'];
$consumerName = $response['consumer']['givenNames'];
$consumerLastname = $response['consumer']['surname'];
if (!$quote->getCustomerId()) {
$quote->setCustomerEmail($response['consumer']['email']);
$quote->setCustomerFirstname($response['consumer']['givenNames']);
$quote->setCustomerLastname($response['consumer']['surname']);
$quote->setCustomerEmail($consumerEmail);
$quote->setCustomerFirstname($consumerName);
$quote->setCustomerLastname($consumerLastname);
}

/** @var \Magento\Checkout\Api\Data\ShippingInformationInterface $shippingInformation */
$shippingInformation = $this->shippingInformationFactory->create();

if (!empty($response['shipping']['name'])) {
$nameArray = explode(' ', $response['shipping']['name']);
$firstname = $nameArray[0] ?? $consumerName;
if (!empty($nameArray[1])) {
$lastname = implode(' ', array_slice($nameArray, 1));
} else {
$lastname = $firstname;
}
} else {
$firstname = $consumerName;
$lastname = $consumerLastname;
}

/** @var \Magento\Quote\Api\Data\AddressInterface $address */
$address = $this->addressInterfaceFactory->create();
$address->setEmail($response['consumer']['email'])
->setFirstname($response['consumer']['givenNames'])
->setLastname($response['consumer']['surname'])
$address->setEmail($consumerEmail)
->setFirstname($firstname)
->setLastname($lastname)
->setTelephone($response['shipping']['phoneNumber'] ?? $response['consumer']['phoneNumber'])
->setCity($response['shipping']['area1'])
->setCountryId($response['shipping']['countryCode'])
Expand Down
8 changes: 4 additions & 4 deletions Gateway/Validator/StockItemsValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,20 @@ class StockItemsValidator implements \Afterpay\Afterpay\Model\Spi\StockItemsVali
* @param \Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface $isSingleSourceMode
* @param \Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface $defaultSourceProvider
* @param \Magento\InventoryShipping\Model\GetItemsToDeductFromShipment $getItemsToDeductFromShipment
* @param \Magento\InventoryShipping\Model\SourceDeductionRequestFromShipmentFactory $sourceDeductionRequestFromShipmentFactory
* @param \Magento\InventoryShipping\Model\SourceDeductionRequestFromShipmentFactory $shipmentFactory
* @param \Afterpay\Afterpay\Model\Spi\SourceValidatorServiceInterface $sourceValidatorService
*/
public function __construct(
$isSingleSourceMode,
$defaultSourceProvider,
$getItemsToDeductFromShipment,
$sourceDeductionRequestFromShipmentFactory,
$shipmentFactory,
$sourceValidatorService
) {
$this->isSingleSourceMode = $isSingleSourceMode;
$this->defaultSourceProvider = $defaultSourceProvider;
$this->getItemsToDeductFromShipment = $getItemsToDeductFromShipment;
$this->sourceDeductionRequestFromShipmentFactory = $sourceDeductionRequestFromShipmentFactory;
$this->shipmentFactory = $shipmentFactory;
$this->sourceValidatorService = $sourceValidatorService;
}

Expand All @@ -52,7 +52,7 @@ public function validate(\Magento\Sales\Model\Order\Shipment $shipment): void
$shipmentItems = $this->getItemsToDeductFromShipment->execute($shipment);

if (!empty($shipmentItems)) {
$sourceDeductionRequest = $this->sourceDeductionRequestFromShipmentFactory->execute(
$sourceDeductionRequest = $this->shipmentFactory->execute(
$shipment,
$sourceCode,
$shipmentItems
Expand Down
7 changes: 0 additions & 7 deletions Model/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -362,13 +362,6 @@ public function getMerchantCountry(
string $scope = ScopeInterface::SCOPE_WEBSITES,
?int $scopeCode = null
): ?string {
if ($countryCode = $this->scopeConfig->getValue(
self::XML_PATH_PAYPAL_MERCHANT_COUNTRY,
$scope,
$scopeCode
)) {
return $countryCode;
}
if ($countryCode = $this->scopeConfig->getValue(
\Magento\Directory\Helper\Data::XML_PATH_DEFAULT_COUNTRY,
$scope,
Expand Down
9 changes: 4 additions & 5 deletions Model/Order/CreditMemo/CreditMemoProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,8 @@ public function __construct(
public function processOrder(\Magento\Sales\Model\Order $order): void
{
$additionalInformation = $order->getData('additional_information');
$expireDate = $additionalInformation[
AdditionalInformationInterface::AFTERPAY_AUTH_EXPIRY_DATE
];
if (!$this->expiryDate->isExpired($expireDate)) {
$expireDate = $additionalInformation[AdditionalInformationInterface::AFTERPAY_AUTH_EXPIRY_DATE] ?? null;
if (!$expireDate || !$this->expiryDate->isExpired($expireDate)) {
return;
}
/** @var \Magento\Payment\Model\InfoInterface $payment */
Expand All @@ -45,7 +43,8 @@ public function processOrder(\Magento\Sales\Model\Order $order): void
];
if ($paymentState !== PaymentStateInterface::CAPTURED &&
$paymentState !== PaymentStateInterface::PARTIALLY_CAPTURED &&
$paymentState !== PaymentStateInterface::VOIDED) {
$paymentState !== PaymentStateInterface::VOIDED &&
$paymentState !== PaymentStateInterface::EXPIRED) {
return;
}
$creditmemo = $this->creditMemoInitiator->init($order);
Expand Down
48 changes: 46 additions & 2 deletions Model/Order/CreditMemo/OrdersRetriever.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,41 @@
namespace Afterpay\Afterpay\Model\Order\CreditMemo;

use Afterpay\Afterpay\Api\Data\TokenInterface;
use Afterpay\Afterpay\Model\Payment\AdditionalInformationInterface;
use Afterpay\Afterpay\Model\ResourceModel\Token\CollectionFactory;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderPaymentInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\ResourceModel\Order\Collection;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory as OrderCollectionFactory;
use Psr\Log\LoggerInterface;

class OrdersRetriever
{
private $orderCollectionFactory;
private $resourceConnection;
private $tokensCollectionFactory;
private $dateTime;
private $serializer;
private $logger;

public function __construct(
OrderCollectionFactory $orderCollectionFactory,
ResourceConnection $resourceConnection,
CollectionFactory $tokensCollectionFactory,
DateTime $dateTime
DateTime $dateTime,
Json $serializer,
LoggerInterface $logger
) {
$this->orderCollectionFactory = $orderCollectionFactory;
$this->resourceConnection = $resourceConnection;
$this->tokensCollectionFactory = $tokensCollectionFactory;
$this->dateTime = $dateTime;
$this->serializer = $serializer;
$this->logger = $logger;
}

/**
Expand Down Expand Up @@ -59,7 +68,42 @@ public function getAfterpayOrders(): array
);
$orderCollection = $this->joinAfterpayPaymentAdditionalInfo($orderCollection);

return $orderCollection->getItems();
return $this->getItemsWithAdditionalInfo($orderCollection->getItems());
}

/**
* @param Order[] $items
*
* @return array
*/
private function getItemsWithAdditionalInfo(array $items): array
{
$itemsWithJsonAdditionalInfo = [];
foreach ($items as $item) {
$additionalInformation = $item->getData(
OrderPaymentInterface::ADDITIONAL_INFORMATION
);
try {
$unserializedInfo = !empty($additionalInformation) ? $this->serializer->unserialize($additionalInformation) : null;
if (!is_array($unserializedInfo)) {
continue;
}

$item->setData(OrderPaymentInterface::ADDITIONAL_INFORMATION, $unserializedInfo);
if (isset(
$unserializedInfo[AdditionalInformationInterface::AFTERPAY_PAYMENT_STATE],
$unserializedInfo[AdditionalInformationInterface::AFTERPAY_OPEN_TO_CAPTURE_AMOUNT],
$unserializedInfo[AdditionalInformationInterface::AFTERPAY_AUTH_EXPIRY_DATE]
)) {
$itemsWithJsonAdditionalInfo[] = $item;
}
} catch (\InvalidArgumentException $e) {
$this->logger->warning('Error during ansync offline credit memo processing for Order #' . $item->getIncrementId());
$this->logger->warning($e->getMessage());
}
}

return $itemsWithJsonAdditionalInfo;
}

private function joinAfterpayPaymentAdditionalInfo(
Expand Down
1 change: 1 addition & 0 deletions Model/PaymentStateInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ interface PaymentStateInterface
public const PARTIALLY_CAPTURED = 'PARTIALLY_CAPTURED';
public const CAPTURED = 'CAPTURED';
public const VOIDED = 'VOIDED';
public const EXPIRED = 'EXPIRED';
}
10 changes: 5 additions & 5 deletions Model/StockItemsValidator/StockItemsValidatorProxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,11 @@ private function getStockItemValidator(): StockItemsValidatorInterface
'getStockBySalesChannel' => $objectManager->create(GetStockBySalesChannelInterface::class),
]);
$this->subject = $this->stockItemValidatorFactory->create([
'isSingleSourceMode' => $objectManager->create(IsSingleSourceModeInterface::class),
'defaultSourceProvider' => $objectManager->create(DefaultSourceProviderInterface::class),
'getItemsToDeductFromShipment' => $objectManager->create(GetItemsToDeductFromShipment::class),
'sourceDeductionRequestFromShipmentFactory' => $objectManager->create(SourceDeductionRequestFactory::class),
'sourceValidatorService' => $sourceValidatorService,
'isSingleSourceMode' => $objectManager->create(IsSingleSourceModeInterface::class),
'defaultSourceProvider' => $objectManager->create(DefaultSourceProviderInterface::class),
'getItemsToDeductFromShipment' => $objectManager->create(GetItemsToDeductFromShipment::class),
'shipmentFactory' => $objectManager->create(SourceDeductionRequestFactory::class),
'sourceValidatorService' => $sourceValidatorService,
]);
}

Expand Down
3 changes: 1 addition & 2 deletions Observer/Adminhtml/ConfigSaveAfter.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ class ConfigSaveAfter implements \Magento\Framework\Event\ObserverInterface
];
public const CONFIGS_PATHS_TO_TRACK = [
\Magento\Directory\Model\Currency::XML_PATH_CURRENCY_BASE,
\Magento\Directory\Helper\Data::XML_PATH_DEFAULT_COUNTRY,
\Afterpay\Afterpay\Model\Config::XML_PATH_PAYPAL_MERCHANT_COUNTRY
\Magento\Directory\Helper\Data::XML_PATH_DEFAULT_COUNTRY
];

public function __construct(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php declare(strict_types=1);

namespace Afterpay\Afterpay\Plugin\Sales\Model\Service\CreditmemoService;

use Afterpay\Afterpay\Gateway\Config\Config;
use Afterpay\Afterpay\Model\Payment\AdditionalInformationInterface;
use Afterpay\Afterpay\Model\PaymentStateInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\CreditmemoManagementInterface;
use Magento\Sales\Api\Data\CreditmemoInterface;

class AdjustmentAmountValidation
{
private const ALLOWED_PAYMENT_STATES = [
PaymentStateInterface::CAPTURED,
PaymentStateInterface::PARTIALLY_CAPTURED
];

public function beforeRefund(
CreditmemoManagementInterface $subject,
CreditmemoInterface $creditmemo,
$offlineRequested = false
) {
$order = $creditmemo->getOrder();
if (($creditmemo->getBaseAdjustmentPositive() != 0 || $creditmemo->getBaseAdjustmentNegative() != 0)
&& $order->getPayment()->getMethod() === Config::CODE
&& !in_array(
$order->getPayment()->getAdditionalInformation(AdditionalInformationInterface::AFTERPAY_PAYMENT_STATE),
self::ALLOWED_PAYMENT_STATES
)) {
throw new LocalizedException(__(
'You cannot use adjustments for a payment with a status'
. ' that does not equal "CAPTURED" or "PARTIALLY_CAPTURED" for the current payment method.'
));
}

return [$creditmemo, $offlineRequested];
}
}
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"license": "Apache-2.0",
"type": "magento2-module",
"description": "Magento 2 Afterpay Payment Module",
"version": "4.3.1",
"version": "4.3.2",
"require": {
"php": "~7.1.3||~7.2.0||~7.3.0||~7.4.0",
"magento/framework": "^102.0",
Expand Down
4 changes: 4 additions & 0 deletions etc/di.xml
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,10 @@
<plugin name="afterpay_replace_invoice_amount_for_cbt"
type="Afterpay\Afterpay\Plugin\Model\Order\Payment\Operations\CaptureOperation"/>
</type>
<type name="Magento\Sales\Api\CreditmemoManagementInterface">
<plugin name="afterpay_replace_adjustment amount_validation"
type="Afterpay\Afterpay\Plugin\Sales\Model\Service\CreditmemoService\AdjustmentAmountValidation"/>
</type>
<type name="Magento\Sales\Model\Order\Payment\State\CaptureCommand">
<plugin name="afterpay_change_captured_comment" type="Afterpay\Afterpay\Plugin\Order\Payment\State\CaptureCommand"/>
</type>
Expand Down
2 changes: 1 addition & 1 deletion etc/module.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Afterpay_Afterpay" setup_version="4.3.1">
<module name="Afterpay_Afterpay" setup_version="4.3.2">
<sequence>
<module name="Magento_Payment"/>
<module name="Magento_Checkout"/>
Expand Down
2 changes: 1 addition & 1 deletion view/frontend/web/js/view/payment/info/checkout-note.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ define([
},
_getWidgetAmount: function (totals) {
let amount = window.checkoutConfig.payment.afterpay.isCBTCurrency
? totals.grand_total + totals.tax_amount
? totals.grand_total
: totals.base_grand_total;
let currency = window.checkoutConfig.payment.afterpay.isCBTCurrency
? totals.quote_currency_code
Expand Down
Loading

0 comments on commit ab90df3

Please sign in to comment.