Skip to content

Commit

Permalink
Release version 5.3.2
Browse files Browse the repository at this point in the history
  • Loading branch information
afterpayplugins committed Aug 7, 2024
1 parent 6e8f4a1 commit f59477e
Show file tree
Hide file tree
Showing 18 changed files with 153 additions and 81 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 @@ -40,10 +40,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 @@ -25,17 +25,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
10 changes: 5 additions & 5 deletions Gateway/Validator/StockItemsValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class StockItemsValidator implements \Afterpay\Afterpay\Model\Spi\StockItemsVali
{
private \Magento\InventoryCatalogApi\Model\IsSingleSourceModeInterface $isSingleSourceMode;
private \Afterpay\Afterpay\Model\Spi\SourceValidatorServiceInterface $sourceValidatorService;
private \Magento\InventoryShipping\Model\SourceDeductionRequestFromShipmentFactory $sourceDeductionRequestFromShipmentFactory;
private \Magento\InventoryShipping\Model\SourceDeductionRequestFromShipmentFactory $shipmentFactory;
private \Magento\InventoryShipping\Model\GetItemsToDeductFromShipment $getItemsToDeductFromShipment;
private \Magento\InventoryCatalogApi\Api\DefaultSourceProviderInterface $defaultSourceProvider;

Expand All @@ -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
4 changes: 2 additions & 2 deletions Model/GraphQl/Resolver/CreateAfterpayCheckout.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ public function resolve(Field $field, $context, ResolveInfo $info, array $value
{
try {
/** @phpstan-ignore-next-line */
$storeId = $context->getExtensionAttributes()->getStore()->getId();
$websiteId = $context->getExtensionAttributes()->getStore()->getWebsiteId();

if (!$this->config->getIsPaymentActive((int)$storeId)) {
if (!$this->config->getIsPaymentActive((int)$websiteId)) {
throw new GraphQlInputException(__('Afterpay payment method is not active'));
}

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
49 changes: 47 additions & 2 deletions Model/Order/CreditMemo/OrdersRetriever.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,42 @@
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\Serialize\SerializerInterface;
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 $orderCollectionFactory;
private ResourceConnection $resourceConnection;
private CollectionFactory $tokensCollectionFactory;
private DateTime $dateTime;
private SerializerInterface $serializer;
private LoggerInterface $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 +69,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 @@ -67,11 +67,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
Expand Up @@ -2,22 +2,38 @@

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(
\Magento\Sales\Api\CreditmemoManagementInterface $subject,
\Magento\Sales\Api\Data\CreditmemoInterface $creditmemo,
$offlineRequested = false
CreditmemoManagementInterface $subject,
CreditmemoInterface $creditmemo,
$offlineRequested = false
) {
$order = $creditmemo->getOrder();
if (($creditmemo->getBaseAdjustmentPositive() != 0 || $creditmemo->getBaseAdjustmentNegative() != 0)
&& $order->getPayment()->getMethod() === \Afterpay\Afterpay\Gateway\Config\Config::CODE
&& $order->getState() !== \Magento\Sales\Model\Order::STATE_COMPLETE
) {
throw new \Magento\Framework\Exception\LocalizedException(
__("You can't use Adjustment amount for order with status that isn't complete for the current payment method")
);
&& $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": "5.3.1",
"version": "5.3.2",
"require": {
"php": ">=7.4.0",
"magento/framework": "^103.0",
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="5.3.1">
<module name="Afterpay_Afterpay" setup_version="5.3.2">
<sequence>
<module name="Magento_Payment"/>
<module name="Magento_Checkout"/>
Expand Down
Loading

0 comments on commit f59477e

Please sign in to comment.