From 442c78201f563e22e4e0bfb7e3cf68e735c81646 Mon Sep 17 00:00:00 2001 From: Afterpay Plugins Date: Thu, 1 Feb 2024 12:43:16 +1100 Subject: [PATCH] Release version 5.3.0 --- Api/Data/CheckoutInterface.php | 10 +- .../System/Config/Button/LimitUpdate.php | 2 +- .../Form/Field/CBTAvailableCurrencies.php | 4 +- .../System/Config/Form/Field/Version.php | 2 +- Controller/Payment/Capture.php | 4 +- ...GetMerchantConfigurationCommandWrapper.php | 6 +- Gateway/Config/Config.php | 2 +- .../CaptureErrorMessageMapper.php | 5 +- Gateway/Http/TransferFactory.php | 6 +- .../TransferFactory/UserAgentProvider.php | 1 + .../CaptureVirtualProductsHandler.php | 2 +- .../CheckoutItemsAmountValidationHandler.php | 2 +- .../ChannelsConfigurationHandler.php | 26 +++-- .../LimitConfigurationHandler.php | 2 +- .../SpecificCountriesConfigurationHandler.php | 2 +- .../Validator/CaptureResponseValidator.php | 4 +- Model/CheckoutConfigProvider.php | 1 + Model/Config.php | 95 +++++++++++++------ Model/Config/Source/ApiMode.php | 4 +- Model/Config/Source/PaymentFlow.php | 4 +- .../Resolver/CreateAfterpayCheckout.php | 62 +++++++----- Model/Order/OrderItemProvider.php | 4 +- Model/Order/Payment/Auth/ExpiryDate.php | 2 +- .../AdditionalInformationInterface.php | 12 +-- Model/Payment/AmountProcessor/CreditMemo.php | 10 +- .../Payment/Capture/CancelOrderProcessor.php | 2 +- Model/Payment/Capture/PlaceOrderProcessor.php | 24 ++--- Model/Payment/PaymentErrorProcessor.php | 4 +- Model/PaymentStateInterface.php | 8 +- Model/ResourceModel/Token.php | 3 +- .../Shipment/Express/CreateShippingOption.php | 2 +- Model/SourceValidatorService.php | 16 ++-- Model/Spi/SourceValidatorServiceInterface.php | 2 +- .../StockItemsValidatorProxy.php | 14 +-- Model/Url/UrlBuilder.php | 4 +- Observer/Adminhtml/ConfigSaveAfter.php | 4 +- Observer/AuthCaptureAfterCreditMemo.php | 3 +- .../AddLastSelectedShippingRate.php | 49 +++++++--- .../AdjustmentAmountValidation.php | 2 +- Setup/Patch/Data/MigrateTokens.php | 20 ++-- .../GraphQl/CreateAfterpayCheckoutTest.php | 6 +- .../AmountProcessor/CreditMemoTest.php | 6 ++ .../Express/CreateShippingOptionTest.php | 46 ++++++--- .../Service/Payment/Auth/ExpiryDateTest.php | 2 +- ViewModel/Container/Cta/Lib.php | 2 +- .../ExpressCheckout/ExpressCheckout.php | 11 +-- composer.json | 2 +- etc/config.xml | 1 + etc/module.xml | 2 +- .../view/container/express-checkout/button.js | 1 + .../web/js/view/payment/info/checkout-note.js | 34 +++---- .../view/payment/method-renderer/afterpay.js | 53 ++++++++++- .../web/template/payment/afterpay.html | 14 ++- 53 files changed, 385 insertions(+), 226 deletions(-) diff --git a/Api/Data/CheckoutInterface.php b/Api/Data/CheckoutInterface.php index 4c5530e..5da20ad 100644 --- a/Api/Data/CheckoutInterface.php +++ b/Api/Data/CheckoutInterface.php @@ -11,11 +11,11 @@ interface CheckoutInterface /**#@+ * Checkout result keys */ - const AFTERPAY_TOKEN = 'afterpay_token'; - const AFTERPAY_AUTH_TOKEN_EXPIRES = 'afterpay_expires'; - const AFTERPAY_REDIRECT_CHECKOUT_URL = 'afterpay_redirectCheckoutUrl'; - const AFTERPAY_IS_CBT_CURRENCY = 'afterpay_is_cbt_currency'; - const AFTERPAY_CBT_CURRENCY = 'afterpay_cbt_currency'; + public const AFTERPAY_TOKEN = 'afterpay_token'; + public const AFTERPAY_AUTH_TOKEN_EXPIRES = 'afterpay_expires'; + public const AFTERPAY_REDIRECT_CHECKOUT_URL = 'afterpay_redirectCheckoutUrl'; + public const AFTERPAY_IS_CBT_CURRENCY = 'afterpay_is_cbt_currency'; + public const AFTERPAY_CBT_CURRENCY = 'afterpay_cbt_currency'; /**#@-*/ /** diff --git a/Block/Adminhtml/System/Config/Button/LimitUpdate.php b/Block/Adminhtml/System/Config/Button/LimitUpdate.php index 753377a..440ec10 100644 --- a/Block/Adminhtml/System/Config/Button/LimitUpdate.php +++ b/Block/Adminhtml/System/Config/Button/LimitUpdate.php @@ -6,7 +6,7 @@ class LimitUpdate extends \Magento\Config\Block\System\Config\Form\Field { - const TEMPLATE = 'Afterpay_Afterpay::system/config/button/update.phtml'; + public const TEMPLATE = 'Afterpay_Afterpay::system/config/button/update.phtml'; public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element) { diff --git a/Block/Adminhtml/System/Config/Form/Field/CBTAvailableCurrencies.php b/Block/Adminhtml/System/Config/Form/Field/CBTAvailableCurrencies.php index 4252fba..984655c 100644 --- a/Block/Adminhtml/System/Config/Form/Field/CBTAvailableCurrencies.php +++ b/Block/Adminhtml/System/Config/Form/Field/CBTAvailableCurrencies.php @@ -32,8 +32,8 @@ protected function _renderValue(\Magento\Framework\Data\Form\Element\AbstractEle } foreach ($CbtAvailableCurrencies as $currencyCode => $currency) { - $newValue .= $currencyCode . '(min:' . $currency['minimumAmount']['amount'] - . ',max:' . $currency['maximumAmount']['amount'] . ') '; + $min = $currency['minimumAmount']['amount'] ?? '0'; + $newValue .= $currencyCode . '(min:' . $min . ',max:' . $currency['maximumAmount']['amount'] . ') '; } $element->setValue($newValue); } catch (\Exception $e) { diff --git a/Block/Adminhtml/System/Config/Form/Field/Version.php b/Block/Adminhtml/System/Config/Form/Field/Version.php index a508bc8..0338670 100644 --- a/Block/Adminhtml/System/Config/Form/Field/Version.php +++ b/Block/Adminhtml/System/Config/Form/Field/Version.php @@ -9,7 +9,7 @@ class Version extends \Magento\Config\Block\System\Config\Form\Field { - const MODULE_NAME = "Afterpay_Afterpay"; + public const MODULE_NAME = "Afterpay_Afterpay"; private \Magento\Framework\Module\ResourceInterface $resource; diff --git a/Controller/Payment/Capture.php b/Controller/Payment/Capture.php index 079e4db..a241421 100644 --- a/Controller/Payment/Capture.php +++ b/Controller/Payment/Capture.php @@ -13,8 +13,8 @@ class Capture implements HttpGetActionInterface { - const CHECKOUT_STATUS_CANCELLED = 'CANCELLED'; - const CHECKOUT_STATUS_SUCCESS = 'SUCCESS'; + public const CHECKOUT_STATUS_CANCELLED = 'CANCELLED'; + public const CHECKOUT_STATUS_SUCCESS = 'SUCCESS'; private RequestInterface $request; private Session $session; private RedirectFactory $redirectFactory; diff --git a/Gateway/Command/GetMerchantConfigurationCommandWrapper.php b/Gateway/Command/GetMerchantConfigurationCommandWrapper.php index d370539..c14ad69 100644 --- a/Gateway/Command/GetMerchantConfigurationCommandWrapper.php +++ b/Gateway/Command/GetMerchantConfigurationCommandWrapper.php @@ -7,7 +7,7 @@ class GetMerchantConfigurationCommandWrapper implements \Magento\Payment\Gateway\CommandInterface { - const DEFAULT_WEBSITE_ID = 0; + public const DEFAULT_WEBSITE_ID = 0; private \Magento\Payment\Gateway\CommandInterface $merchantConfigurationCommand; private \Afterpay\Afterpay\Model\Config $afterpayConfig; @@ -48,6 +48,10 @@ public function execute(array $commandSubject) } $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); + } $this->debugLogger->setForceDebug($this->afterpayConfig->getIsDebug($websiteId)); return $this->merchantConfigurationCommand->execute($commandSubject); } catch (\Magento\Payment\Gateway\Command\CommandException $e) { diff --git a/Gateway/Config/Config.php b/Gateway/Config/Config.php index c3d84f4..905cb1f 100644 --- a/Gateway/Config/Config.php +++ b/Gateway/Config/Config.php @@ -4,7 +4,7 @@ class Config extends \Magento\Payment\Gateway\Config\Config { - const CODE = 'afterpay'; + public const CODE = 'afterpay'; public function __construct( \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig diff --git a/Gateway/ErrorMessageMapper/CaptureErrorMessageMapper.php b/Gateway/ErrorMessageMapper/CaptureErrorMessageMapper.php index f94ffcb..219ffa3 100644 --- a/Gateway/ErrorMessageMapper/CaptureErrorMessageMapper.php +++ b/Gateway/ErrorMessageMapper/CaptureErrorMessageMapper.php @@ -7,13 +7,14 @@ class CaptureErrorMessageMapper implements ErrorMessageMapperInterface { - public const STATUS_DECLINED_ERROR_MESSAGE = 'Aftepay payment declined. Please select an alternative payment method.'; + public const STATUS_DECLINED_ERROR_MESSAGE = 'Aftepay payment declined. Please select an alternative payment method.'; // @codingStandardsIgnoreLine public function getMessage(string $code) { + $message = (string)self::STATUS_DECLINED_ERROR_MESSAGE; switch ($code) { case CaptureResponseValidator::STATUS_DECLINED: - return __(self::STATUS_DECLINED_ERROR_MESSAGE); + return __($message); default: return null; } diff --git a/Gateway/Http/TransferFactory.php b/Gateway/Http/TransferFactory.php index 7d2d568..c4bb0a8 100644 --- a/Gateway/Http/TransferFactory.php +++ b/Gateway/Http/TransferFactory.php @@ -6,10 +6,10 @@ class TransferFactory implements \Magento\Payment\Gateway\Http\TransferFactoryInterface { - const METHOD_POST = "post"; - const METHOD_GET = "get"; + public const METHOD_POST = "post"; + public const METHOD_GET = "get"; - const ARGS = [ + public const ARGS = [ 'orderId', 'websiteId', 'storeId', diff --git a/Gateway/Http/TransferFactory/UserAgentProvider.php b/Gateway/Http/TransferFactory/UserAgentProvider.php index fa33039..e4c1010 100644 --- a/Gateway/Http/TransferFactory/UserAgentProvider.php +++ b/Gateway/Http/TransferFactory/UserAgentProvider.php @@ -41,5 +41,6 @@ public function provide(?int $websiteId = null): string return "AfterpayMagento2Plugin $moduleVersion ($magentoProductName $magentoProductEdition $magentoVersion) " . "PHPVersion: PHP/$phpVersion MerchantID: $afterpayMerchantId; MPID/$afterpayMPId; CAPAvailable/$CashAppPayAvailable; CAPEnabled/$CashAppPayEnabled; URL: $websiteDomain"; + } } diff --git a/Gateway/Response/CaptureVirtualProductsHandler.php b/Gateway/Response/CaptureVirtualProductsHandler.php index dd64625..1e40762 100644 --- a/Gateway/Response/CaptureVirtualProductsHandler.php +++ b/Gateway/Response/CaptureVirtualProductsHandler.php @@ -14,7 +14,7 @@ public function __construct( \Magento\Payment\Gateway\Data\PaymentDataObjectFactoryInterface $paymentDataObjectFactory, \Afterpay\Afterpay\Model\Payment\AmountProcessor\Order $orderAmountProcessor, \Magento\Payment\Gateway\CommandInterface $voidCommand - ){ + ) { $this->authCaptureCommand = $authCaptureCommand; $this->paymentDataObjectFactory = $paymentDataObjectFactory; $this->orderAmountProcessor = $orderAmountProcessor; diff --git a/Gateway/Response/Checkout/CheckoutItemsAmountValidationHandler.php b/Gateway/Response/Checkout/CheckoutItemsAmountValidationHandler.php index 30792d8..464ed67 100644 --- a/Gateway/Response/Checkout/CheckoutItemsAmountValidationHandler.php +++ b/Gateway/Response/Checkout/CheckoutItemsAmountValidationHandler.php @@ -10,7 +10,7 @@ public function handle(array $handlingSubject, array $response) $payment = $paymentDO->getPayment(); /** @var \Magento\Quote\Model\Quote $quote */ $quote = $payment->getQuote(); - $isCBTCurrency = $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY); + $isCBTCurrency = $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY); // @codingStandardsIgnoreLine $grandTotal = $isCBTCurrency ? $quote->getGrandTotal() : $quote->getBaseGrandTotal(); if (round(1 * $grandTotal, 2) != round(1 * $response['amount']['amount'], 2)) { diff --git a/Gateway/Response/MerchantConfiguration/ChannelsConfigurationHandler.php b/Gateway/Response/MerchantConfiguration/ChannelsConfigurationHandler.php index d54367b..8cbb527 100644 --- a/Gateway/Response/MerchantConfiguration/ChannelsConfigurationHandler.php +++ b/Gateway/Response/MerchantConfiguration/ChannelsConfigurationHandler.php @@ -8,33 +8,43 @@ class ChannelsConfigurationHandler implements HandlerInterface { private Config $config; + private \Psr\Log\LoggerInterface $logger; public function __construct( - Config $config - ) - { + Config $config, + \Psr\Log\LoggerInterface $logger + ) { $this->config = $config; + $this->logger = $logger; } public function handle(array $handlingSubject, array $response): void { $websiteId = (int)$handlingSubject['websiteId']; - if (isset($response['channels']) && is_array($response['channels'])) { + if (isset($response['channels']) && is_array($response['channels'])) { $getCashAppConfig = array_search("CASH_APP", array_column($response['channels'], 'name')); $isCashAppEnabled = 0; - if (isset($response['channels'][$getCashAppConfig])) { + + if ( isset($response['channels'][$getCashAppConfig]) && + isset($response['channels'][$getCashAppConfig]['name']) && + strtoupper($response['channels'][$getCashAppConfig]['name'])== "CASH_APP") { $cashappData=$response['channels'][$getCashAppConfig]; + if (isset($cashappData['enabled']) && $cashappData['enabled']==true && isset($cashappData['integrationCompleted']) && $cashappData['integrationCompleted']==true && isset($cashappData['enabledForOrders']) && $cashappData['enabledForOrders']==true) { $isCashAppEnabled = (int)$cashappData['enabled']; } - $this->config->setCashAppPayAvailable($isCashAppEnabled, $websiteId); + }else{ + if( $this->config->getCashAppPayActive($websiteId)==true) { + //Disable the Cash App Pay if it's not available for the Merchant + $this->config->setCashAppPayActive($isCashAppEnabled, $websiteId); + $this->logger->notice("Disable the Cash App Pay as it's not available for the Merchant"); + } } + $this->config->setCashAppPayAvailable($isCashAppEnabled, $websiteId); } } - - } diff --git a/Gateway/Response/MerchantConfiguration/LimitConfigurationHandler.php b/Gateway/Response/MerchantConfiguration/LimitConfigurationHandler.php index fdf1c99..2e78ecf 100644 --- a/Gateway/Response/MerchantConfiguration/LimitConfigurationHandler.php +++ b/Gateway/Response/MerchantConfiguration/LimitConfigurationHandler.php @@ -4,7 +4,7 @@ class LimitConfigurationHandler implements \Magento\Payment\Gateway\Response\HandlerInterface { - private \Afterpay\Afterpay\Model\Config $config; + private \Afterpay\Afterpay\Model\Config $config; public function __construct( \Afterpay\Afterpay\Model\Config $config diff --git a/Gateway/Response/MerchantConfiguration/SpecificCountriesConfigurationHandler.php b/Gateway/Response/MerchantConfiguration/SpecificCountriesConfigurationHandler.php index 78b5d0a..a8d3da0 100644 --- a/Gateway/Response/MerchantConfiguration/SpecificCountriesConfigurationHandler.php +++ b/Gateway/Response/MerchantConfiguration/SpecificCountriesConfigurationHandler.php @@ -4,7 +4,7 @@ class SpecificCountriesConfigurationHandler implements \Magento\Payment\Gateway\Response\HandlerInterface { - private \Afterpay\Afterpay\Model\Config $config; + private \Afterpay\Afterpay\Model\Config $config; public function __construct( \Afterpay\Afterpay\Model\Config $config diff --git a/Gateway/Validator/CaptureResponseValidator.php b/Gateway/Validator/CaptureResponseValidator.php index d0de33d..c786860 100644 --- a/Gateway/Validator/CaptureResponseValidator.php +++ b/Gateway/Validator/CaptureResponseValidator.php @@ -4,8 +4,8 @@ class CaptureResponseValidator extends \Magento\Payment\Gateway\Validator\AbstractValidator { - const STATUS_DECLINED = 'DECLINED'; - const STATUS_APPROVED = 'APPROVED'; + public const STATUS_DECLINED = 'DECLINED'; + public const STATUS_APPROVED = 'APPROVED'; public function validate(array $validationSubject): \Magento\Payment\Gateway\Validator\ResultInterface { diff --git a/Model/CheckoutConfigProvider.php b/Model/CheckoutConfigProvider.php index b341941..8c70461 100644 --- a/Model/CheckoutConfigProvider.php +++ b/Model/CheckoutConfigProvider.php @@ -34,6 +34,7 @@ public function getConfig(): array 'isCBTCurrency' => $this->checkCBTCurrencyAvailability->checkByQuote($quote), 'consumerLendingEnabled' => $this->config->getConsumerLendingEnabled(), 'consumerLendingMinimumAmount' => $this->config->getConsumerLendingMinAmount(), + 'mpid' => $this->config->getPublicId(), ] ] ]; diff --git a/Model/Config.php b/Model/Config.php index b0f52f5..07aa73a 100644 --- a/Model/Config.php +++ b/Model/Config.php @@ -10,33 +10,36 @@ class Config { - const XML_PATH_PAYMENT_ACTIVE = 'payment/afterpay/active'; - const XML_PATH_API_MODE = 'payment/afterpay/api_mode'; - const XML_PATH_DEBUG = 'payment/afterpay/debug'; - const XML_PATH_ENABLE_CTA_PRODUCT = 'payment/afterpay/enable_cta_product_page'; - const XML_PATH_ENABLE_CTA_MINI_CART = 'payment/afterpay/enable_cta_mini_cart'; - const XML_PATH_ENABLE_CTA_CART_PAGE = 'payment/afterpay/enable_cta_cart_page'; - const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_PRODUCT = 'payment/afterpay/enable_express_checkout_product_page'; - const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_MINI_CART = 'payment/afterpay/enable_express_checkout_mini_cart'; - const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_CART_PAGE = 'payment/afterpay/enable_express_checkout_cart_page'; - const XML_PATH_MERCHANT_ID = 'payment/afterpay/merchant_id'; - const XML_PATH_MERCHANT_KEY = 'payment/afterpay/merchant_key'; - const XML_PATH_PAYMENT_FLOW = 'payment/afterpay/payment_flow'; - const XML_PATH_MIN_LIMIT = 'payment/afterpay/min_order_total'; - const XML_PATH_MAX_LIMIT = 'payment/afterpay/max_order_total'; - const XML_PATH_CBT_CURRENCY_LIMITS = 'payment/afterpay/cbt_currency_limits'; - const XML_PATH_EXCLUDE_CATEGORIES = 'payment/afterpay/exclude_categories'; - 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'; - const XML_PATH_ENABLE_REVERSAL = 'payment/afterpay/enable_reversal'; - const XML_PATH_MPID = 'payment/afterpay/public_id'; - const XML_PATH_CASHAPP_PAY_AVAILABLE = 'payment/afterpay/cash_app_pay_available'; - const XML_PATH_CASHAPP_PAY_ENABLE = 'payment/cashapp/active'; - const XML_PATH_CONSUMER_LENDING_ENABLED = 'payment/afterpay/consumer_lending_enabled'; - const XML_PATH_CONSUMER_LENDING_MIN_AMOUNT = 'payment/afterpay/consumer_lending_min_amount'; + + public const XML_PATH_PAYMENT_ACTIVE = 'payment/afterpay/active'; + public const XML_PATH_API_MODE = 'payment/afterpay/api_mode'; + public const XML_PATH_DEBUG = 'payment/afterpay/debug'; + public const XML_PATH_ENABLE_CTA_PRODUCT = 'payment/afterpay/enable_cta_product_page'; + public const XML_PATH_ENABLE_CTA_MINI_CART = 'payment/afterpay/enable_cta_mini_cart'; + public const XML_PATH_ENABLE_CTA_CART_PAGE = 'payment/afterpay/enable_cta_cart_page'; + public const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_PRODUCT = 'payment/afterpay/enable_express_checkout_product_page'; + public const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_MINI_CART = 'payment/afterpay/enable_express_checkout_mini_cart'; + public const XML_PATH_ENABLE_EXPRESS_CHECKOUT_ACTION_CART_PAGE = 'payment/afterpay/enable_express_checkout_cart_page'; + public const XML_PATH_ADD_LAST_SELECTED_SHIP_RATE = 'payment/afterpay/add_last_selected_ship_rate'; + public const XML_PATH_MERCHANT_ID = 'payment/afterpay/merchant_id'; + public const XML_PATH_MERCHANT_KEY = 'payment/afterpay/merchant_key'; + public const XML_PATH_PAYMENT_FLOW = 'payment/afterpay/payment_flow'; + public const XML_PATH_MIN_LIMIT = 'payment/afterpay/min_order_total'; + public const XML_PATH_MAX_LIMIT = 'payment/afterpay/max_order_total'; + public const XML_PATH_CBT_CURRENCY_LIMITS = 'payment/afterpay/cbt_currency_limits'; + public const XML_PATH_EXCLUDE_CATEGORIES = 'payment/afterpay/exclude_categories'; + public const XML_PATH_ALLOW_SPECIFIC_COUNTRIES = 'payment/afterpay/allowspecific'; + public const XML_PATH_SPECIFIC_COUNTRIES = 'payment/afterpay/specificcountry'; + public const XML_PATH_ALLOWED_MERCHANT_COUNTRIES = 'payment/afterpay/allowed_merchant_countries'; + public const XML_PATH_ALLOWED_MERCHANT_CURRENCIES = 'payment/afterpay/allowed_merchant_currencies'; + public const XML_PATH_PAYPAL_MERCHANT_COUNTRY = 'paypal/general/merchant_country'; + public const XML_PATH_ENABLE_REVERSAL = 'payment/afterpay/enable_reversal'; + public const XML_PATH_MPID = 'payment/afterpay/public_id'; + public const XML_PATH_CASHAPP_PAY_AVAILABLE = 'payment/afterpay/cash_app_pay_available'; + public const XML_PATH_CASHAPP_PAY_ACTIVE = 'payment/cashapp/active'; + public const XML_PATH_CONSUMER_LENDING_ENABLED = 'payment/afterpay/consumer_lending_enabled'; + public const XML_PATH_CONSUMER_LENDING_MIN_AMOUNT = 'payment/afterpay/consumer_lending_min_amount'; + private ScopeConfigInterface $scopeConfig; private WriterInterface $writer; private ResourceConnection $resourceConnection; @@ -500,7 +503,7 @@ public function getCashAppPayAvailable(?int $scopeCode = null): bool public function getCashAppPayEnabled(?int $scopeCode = null): bool { return (bool)$this->scopeConfig->getValue( - self::XML_PATH_CASHAPP_PAY_ENABLE, + self::XML_PATH_CASHAPP_PAY_ACTIVE, ScopeInterface::SCOPE_WEBSITE, $scopeCode ); @@ -563,4 +566,40 @@ public function getConsumerLendingMinAmount(?int $scopeCode = null): float $scopeCode ); } + + public function getAddLastSelectedShipRate(?int $scopeCode = null): bool + { + return $this->scopeConfig->isSetFlag( + self::XML_PATH_ADD_LAST_SELECTED_SHIP_RATE, + ScopeInterface::SCOPE_WEBSITE, + $scopeCode + ); + } + + public function setCashAppPayActive(int $value, int $scopeId = 0): self + { + if ($scopeId) { + $this->writer->save( + self::XML_PATH_CASHAPP_PAY_ACTIVE, + $value, + ScopeInterface::SCOPE_WEBSITES, + $scopeId + ); + return $this; + } + $this->writer->save( + self::XML_PATH_CASHAPP_PAY_ACTIVE, + $value + ); + return $this; + } + + public function getCashAppPayActive(?int $scopeCode = null): bool + { + return (bool)$this->scopeConfig->isSetFlag( + self::XML_PATH_CASHAPP_PAY_ACTIVE, + ScopeInterface::SCOPE_WEBSITE, + $scopeCode + ); + } } diff --git a/Model/Config/Source/ApiMode.php b/Model/Config/Source/ApiMode.php index 25aca3b..4176ebb 100644 --- a/Model/Config/Source/ApiMode.php +++ b/Model/Config/Source/ApiMode.php @@ -4,8 +4,8 @@ class ApiMode implements \Magento\Framework\Data\OptionSourceInterface { - const SANDBOX = 'sandbox'; - const PRODUCTION = 'production'; + public const SANDBOX = 'sandbox'; + public const PRODUCTION = 'production'; public function toOptionArray(): array { diff --git a/Model/Config/Source/PaymentFlow.php b/Model/Config/Source/PaymentFlow.php index b5e7e67..2620237 100644 --- a/Model/Config/Source/PaymentFlow.php +++ b/Model/Config/Source/PaymentFlow.php @@ -4,8 +4,8 @@ class PaymentFlow implements \Magento\Framework\Data\OptionSourceInterface { - const IMMEDIATE = 'immediate'; - const DEFERRED = 'deferred'; + public const IMMEDIATE = 'immediate'; + public const DEFERRED = 'deferred'; public function toOptionArray(): array { diff --git a/Model/GraphQl/Resolver/CreateAfterpayCheckout.php b/Model/GraphQl/Resolver/CreateAfterpayCheckout.php index 784f0a3..0a27791 100644 --- a/Model/GraphQl/Resolver/CreateAfterpayCheckout.php +++ b/Model/GraphQl/Resolver/CreateAfterpayCheckout.php @@ -2,21 +2,27 @@ namespace Afterpay\Afterpay\Model\GraphQl\Resolver; +use Afterpay\Afterpay\Api\CheckoutManagementInterface; use Afterpay\Afterpay\Api\Data\CheckoutInterface; +use Afterpay\Afterpay\Api\Data\RedirectPathInterfaceFactory; +use Afterpay\Afterpay\Model\Config; +use GraphQL\Error\Error; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\GraphQl\Config\Element\Field; use Magento\Framework\GraphQl\Exception\GraphQlInputException; +use Magento\Framework\GraphQl\Query\ResolverInterface; use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; -class CreateAfterpayCheckout implements \Magento\Framework\GraphQl\Query\ResolverInterface +class CreateAfterpayCheckout implements ResolverInterface { - private \Afterpay\Afterpay\Model\Config $config; - private \Afterpay\Afterpay\Api\CheckoutManagementInterface $afterpayCheckoutManagement; - private \Afterpay\Afterpay\Api\Data\RedirectPathInterfaceFactory $redirectPathFactory; + private Config $config; + private CheckoutManagementInterface $afterpayCheckoutManagement; + private RedirectPathInterfaceFactory $redirectPathFactory; public function __construct( - \Afterpay\Afterpay\Model\Config $config, - \Afterpay\Afterpay\Api\CheckoutManagementInterface $afterpayCheckoutManagement, - \Afterpay\Afterpay\Api\Data\RedirectPathInterfaceFactory $redirectPathFactory + Config $config, + CheckoutManagementInterface $afterpayCheckoutManagement, + RedirectPathInterfaceFactory $redirectPathFactory ) { $this->config = $config; $this->afterpayCheckoutManagement = $afterpayCheckoutManagement; @@ -28,30 +34,34 @@ public function __construct( */ public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null): array { - /** @phpstan-ignore-next-line */ - $storeId = $context->getExtensionAttributes()->getStore()->getId(); + try { + /** @phpstan-ignore-next-line */ + $storeId = $context->getExtensionAttributes()->getStore()->getId(); - if (!$this->config->getIsPaymentActive((int)$storeId)) { - throw new GraphQlInputException(__('Afterpay payment method is not active')); - } + if (!$this->config->getIsPaymentActive((int)$storeId)) { + throw new GraphQlInputException(__('Afterpay payment method is not active')); + } - if (!$args || !$args['input']) { - throw new \InvalidArgumentException('Required params cart_id and redirect_path are missing'); - } + if (!$args || !$args['input']) { + throw new \InvalidArgumentException('Required params cart_id and redirect_path are missing'); + } - $maskedCartId = $args['input']['cart_id']; - $afterpayRedirectPath = $args['input']['redirect_path']; + $maskedCartId = $args['input']['cart_id']; + $afterpayRedirectPath = $args['input']['redirect_path']; - $redirectUrls = $this->redirectPathFactory->create() - ->setConfirmPath($afterpayRedirectPath['confirm_path']) - ->setCancelPath($afterpayRedirectPath['cancel_path']); + $redirectUrls = $this->redirectPathFactory->create() + ->setConfirmPath($afterpayRedirectPath['confirm_path']) + ->setCancelPath($afterpayRedirectPath['cancel_path']); - $checkoutResult = $this->afterpayCheckoutManagement->create($maskedCartId, $redirectUrls); + $checkoutResult = $this->afterpayCheckoutManagement->create($maskedCartId, $redirectUrls); - return [ - CheckoutInterface::AFTERPAY_TOKEN => $checkoutResult->getAfterpayToken(), - CheckoutInterface::AFTERPAY_AUTH_TOKEN_EXPIRES => $checkoutResult->getAfterpayAuthTokenExpires(), - CheckoutInterface::AFTERPAY_REDIRECT_CHECKOUT_URL => $checkoutResult->getAfterpayRedirectCheckoutUrl() - ]; + return [ + CheckoutInterface::AFTERPAY_TOKEN => $checkoutResult->getAfterpayToken(), + CheckoutInterface::AFTERPAY_AUTH_TOKEN_EXPIRES => $checkoutResult->getAfterpayAuthTokenExpires(), + CheckoutInterface::AFTERPAY_REDIRECT_CHECKOUT_URL => $checkoutResult->getAfterpayRedirectCheckoutUrl() + ]; + } catch (LocalizedException $exception) { + throw new Error($exception->getMessage()); + } } } diff --git a/Model/Order/OrderItemProvider.php b/Model/Order/OrderItemProvider.php index 0c795dd..b4c64d8 100644 --- a/Model/Order/OrderItemProvider.php +++ b/Model/Order/OrderItemProvider.php @@ -6,8 +6,8 @@ class OrderItemProvider { - const ITEM_SHIPPED = 'shipped'; - const ITEM_REFUNDED = 'refunded'; + public const ITEM_SHIPPED = 'shipped'; + public const ITEM_REFUNDED = 'refunded'; private \Afterpay\Afterpay\Model\Order\OrderItemInterfaceFactory $orderItemFactory; diff --git a/Model/Order/Payment/Auth/ExpiryDate.php b/Model/Order/Payment/Auth/ExpiryDate.php index 686fe44..3ad7f46 100644 --- a/Model/Order/Payment/Auth/ExpiryDate.php +++ b/Model/Order/Payment/Auth/ExpiryDate.php @@ -4,7 +4,7 @@ class ExpiryDate { - const FORMAT = 'Y-m-d H:i T'; + public const FORMAT = 'Y-m-d H:i T'; private \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone; diff --git a/Model/Payment/AdditionalInformationInterface.php b/Model/Payment/AdditionalInformationInterface.php index 28a3400..bf90cc2 100644 --- a/Model/Payment/AdditionalInformationInterface.php +++ b/Model/Payment/AdditionalInformationInterface.php @@ -4,10 +4,10 @@ interface AdditionalInformationInterface { - const AFTERPAY_ORDER_ID = 'afterpay_order_id'; - const AFTERPAY_OPEN_TO_CAPTURE_AMOUNT = 'afterpay_open_to_capture_amount'; - const AFTERPAY_PAYMENT_STATE = 'afterpay_payment_state'; - const AFTERPAY_AUTH_EXPIRY_DATE = 'afterpay_auth_expiry_date'; - const AFTERPAY_ROLLOVER_DISCOUNT = 'afterpay_rollover_discount'; - const AFTERPAY_CAPTURED_DISCOUNT = 'afterpay_captured_discount'; + public const AFTERPAY_ORDER_ID = 'afterpay_order_id'; + public const AFTERPAY_OPEN_TO_CAPTURE_AMOUNT = 'afterpay_open_to_capture_amount'; + public const AFTERPAY_PAYMENT_STATE = 'afterpay_payment_state'; + public const AFTERPAY_AUTH_EXPIRY_DATE = 'afterpay_auth_expiry_date'; + public const AFTERPAY_ROLLOVER_DISCOUNT = 'afterpay_rollover_discount'; + public const AFTERPAY_CAPTURED_DISCOUNT = 'afterpay_captured_discount'; } diff --git a/Model/Payment/AmountProcessor/CreditMemo.php b/Model/Payment/AmountProcessor/CreditMemo.php index 41990a5..fd5061c 100644 --- a/Model/Payment/AmountProcessor/CreditMemo.php +++ b/Model/Payment/AmountProcessor/CreditMemo.php @@ -19,6 +19,7 @@ public function __construct( public function process(\Magento\Sales\Model\Order\Payment $payment): array { $amountToRefund = $amountToVoid = 0; + $creditmemo = $payment->getCreditmemo(); foreach ($creditmemo->getAllItems() as $creditmemoItem) { $orderItem = $creditmemoItem->getOrderItem(); @@ -44,6 +45,7 @@ public function process(\Magento\Sales\Model\Order\Payment $payment): array } $this->processForCapturedAndRefunded($payment, $orderItem, $creditmemoItem, $amountToRefund, $amountToVoid); + } $this->processShipmentAmount($payment, $creditmemo, $amountToRefund, $amountToVoid); @@ -61,7 +63,7 @@ private function processAdjustmentAmount( float &$amountToRefund): void { $additionalInfo = $payment->getAdditionalInformation(); - $paymentState = $additionalInfo[\Afterpay\Afterpay\Model\Payment\AdditionalInformationInterface::AFTERPAY_PAYMENT_STATE] ?? ''; + $paymentState = $additionalInfo[\Afterpay\Afterpay\Model\Payment\AdditionalInformationInterface::AFTERPAY_PAYMENT_STATE] ?? ''; // @codingStandardsIgnoreLine $creditmemo = $payment->getCreditmemo(); if ($paymentState === \Afterpay\Afterpay\Model\PaymentStateInterface::AUTH_APPROVED) { @@ -116,7 +118,7 @@ private function processForCapturedAndRefunded( (float)($creditmemoItem->getQty() - $allowedToRefundQty) ); } else { - $amountToRefund += $this->calculateItemPrice($payment, $creditmemoItem, (float)$creditmemoItem->getQty()); + $amountToRefund += $this->calculateItemPrice($payment, $creditmemoItem, (float)$creditmemoItem->getQty()); // @codingStandardsIgnoreLine } } else { $amountToVoid += $this->calculateItemPrice($payment, $creditmemoItem, (float)$creditmemoItem->getQty()); @@ -193,8 +195,8 @@ private function calculateItemPrice( \Magento\Sales\Model\Order\Creditmemo\Item $item, float $qty ): float { - $isCBTCurrency = $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY); - $rowTotal = $isCBTCurrency ? $this->priceRenderer->getTotalAmount($item) : $this->priceRenderer->getBaseTotalAmount($item); + $isCBTCurrency = $payment->getAdditionalInformation(\Afterpay\Afterpay\Api\Data\CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY); // @codingStandardsIgnoreLine + $rowTotal = $isCBTCurrency ? $this->priceRenderer->getTotalAmount($item) : $this->priceRenderer->getBaseTotalAmount($item); // @codingStandardsIgnoreLine $pricePerItem = $rowTotal / $item->getQty(); return $qty * $pricePerItem; diff --git a/Model/Payment/Capture/CancelOrderProcessor.php b/Model/Payment/Capture/CancelOrderProcessor.php index 4b9cab3..7a975e1 100644 --- a/Model/Payment/Capture/CancelOrderProcessor.php +++ b/Model/Payment/Capture/CancelOrderProcessor.php @@ -41,7 +41,7 @@ public function execute(\Magento\Quote\Model\Quote\Payment $payment, int $quoteI throw new \Magento\Framework\Exception\LocalizedException( __( 'There was a problem placing your order. Your Afterpay order %1 is refunded.', - $payment->getAdditionalInformation(\Afterpay\Afterpay\Model\Payment\AdditionalInformationInterface::AFTERPAY_ORDER_ID) + $payment->getAdditionalInformation(\Afterpay\Afterpay\Model\Payment\AdditionalInformationInterface::AFTERPAY_ORDER_ID) // @codingStandardsIgnoreLine ) ); } diff --git a/Model/Payment/Capture/PlaceOrderProcessor.php b/Model/Payment/Capture/PlaceOrderProcessor.php index 42cab1f..be9709f 100644 --- a/Model/Payment/Capture/PlaceOrderProcessor.php +++ b/Model/Payment/Capture/PlaceOrderProcessor.php @@ -55,21 +55,21 @@ public function execute(Quote $quote, CommandInterface $checkoutDataCommand, str $payment = $quote->getPayment(); try { - $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_TOKEN, $afterpayOrderToken); - $isCBTCurrencyAvailable = $this->checkCBTCurrencyAvailability->checkByQuote($quote); - $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY, $isCBTCurrencyAvailable); - $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_CBT_CURRENCY, $quote->getQuoteCurrencyCode()); + $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_TOKEN, $afterpayOrderToken); + $isCBTCurrencyAvailable = $this->checkCBTCurrencyAvailability->checkByQuote($quote); + $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_IS_CBT_CURRENCY, $isCBTCurrencyAvailable); + $payment->setAdditionalInformation(CheckoutInterface::AFTERPAY_CBT_CURRENCY, $quote->getQuoteCurrencyCode()); - if (!$quote->getCustomerId()) { - $quote->setCustomerEmail($quote->getBillingAddress()->getEmail()) - ->setCustomerIsGuest(true) - ->setCustomerGroupId(GroupInterface::NOT_LOGGED_IN_ID); - } + if (!$quote->getCustomerId()) { + $quote->setCustomerEmail($quote->getBillingAddress()->getEmail()) + ->setCustomerIsGuest(true) + ->setCustomerGroupId(GroupInterface::NOT_LOGGED_IN_ID); + } - $checkoutDataCommand->execute(['payment' => $this->paymentDataObjectFactory->create($payment)]); - $this->checkoutSession->setAfterpayRedirect(true); + $checkoutDataCommand->execute(['payment' => $this->paymentDataObjectFactory->create($payment)]); + $this->checkoutSession->setAfterpayRedirect(true); - $orderId = (int)$this->cartManagement->placeOrder($quote->getId()); + $orderId = (int)$this->cartManagement->placeOrder($quote->getId()); } catch (\Throwable $e) { $orderId = $this->paymentErrorProcessor->execute($quote, $e, $payment); } diff --git a/Model/Payment/PaymentErrorProcessor.php b/Model/Payment/PaymentErrorProcessor.php index 0fc7dea..d3043df 100644 --- a/Model/Payment/PaymentErrorProcessor.php +++ b/Model/Payment/PaymentErrorProcessor.php @@ -36,7 +36,8 @@ public function __construct( public function execute(Quote $quote, \Throwable $e, Payment $payment): int { $this->logger->critical('Order placement is failed with error: ' . PHP_EOL . $e); - if (($this->checkoutSession->getLastSuccessQuoteId() == $quote->getId()) && $this->checkoutSession->getLastOrderId()) { + if (($this->checkoutSession->getLastSuccessQuoteId() == $quote->getId()) && + $this->checkoutSession->getLastOrderId()) { try { $order = $this->orderRepository->get((int)$this->checkoutSession->getLastOrderId()); $order->addCommentToStatusHistory( @@ -48,6 +49,7 @@ public function execute(Quote $quote, \Throwable $e, Payment $payment): int return (int)$order->getEntityId(); } catch (NoSuchEntityException $e) { + throw $e; } } diff --git a/Model/PaymentStateInterface.php b/Model/PaymentStateInterface.php index 7b1ca4c..ee81a21 100644 --- a/Model/PaymentStateInterface.php +++ b/Model/PaymentStateInterface.php @@ -4,8 +4,8 @@ interface PaymentStateInterface { - const AUTH_APPROVED = 'AUTH_APPROVED'; - const PARTIALLY_CAPTURED = 'PARTIALLY_CAPTURED'; - const CAPTURED = 'CAPTURED'; - const VOIDED = 'VOIDED'; + public const AUTH_APPROVED = 'AUTH_APPROVED'; + public const PARTIALLY_CAPTURED = 'PARTIALLY_CAPTURED'; + public const CAPTURED = 'CAPTURED'; + public const VOIDED = 'VOIDED'; } diff --git a/Model/ResourceModel/Token.php b/Model/ResourceModel/Token.php index a7353b6..9f98ff0 100644 --- a/Model/ResourceModel/Token.php +++ b/Model/ResourceModel/Token.php @@ -36,6 +36,7 @@ public function insertNewToken(int $orderId, string $token, ?string $expiryDate) TokenInterface::ORDER_ID_FIELD => $orderId, TokenInterface::TOKEN_FIELD => $token, TokenInterface::EXPIRATION_DATE_FIELD => $expiryDate, - ]); + ] + ); } } diff --git a/Model/Shipment/Express/CreateShippingOption.php b/Model/Shipment/Express/CreateShippingOption.php index 14e43de..a0827c5 100644 --- a/Model/Shipment/Express/CreateShippingOption.php +++ b/Model/Shipment/Express/CreateShippingOption.php @@ -62,7 +62,7 @@ private function createShippingOptionByMethod( : $totals->getBaseShippingAmount()); return [ - 'id' => $shippingMethod->getCarrierCode() . "_" . $shippingMethod->getMethodCode(), + 'id' => implode('_', [$shippingMethod->getCarrierCode(), $shippingMethod->getMethodCode()]), 'name' => $shippingMethod->getCarrierTitle(), 'description' => $shippingMethod->getCarrierTitle(), 'shippingAmount' => [ diff --git a/Model/SourceValidatorService.php b/Model/SourceValidatorService.php index 1166eee..211991b 100644 --- a/Model/SourceValidatorService.php +++ b/Model/SourceValidatorService.php @@ -8,13 +8,13 @@ class SourceValidatorService implements \Afterpay\Afterpay\Model\Spi\SourceValid private \Magento\InventoryConfigurationApi\Api\GetStockItemConfigurationInterface $getStockItemConfiguration; private \Magento\InventorySourceDeductionApi\Model\GetSourceItemBySourceCodeAndSku $getSourceItemBySourceCodeAndSku; - /** - * We avoid strict types in constructor for create instances dynamically look at - * \Afterpay\Afterpay\Model\StockItemsValidator\StockItemsValidatorProxy - * @param \Magento\InventorySourceDeductionApi\Model\GetSourceItemBySourceCodeAndSku $getSourceItemBySourceCodeAndSku - * @param \Magento\InventoryConfigurationApi\Api\GetStockItemConfigurationInterface $getStockItemConfiguration - * @param \Magento\InventorySalesApi\Api\GetStockBySalesChannelInterface $getStockBySalesChannel - */ +/** + * We avoid strict types in constructor for create instances dynamically look at + * \Afterpay\Afterpay\Model\StockItemsValidator\StockItemsValidatorProxy + * @param \Magento\InventorySourceDeductionApi\Model\GetSourceItemBySourceCodeAndSku $getSourceItemBySourceCodeAndSku + * @param \Magento\InventoryConfigurationApi\Api\GetStockItemConfigurationInterface $getStockItemConfiguration + * @param \Magento\InventorySalesApi\Api\GetStockBySalesChannelInterface $getStockBySalesChannel + */ public function __construct( $getSourceItemBySourceCodeAndSku, $getStockItemConfiguration, @@ -31,7 +31,7 @@ public function __construct( * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\InventoryConfigurationApi\Exception\SkuIsNotAssignedToStockException */ - public function execute(\Magento\InventorySourceDeductionApi\Model\SourceDeductionRequestInterface $sourceDeductionRequest): void + public function execute(\Magento\InventorySourceDeductionApi\Model\SourceDeductionRequestInterface $sourceDeductionRequest): void // @codingStandardsIgnoreLine { $sourceCode = $sourceDeductionRequest->getSourceCode(); $salesChannel = $sourceDeductionRequest->getSalesChannel(); diff --git a/Model/Spi/SourceValidatorServiceInterface.php b/Model/Spi/SourceValidatorServiceInterface.php index 082b687..d11615c 100644 --- a/Model/Spi/SourceValidatorServiceInterface.php +++ b/Model/Spi/SourceValidatorServiceInterface.php @@ -14,5 +14,5 @@ interface SourceValidatorServiceInterface * @param SourceDeductionRequestInterface $sourceDeductionRequest * @return void */ - public function execute(\Magento\InventorySourceDeductionApi\Model\SourceDeductionRequestInterface $sourceDeductionRequest): void; + public function execute(\Magento\InventorySourceDeductionApi\Model\SourceDeductionRequestInterface $sourceDeductionRequest): void; // @codingStandardsIgnoreLine } diff --git a/Model/StockItemsValidator/StockItemsValidatorProxy.php b/Model/StockItemsValidator/StockItemsValidatorProxy.php index 84b6eef..a454f03 100644 --- a/Model/StockItemsValidator/StockItemsValidatorProxy.php +++ b/Model/StockItemsValidator/StockItemsValidatorProxy.php @@ -4,7 +4,7 @@ use Magento\Framework\App\ObjectManager; -class StockItemsValidatorProxy implements \Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface, \Magento\Framework\ObjectManager\NoninterceptableInterface +class StockItemsValidatorProxy implements \Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface, \Magento\Framework\ObjectManager\NoninterceptableInterface // @codingStandardsIgnoreLine { private ?\Afterpay\Afterpay\Model\Spi\StockItemsValidatorInterface $subject = null; private \Afterpay\Afterpay\Gateway\Validator\StockItemsValidatorFactory $stockItemValidatorFactory; @@ -46,15 +46,15 @@ private function getStockItemValidator(): \Afterpay\Afterpay\Model\Spi\StockItem if ($this->subject == null) { $objectManager = ObjectManager::getInstance(); $sourceValidatorService = $this->sourceValidatorServiceFactory->create([ - 'getSourceItemBySourceCodeAndSku' => $objectManager->create('\\Magento\\InventorySourceDeductionApi\\Model\\GetSourceItemBySourceCodeAndSku'), - 'getStockItemConfiguration' => $objectManager->create('\\Magento\\InventoryConfigurationApi\\Api\\GetStockItemConfigurationInterface'), + 'getSourceItemBySourceCodeAndSku' => $objectManager->create('\\Magento\\InventorySourceDeductionApi\\Model\\GetSourceItemBySourceCodeAndSku'), // @codingStandardsIgnoreLine + 'getStockItemConfiguration' => $objectManager->create('\\Magento\\InventoryConfigurationApi\\Api\\GetStockItemConfigurationInterface'), // @codingStandardsIgnoreLine 'getStockBySalesChannel' => $objectManager->create('\\Magento\\InventorySalesApi\\Api\\GetStockBySalesChannelInterface'), ]); $this->subject = $this->stockItemValidatorFactory->create([ - 'isSingleSourceMode' => $objectManager->create('\\Magento\\InventoryCatalogApi\\Model\\IsSingleSourceModeInterface'), - 'defaultSourceProvider' => $objectManager->create('\\Magento\\InventoryCatalogApi\\Api\\DefaultSourceProviderInterface'), - 'getItemsToDeductFromShipment' => $objectManager->create('\\Magento\\InventoryShipping\\Model\\GetItemsToDeductFromShipment'), - 'sourceDeductionRequestFromShipmentFactory' => $objectManager->create('\\Magento\\InventoryShipping\\Model\\SourceDeductionRequestFromShipmentFactory'), + 'isSingleSourceMode' => $objectManager->create('\\Magento\\InventoryCatalogApi\\Model\\IsSingleSourceModeInterface'), // @codingStandardsIgnoreLine + 'defaultSourceProvider' => $objectManager->create('\\Magento\\InventoryCatalogApi\\Api\\DefaultSourceProviderInterface'), // @codingStandardsIgnoreLine + 'getItemsToDeductFromShipment' => $objectManager->create('\\Magento\\InventoryShipping\\Model\\GetItemsToDeductFromShipment'), // @codingStandardsIgnoreLine + 'sourceDeductionRequestFromShipmentFactory' => $objectManager->create('\\Magento\\InventoryShipping\\Model\\SourceDeductionRequestFromShipmentFactory'), // @codingStandardsIgnoreLine 'sourceValidatorService' => $sourceValidatorService, ]); } diff --git a/Model/Url/UrlBuilder.php b/Model/Url/UrlBuilder.php index 05e054a..1e61132 100644 --- a/Model/Url/UrlBuilder.php +++ b/Model/Url/UrlBuilder.php @@ -4,8 +4,8 @@ class UrlBuilder { - const TYPE_API = 'api_url'; - const TYPE_JS_LIB = 'js_lib_url'; + public const TYPE_API = 'api_url'; + public const TYPE_JS_LIB = 'js_lib_url'; private UrlBuilder\UrlFactory $urlFactory; diff --git a/Observer/Adminhtml/ConfigSaveAfter.php b/Observer/Adminhtml/ConfigSaveAfter.php index 8c3a103..26e951c 100644 --- a/Observer/Adminhtml/ConfigSaveAfter.php +++ b/Observer/Adminhtml/ConfigSaveAfter.php @@ -7,12 +7,12 @@ class ConfigSaveAfter implements \Magento\Framework\Event\ObserverInterface private \Magento\Payment\Gateway\CommandInterface $merchantConfigurationCommand; private \Magento\Framework\Message\ManagerInterface $messageManager; - const AFTERPAY_CONFIGS = [ + public const AFTERPAY_CONFIGS = [ \Afterpay\Afterpay\Model\Config::XML_PATH_API_MODE, \Afterpay\Afterpay\Model\Config::XML_PATH_MERCHANT_KEY, \Afterpay\Afterpay\Model\Config::XML_PATH_MERCHANT_ID ]; - const CONFIGS_PATHS_TO_TRACK = [ + 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 diff --git a/Observer/AuthCaptureAfterCreditMemo.php b/Observer/AuthCaptureAfterCreditMemo.php index 55cbd40..6dd02f1 100644 --- a/Observer/AuthCaptureAfterCreditMemo.php +++ b/Observer/AuthCaptureAfterCreditMemo.php @@ -39,7 +39,8 @@ public function execute(\Magento\Framework\Event\Observer $observer): void $additionalInfo = $paymentInfo->getAdditionalInformation(); $paymentState = $additionalInfo[AdditionalInformationInterface::AFTERPAY_PAYMENT_STATE] ?? ''; - if ($paymentState !== PaymentStateInterface::AUTH_APPROVED && $paymentState !== PaymentStateInterface::PARTIALLY_CAPTURED) { + if ($paymentState !== PaymentStateInterface::AUTH_APPROVED && + $paymentState !== PaymentStateInterface::PARTIALLY_CAPTURED) { return; } diff --git a/Plugin/Checkout/Model/TotalsInformationManagement/AddLastSelectedShippingRate.php b/Plugin/Checkout/Model/TotalsInformationManagement/AddLastSelectedShippingRate.php index f70d367..44a9bea 100644 --- a/Plugin/Checkout/Model/TotalsInformationManagement/AddLastSelectedShippingRate.php +++ b/Plugin/Checkout/Model/TotalsInformationManagement/AddLastSelectedShippingRate.php @@ -2,42 +2,63 @@ namespace Afterpay\Afterpay\Plugin\Checkout\Model\TotalsInformationManagement; +use Afterpay\Afterpay\Api\Data\Quote\ExtendedShippingInformationInterface; +use Afterpay\Afterpay\Model\Config; use Magento\Checkout\Api\Data\TotalsInformationInterface; +use Magento\Checkout\Api\TotalsInformationManagementInterface; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\TotalsInterface; +use Magento\Quote\Model\Quote; class AddLastSelectedShippingRate { - private \Magento\Quote\Api\CartRepositoryInterface $cartRepository; - private \Afterpay\Afterpay\Api\Data\Quote\ExtendedShippingInformationInterface $extendedShippingInformation; + private CartRepositoryInterface $cartRepository; + private ExtendedShippingInformationInterface $extendedShippingInformation; + private Config $config; public function __construct( - \Magento\Quote\Api\CartRepositoryInterface $cartRepository, - \Afterpay\Afterpay\Api\Data\Quote\ExtendedShippingInformationInterface $extendedShippingInformation + CartRepositoryInterface $cartRepository, + ExtendedShippingInformationInterface $extendedShippingInformation, + Config $config ) { $this->cartRepository = $cartRepository; $this->extendedShippingInformation = $extendedShippingInformation; + $this->config = $config; } - public function beforeCalculate( - \Magento\Checkout\Api\TotalsInformationManagementInterface $subject, - $cartId, - \Magento\Checkout\Api\Data\TotalsInformationInterface $addressInformation + public function afterCalculate( + TotalsInformationManagementInterface $subject, + TotalsInterface $result, + $cartId, + TotalsInformationInterface $addressInformation ) { - /** @var \Magento\Quote\Model\Quote $quote */ + if (!$this->config->getAddLastSelectedShipRate() + || (!$this->config->getIsEnableExpressCheckoutMiniCart() + && !$this->config->getIsEnableExpressCheckoutProductPage() + && !$this->config->getIsEnableExpressCheckoutCartPage())) { + return $result; + } + + /** @var Quote $quote */ $quote = $this->cartRepository->get($cartId); $shippingRate = ''; - - if ($addressInformation->getShippingMethodCode() && $addressInformation->getShippingCarrierCode()) { - $shippingRate = $addressInformation->getShippingMethodCode() . '_' . $addressInformation->getShippingCarrierCode(); + if ($quote->getShippingAddress()->getShippingMethod()) { + $shippingRate = $quote->getShippingAddress()->getShippingMethod(); + } elseif ($addressInformation->getShippingCarrierCode() && $addressInformation->getShippingMethodCode()) { + $shippingRate = implode( + '_', + [$addressInformation->getShippingCarrierCode(), $addressInformation->getShippingMethodCode()] + ); } if ($shippingRate) { $this->extendedShippingInformation->update( $quote, - \Afterpay\Afterpay\Api\Data\Quote\ExtendedShippingInformationInterface::LAST_SELECTED_SHIPPING_RATE, + ExtendedShippingInformationInterface::LAST_SELECTED_SHIPPING_RATE, $shippingRate ); } - return [$cartId, $addressInformation]; + return $result; } } diff --git a/Plugin/Sales/Model/Service/CreditmemoService/AdjustmentAmountValidation.php b/Plugin/Sales/Model/Service/CreditmemoService/AdjustmentAmountValidation.php index 55771c2..6e3b4dc 100644 --- a/Plugin/Sales/Model/Service/CreditmemoService/AdjustmentAmountValidation.php +++ b/Plugin/Sales/Model/Service/CreditmemoService/AdjustmentAmountValidation.php @@ -7,7 +7,7 @@ class AdjustmentAmountValidation public function beforeRefund( \Magento\Sales\Api\CreditmemoManagementInterface $subject, \Magento\Sales\Api\Data\CreditmemoInterface $creditmemo, - $offlineRequested + $offlineRequested = false ) { $order = $creditmemo->getOrder(); if (($creditmemo->getBaseAdjustmentPositive() != 0 || $creditmemo->getBaseAdjustmentNegative() != 0) diff --git a/Setup/Patch/Data/MigrateTokens.php b/Setup/Patch/Data/MigrateTokens.php index 37c06a7..b830ae5 100644 --- a/Setup/Patch/Data/MigrateTokens.php +++ b/Setup/Patch/Data/MigrateTokens.php @@ -51,16 +51,18 @@ public function apply(): self foreach ($payments as $payment) { if (!empty($payment[OrderPaymentInterface::ADDITIONAL_INFORMATION])) { $additionalInfo = $this->serializer->unserialize($payment[OrderPaymentInterface::ADDITIONAL_INFORMATION]); - $token = $additionalInfo[CheckoutInterface::AFTERPAY_TOKEN]; - $expiration = $additionalInfo[AdditionalInformationInterface::AFTERPAY_AUTH_EXPIRY_DATE] ?? null; - if ($expiration) { - $expiration = $this->dateTime->formatDate($expiration); + $token = $additionalInfo[CheckoutInterface::AFTERPAY_TOKEN] ?? null; + if ($token) { + $expiration = $additionalInfo[AdditionalInformationInterface::AFTERPAY_AUTH_EXPIRY_DATE] ?? null; + if ($expiration) { + $expiration = $this->dateTime->formatDate($expiration); + } + $tokenEntries[] = [ + TokenInterface::ORDER_ID_FIELD => $payment['parent_id'], + TokenInterface::TOKEN_FIELD => $token, + TokenInterface::EXPIRATION_DATE_FIELD => $expiration + ]; } - $tokenEntries[] = [ - TokenInterface::ORDER_ID_FIELD => $payment['parent_id'], - TokenInterface::TOKEN_FIELD => $token, - TokenInterface::EXPIRATION_DATE_FIELD => $expiration - ]; } } diff --git a/Test/ApiFunctional/GraphQl/CreateAfterpayCheckoutTest.php b/Test/ApiFunctional/GraphQl/CreateAfterpayCheckoutTest.php index 7426998..992ee96 100644 --- a/Test/ApiFunctional/GraphQl/CreateAfterpayCheckoutTest.php +++ b/Test/ApiFunctional/GraphQl/CreateAfterpayCheckoutTest.php @@ -1,6 +1,6 @@ getMaskedQuoteIdByReservedOrderId->execute('test_order_item_with_items'); + $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute('guest_quote'); $mutation = $this->createAfterpayCheckoutMutation($maskedQuoteId); $response = $this->graphQlMutation($mutation); diff --git a/Test/Unit/Model/Payment/AmountProcessor/CreditMemoTest.php b/Test/Unit/Model/Payment/AmountProcessor/CreditMemoTest.php index 31bb2c4..277b9dd 100644 --- a/Test/Unit/Model/Payment/AmountProcessor/CreditMemoTest.php +++ b/Test/Unit/Model/Payment/AmountProcessor/CreditMemoTest.php @@ -87,6 +87,12 @@ private function prepareOrderObject(): void ->getMock(); $shipmentCollection->expects($this->atLeastOnce())->method('count')->willReturn(0); + $store = $this->createMock(\Magento\Store\Model\Store::class); + $store->expects($this->any())->method("getWebsiteId")->willReturn(1); + + $this->order->expects($this->any())->method("getStore") + ->with() + ->willReturn($store); $this->order->expects($this->any())->method("getPayment") ->with() ->willReturn($this->payment); diff --git a/Test/Unit/Model/Shipment/Express/CreateShippingOptionTest.php b/Test/Unit/Model/Shipment/Express/CreateShippingOptionTest.php index 3ac3acc..c217d28 100644 --- a/Test/Unit/Model/Shipment/Express/CreateShippingOptionTest.php +++ b/Test/Unit/Model/Shipment/Express/CreateShippingOptionTest.php @@ -25,6 +25,10 @@ class CreateShippingOptionTest extends \PHPUnit\Framework\TestCase * @var \Magento\Quote\Model\Quote|\PHPUnit\Framework\MockObject\MockObject */ private $quote; + /** + * @var \Afterpay\Afterpay\Model\CBT\CheckCBTCurrencyAvailabilityInterface + */ + private $checkCBTCurrencyAvailability; protected function setUp(): void { @@ -42,7 +46,16 @@ protected function setUp(): void $this->totalsInformation->method("setShippingCarrierCode")->willReturnSelf(); $this->totalsInformation->method("setShippingMethodCode")->willReturnSelf(); $this->totalsInformationFactory->method("create")->willReturn($this->totalsInformation); - $this->quote = $this->createMock(\Magento\Quote\Model\Quote::class); + $this->checkCBTCurrencyAvailability = $this->createMock( + \Afterpay\Afterpay\Model\CBT\CheckCBTCurrencyAvailabilityInterface::class + ); + $this->checkCBTCurrencyAvailability->method("checkByQuote")->willReturn(false); + $this->quote = $this->getMockBuilder(\Magento\Quote\Model\Quote::class) + ->disableOriginalConstructor() + ->disableOriginalClone() + ->disableArgumentCloning() + ->setMethods(['getGrandTotal', 'getBaseGrandTotal', 'getShippingAddress']) + ->getMock(); $this->quote->method("getShippingAddress") ->willReturn( $this->createMock(\Magento\Quote\Api\Data\AddressInterface::class) @@ -50,7 +63,8 @@ protected function setUp(): void $this->createShippingOption = new \Afterpay\Afterpay\Model\Shipment\Express\CreateShippingOption( $this->config, $this->totalsInformationManagement, - $this->totalsInformationFactory + $this->totalsInformationFactory, + $this->checkCBTCurrencyAvailability ); } @@ -76,6 +90,8 @@ public function testOrderLimit( $this->totalsInformationManagement->expects($this->once()) ->method("calculate") ->willReturn($calculatedTotals); + $this->quote->method("getGrandTotal")->willReturn($calculatedTotals->getGrandTotal()); + $this->quote->method("getBaseGrandTotal")->willReturn($calculatedTotals->getBaseGrandTotal()); $this->assertEquals($result, $this->createShippingOption->create($this->quote, $shippingMethod)); } @@ -84,6 +100,7 @@ public function orderLimitDataProvider() $carrierCode = 'carrierCode'; $carrierMethod = 'carrierMethod'; $carrierTitle = 'carrierTitle'; + $grandTotal = 10000; $baseGrandTotal = 10000; $baseShippingAmount = 20; $baseTaxAmount = 10; @@ -91,35 +108,35 @@ public function orderLimitDataProvider() [ "0", "1000", - $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, $baseTaxAmount), + $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, $baseTaxAmount), $this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle), null, ], [ "10000", "1000", - $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, $baseTaxAmount), + $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, $baseTaxAmount), $this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle), null, ], [ null, "1000", - $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, $baseTaxAmount), + $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, $baseTaxAmount), $this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle), null, ], [ "0", null, - $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, $baseTaxAmount), + $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, $baseTaxAmount), $this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle), null, ], [ null, null, - $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, $baseTaxAmount), + $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, $baseTaxAmount), $this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle), null, ] @@ -131,6 +148,7 @@ public function resultNullAmountTestDataProvider() $carrierCode = 'carrierCode'; $carrierMethod = 'carrierMethod'; $carrierTitle = 'carrierTitle'; + $grandTotal = 10000; $baseGrandTotal = 10000; $baseShippingAmount = 20; $baseTaxAmount = 10; @@ -138,14 +156,14 @@ public function resultNullAmountTestDataProvider() [ "0", "100000", - $this->createCalculatedTotals(null, $baseShippingAmount, $baseTaxAmount), + $this->createCalculatedTotals(null,null, $baseShippingAmount, $baseTaxAmount), $this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle), null ], [ "0", "100000", - $this->createCalculatedTotals($baseGrandTotal, null, $baseTaxAmount), + $this->createCalculatedTotals($grandTotal, $baseGrandTotal, null, $baseTaxAmount), $this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle), [ 'id' => $carrierCode . "_" . $carrierMethod, @@ -168,7 +186,7 @@ public function resultNullAmountTestDataProvider() [ "0", "100000", - $this->createCalculatedTotals($baseGrandTotal, $baseShippingAmount, null), + $this->createCalculatedTotals($grandTotal, $baseGrandTotal, $baseShippingAmount, null), $this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle), [ 'id' => $carrierCode . "_" . $carrierMethod, @@ -191,7 +209,7 @@ public function resultNullAmountTestDataProvider() [ "0", "100000", - $this->createCalculatedTotals($baseGrandTotal, null, null), + $this->createCalculatedTotals($grandTotal, $baseGrandTotal, null, null), $this->createShippingMethod($carrierCode, $carrierMethod, $carrierTitle), [ 'id' => $carrierCode . "_" . $carrierMethod, @@ -220,7 +238,7 @@ public function resultTestDataProvider() [ "123", "1234", - $this->createCalculatedTotals(1233.11, 12.13, 11.15), + $this->createCalculatedTotals(1233.11,1233.11, 12.13, 11.15), $this->createShippingMethod("carrierCode1", "carrierMethod1", "carrierTitle1"), [ 'id' => "carrierCode1" . "_" . "carrierMethod1", @@ -243,7 +261,7 @@ public function resultTestDataProvider() [ "22222", "55555", - $this->createCalculatedTotals(33333.33, 324.13, 534.234), + $this->createCalculatedTotals(33333.33, 33333.33,324.13, 534.234), $this->createShippingMethod("carrierCode2", "carrierMethod2", "carrierTitle2"), [ 'id' => "carrierCode2" . "_" . "carrierMethod2", @@ -267,11 +285,13 @@ public function resultTestDataProvider() } private function createCalculatedTotals( + ?float $grandTotal = 0, ?float $baseGrandTotal = 0, ?float $baseShippingAmount = 0, ?float $baseTaxAmount = 0 ) { $calculatedTotals = $this->createMock(\Magento\Quote\Api\Data\TotalsInterface::class); + $calculatedTotals->expects($this->any())->method("getGrandTotal")->willReturn($grandTotal); $calculatedTotals->expects($this->any())->method("getBaseGrandTotal")->willReturn($baseGrandTotal); $calculatedTotals->expects($this->any())->method("getBaseTaxAmount")->willReturn($baseTaxAmount); $calculatedTotals->expects($this->any())->method("getBaseShippingAmount")->willReturn($baseShippingAmount); diff --git a/Test/Unit/Service/Payment/Auth/ExpiryDateTest.php b/Test/Unit/Service/Payment/Auth/ExpiryDateTest.php index 6cf0667..215b59f 100644 --- a/Test/Unit/Service/Payment/Auth/ExpiryDateTest.php +++ b/Test/Unit/Service/Payment/Auth/ExpiryDateTest.php @@ -22,7 +22,7 @@ protected function setUp(): void /** * @dataProvider datesProvider */ - public function testIsExpired(string $expireDate, ?string $dateToCheck = null, bool $result) + public function testIsExpired(string $expireDate, ?string $dateToCheck, bool $result) { if (!$dateToCheck) { $this->timezone->expects($this->once())->method("date")->willReturn(new \DateTime()); diff --git a/ViewModel/Container/Cta/Lib.php b/ViewModel/Container/Cta/Lib.php index 238bc6e..8b4d03f 100644 --- a/ViewModel/Container/Cta/Lib.php +++ b/ViewModel/Container/Cta/Lib.php @@ -27,7 +27,7 @@ public function getMinTotalValue(): ?string $currencyCode = $this->storeManager->getStore()->getCurrentCurrencyCode(); $cbtLimits = $this->config->getCbtCurrencyLimits(); if (isset($cbtLimits[$currencyCode])) { - return $cbtLimits[$currencyCode]['minimumAmount']['amount']; + return $cbtLimits[$currencyCode]['minimumAmount']['amount'] ?? '0'; } return $this->config->getMinOrderTotal(); diff --git a/ViewModel/Container/ExpressCheckout/ExpressCheckout.php b/ViewModel/Container/ExpressCheckout/ExpressCheckout.php index 7ee6a15..f91dd35 100644 --- a/ViewModel/Container/ExpressCheckout/ExpressCheckout.php +++ b/ViewModel/Container/ExpressCheckout/ExpressCheckout.php @@ -4,7 +4,7 @@ class ExpressCheckout extends \Afterpay\Afterpay\ViewModel\Container\Container { - const COUNTRY_CURRENCY_MAP = [ + public const COUNTRY_CURRENCY_MAP = [ 'AUD' => 'AU', 'NZD' => 'NZ', 'USD' => 'US', @@ -12,15 +12,6 @@ class ExpressCheckout extends \Afterpay\Afterpay\ViewModel\Container\Container 'GBP' => 'GB' ]; - public function __construct( - \Magento\Framework\Serialize\SerializerInterface $serializer, - \Afterpay\Afterpay\Model\Config $config, - \Afterpay\Afterpay\Model\ResourceModel\NotAllowedProductsProvider $notAllowedProductsProvider, - \Magento\Store\Model\StoreManagerInterface $storeManager - ) { - parent::__construct($serializer, $config, $notAllowedProductsProvider, $storeManager); - } - public function updateJsLayout( string $jsLayoutJson, bool $remove = false, diff --git a/composer.json b/composer.json index 449c904..90d4f1c 100644 --- a/composer.json +++ b/composer.json @@ -3,7 +3,7 @@ "license": "Apache-2.0", "type": "magento2-module", "description": "Magento 2 Afterpay Payment Module", - "version": "5.2.2", + "version": "5.3.0", "require": { "php": ">=7.4.0", "magento/framework": "^103.0", diff --git a/etc/config.xml b/etc/config.xml index 7ad7f3b..646671c 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -23,6 +23,7 @@ AU,NZ,US,CA + 1 diff --git a/etc/module.xml b/etc/module.xml index d8a5239..72e4ea0 100644 --- a/etc/module.xml +++ b/etc/module.xml @@ -1,7 +1,7 @@ - + diff --git a/view/frontend/web/js/view/container/express-checkout/button.js b/view/frontend/web/js/view/container/express-checkout/button.js index 0ed6127..bd80613 100644 --- a/view/frontend/web/js/view/container/express-checkout/button.js +++ b/view/frontend/web/js/view/container/express-checkout/button.js @@ -38,6 +38,7 @@ define([ if (errorMessage) { this._handleError(errorMessage); } + return res; }, initAfterpay: function () { diff --git a/view/frontend/web/js/view/payment/info/checkout-note.js b/view/frontend/web/js/view/payment/info/checkout-note.js index 620e309..145f52c 100644 --- a/view/frontend/web/js/view/payment/info/checkout-note.js +++ b/view/frontend/web/js/view/payment/info/checkout-note.js @@ -18,23 +18,24 @@ define([ return Component.extend({ initWidget: function () { - if (!this._showWidget()) { - return; - } + let widgetAmount = this._getWidgetAmount(totals.totals()); + + window.afterpayWidget = new Square.Marketplace.SquarePlacement(); + afterpayWidget.mpid = window.checkoutConfig.payment.afterpay.mpid; + afterpayWidget.pageType = 'checkout'; + afterpayWidget.amount = widgetAmount.amount; + afterpayWidget.currency = widgetAmount.currency; + afterpayWidget.type = 'payment-schedule'; + afterpayWidget.platform = 'Magento'; + + document.getElementById('afterpay-widget-container').appendChild(afterpayWidget); - window.afterpayWidget = new AfterPay.Widgets.PaymentSchedule({ - target: '#afterpay-widget-container', - locale: window.checkoutConfig.payment.afterpay.locale.replace('_', '-'), - amount: this._getWidgetAmount(totals.totals()), - onError: (event) => console.log(event.data.error) - }) totals.totals.subscribe((totals) => { if (afterpayWidget) { - afterpayWidget.update({ - amount: this._getWidgetAmount(totals), - }) + afterpayWidget.setAttribute('data-amount', this._getWidgetAmount(totals).amount); } }); + if (checkoutData.getSelectedPaymentMethod() == 'afterpay' && checkoutConfig.payment.afterpay.isCBTCurrency === true) { this._hideBaseCurrencyChargeInfo(); @@ -66,14 +67,5 @@ define([ _showBaseCurrencyChargeInfo: function () { $('.opc-block-summary .totals.charge').show(); }, - _showWidget: function () { - if (checkoutConfig.payment.afterpay.consumerLendingEnabled) { - if (totals.totals().base_grand_total >= window.checkoutConfig.payment.afterpay.consumerLendingMinimumAmount) { - return false - } - } - - return true; - }, }); }); diff --git a/view/frontend/web/js/view/payment/method-renderer/afterpay.js b/view/frontend/web/js/view/payment/method-renderer/afterpay.js index 151fa6e..f4c9ea9 100644 --- a/view/frontend/web/js/view/payment/method-renderer/afterpay.js +++ b/view/frontend/web/js/view/payment/method-renderer/afterpay.js @@ -6,7 +6,8 @@ define([ 'Magento_Checkout/js/action/set-payment-information', 'Magento_Checkout/js/model/error-processor', 'Magento_Customer/js/customer-data', - 'Magento_Customer/js/section-config' + 'Magento_Customer/js/section-config', + 'Magento_Checkout/js/model/quote' ], function ( $, Component, @@ -15,7 +16,8 @@ define([ setPaymentInformationAction, errorProcessor, customerData, - sectionConfig + sectionConfig, + quote ) { 'use strict'; @@ -23,7 +25,17 @@ define([ defaults: { template: 'Afterpay_Afterpay/payment/afterpay' }, + getCurrency: function () { + let currency = window.checkoutConfig.payment.afterpay.isCBTCurrency + ? quote.totals().quote_currency_code + : quote.totals().base_currency_code; + return currency; + + }, + getMPID: function () { + return window.checkoutConfig.payment.afterpay.mpid; + }, continueToAfterpay: function (data, event) { const self = this; @@ -44,9 +56,14 @@ define([ confirmPath: captureUrlPath, cancelPath: captureUrlPath }).done(function (response) { + const sections = sectionConfig.getAffectedSections(captureUrlPath); customerData.invalidate(sections); - $.mage.redirect(response.afterpay_redirect_checkout_url); + + let checkoutRedirectUrl=self._getCheckoutUrl(response.afterpay_redirect_checkout_url); + + $.mage.redirect(checkoutRedirectUrl); + }).always(function () { self.isPlaceOrderActionAllowed(true); }); @@ -57,6 +74,34 @@ define([ self.isPlaceOrderActionAllowed(true); }); } - } + }, + _getCheckoutUrl: function (checkoutUrl) { + + let deviceData=$.mage.cookies.get("apt_pixel"); + let args=""; + // Append params from the cookie + if (deviceData !== undefined && deviceData !=null && deviceData.length>0) { + + let queryParams=checkoutUrl.split("?")[1]; + const searchParams = new URLSearchParams(queryParams); + + let device=JSON.parse(atob(deviceData)); + if (device.hasOwnProperty('deviceId') && + (/^[0-9a-z-]*$/i).test(device.deviceId) && + searchParams.has('device_id')===false) { + args="&device_id="+device.deviceId; + } + + if (device.hasOwnProperty('checkout') ) { + for (var prop in device.checkout){ + let val=device.checkout[prop]; + if ((/^[0-9a-z]+$/i).test(prop) && (/^[0-9a-z-]*$/i).test(val) && searchParams.has(prop)===false) { + args+="&"+prop+"="+val; + } + } + } + } + return checkoutUrl+args; + }, }); }); diff --git a/view/frontend/web/template/payment/afterpay.html b/view/frontend/web/template/payment/afterpay.html index d762cbf..15268dd 100644 --- a/view/frontend/web/template/payment/afterpay.html +++ b/view/frontend/web/template/payment/afterpay.html @@ -3,10 +3,18 @@ -