Skip to content

Commit

Permalink
Release version 4.1.0
Browse files Browse the repository at this point in the history
  • Loading branch information
afterpayplugins committed Jun 26, 2023
1 parent 658009e commit cb8cd50
Show file tree
Hide file tree
Showing 26 changed files with 573 additions and 133 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,47 @@

namespace Afterpay\Afterpay\Block\Adminhtml\System\Config\Form\Field;

use Magento\Backend\Block\Template\Context;
use Magento\Framework\Serialize\SerializerInterface;
use Psr\Log\LoggerInterface;

class CBTAvailableCurrencies extends \Magento\Config\Block\System\Config\Form\Field
{
private $serializer;
private $logger;

public function __construct(
LoggerInterface $logger,
SerializerInterface $serializer,
Context $context,
array $data = []
) {
$this->serializer = $serializer;
$this->logger = $logger;
parent::__construct($context, $data);
}

protected function _renderValue(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
try {
$CbtAvailableCurrencies = $this->serializer->unserialize($element->getValue());
$newValue = '';
if (!$CbtAvailableCurrencies) {
return parent::_renderValue($element);
}

foreach ($CbtAvailableCurrencies as $currencyCode => $currency) {
$newValue .= $currencyCode . '(min:' . $currency['minimumAmount']['amount']
. ',max:' . $currency['maximumAmount']['amount'] . ') ';
}
$element->setValue($newValue);
} catch (\Exception $e) {
$this->logger->critical($e);
}

return parent::_renderValue($element);
}

public function render(\Magento\Framework\Data\Form\Element\AbstractElement $element)
{
/** @phpstan-ignore-next-line */
Expand Down
52 changes: 33 additions & 19 deletions Controller/Express/PlaceOrder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,20 @@

namespace Afterpay\Afterpay\Controller\Express;

class PlaceOrder implements \Magento\Framework\App\Action\HttpPostActionInterface
{
const CANCELLED_STATUS = 'CANCELLED';
use Afterpay\Afterpay\Controller\Payment\Capture;
use Afterpay\Afterpay\Gateway\Config\Config;
use Afterpay\Afterpay\Model\Payment\Capture\PlaceOrderProcessor;
use Magento\Checkout\Model\Session;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\UrlInterface;
use Magento\Payment\Gateway\CommandInterface;

class PlaceOrder implements HttpPostActionInterface
{
private $request;
private $messageManager;
private $checkoutSession;
Expand All @@ -15,13 +25,13 @@ class PlaceOrder implements \Magento\Framework\App\Action\HttpPostActionInterfac
private $syncCheckoutDataCommand;

public function __construct(
\Magento\Framework\App\RequestInterface $request,
\Magento\Framework\Message\ManagerInterface $messageManager,
\Magento\Checkout\Model\Session $checkoutSession,
\Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
\Magento\Framework\UrlInterface $url,
\Afterpay\Afterpay\Model\Payment\Capture\PlaceOrderProcessor $placeOrderProcessor,
\Magento\Payment\Gateway\CommandInterface $syncCheckoutDataCommand
RequestInterface $request,
ManagerInterface $messageManager,
Session $checkoutSession,
JsonFactory $jsonFactory,
UrlInterface $url,
PlaceOrderProcessor $placeOrderProcessor,
CommandInterface $syncCheckoutDataCommand
) {
$this->request = $request;
$this->messageManager = $messageManager;
Expand All @@ -40,25 +50,29 @@ public function execute()
$afterpayOrderToken = $this->request->getParam('orderToken');
$status = $this->request->getParam('status');

if ($status === static::CANCELLED_STATUS) {
if ($status === Capture::CHECKOUT_STATUS_CANCELLED) {
return $jsonResult;
}

if ($status !== Capture::CHECKOUT_STATUS_SUCCESS) {
$errorMessage = (string)__('Afterpay payment is declined. Please select an alternative payment method.');
$this->messageManager->addErrorMessage($errorMessage);

return $jsonResult->setData(['redirectUrl' => $this->url->getUrl('checkout/cart')]);
}

try {
$quote->getPayment()
->setMethod(\Afterpay\Afterpay\Gateway\Config\Config::CODE)
->setMethod(Config::CODE)
->setAdditionalInformation('afterpay_express', true);
$this->placeOrderProcessor->execute($quote, $this->syncCheckoutDataCommand, $afterpayOrderToken);
} catch (\Throwable $e) {
$errorMessage = $e instanceof \Magento\Framework\Exception\LocalizedException
$errorMessage = $e instanceof LocalizedException
? $e->getMessage()
: (string)__('Afterpay payment declined. Please select an alternative payment method.');
: (string)__('Afterpay payment is declined. Please select an alternative payment method.');
$this->messageManager->addErrorMessage($errorMessage);

return $jsonResult->setData(['error' => $errorMessage, 'redirectUrl' => $this->url->getUrl(
'checkout/cart',
['_scope' => $quote->getStore()]
)]
);
return $jsonResult->setData(['redirectUrl' => $this->url->getUrl('checkout/cart')]);
}

return $jsonResult->setData(['redirectUrl' => $this->url->getUrl('checkout/onepage/success')]);
Expand Down
52 changes: 29 additions & 23 deletions Gateway/Request/Checkout/CheckoutDataBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,18 +101,26 @@ protected function getItems(\Magento\Quote\Model\Quote $quote): array

foreach ($quoteItems as $item) {
$productId = $item->getProduct()->getId();
$amount = $isCBTCurrencyAvailable ? $item->getPriceInclTax() : $item->getBasePriceInclTax();
$currencyCode = $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode();
$qty = $item->getQty();
$isIntQty = floor($qty) == $qty;
if ($isIntQty) {
$qty = (int)$item->getQty();
} else {
$amount *= $item->getQty();
$qty = 1;
}

$formattedItem = [
'name' => $item->getName(),
'sku' => $item->getSku(),
'quantity' => $item->getQty(),
'quantity' => $qty,
'pageUrl' => $item->getProduct()->getProductUrl(),
'categories' => [array_values($this->getQuoteItemCategoriesNames($item))],
'price' => [
'amount' => $this->formatPrice(
$isCBTCurrencyAvailable ? $item->getPriceInclTax() : $item->getBasePriceInclTax()
),
'currency' => $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode()
'amount' => $this->formatPrice($amount),
'currency' => $currencyCode
]
];

Expand All @@ -132,10 +140,7 @@ protected function getQuoteItemCategoriesNames(\Magento\Quote\Model\Quote\Item $
/** @var \Magento\Catalog\Model\ResourceModel\AbstractCollection $categoryCollection */
$categoryCollection = $item->getProduct()->getCategoryCollection();
$itemCategories = $categoryCollection->addAttributeToSelect('name')->getItems();
return array_map(
function ($cat) {return $cat->getData('name');},
$itemCategories
);
return array_map(static function ($cat) {return $cat->getData('name');}, $itemCategories);
}

/**
Expand All @@ -146,11 +151,8 @@ protected function getItemsImages(array $items): array
{
$itemsImages = [];
$searchCriteria = $this->searchCriteriaBuilder
->addFilter(
'entity_id',
array_map(function ($item) {return $item->getProduct()->getId();}, $items),
'in'
)->create();
->addFilter('entity_id', array_map(static function ($item) {return $item->getProduct()->getId();}, $items), 'in')
->create();
$products = $this->productRepository->getList($searchCriteria)->getItems();

foreach ($products as $product) {
Expand Down Expand Up @@ -184,13 +186,14 @@ protected function getShippingAmount(\Magento\Quote\Model\Quote $quote): ?array
return null;
}
$isCBTCurrencyAvailable = $this->checkCBTCurrencyAvailability->checkByQuote($quote);
$amount = $isCBTCurrencyAvailable
? $quote->getShippingAddress()->getShippingAmount()
: $quote->getShippingAddress()->getBaseShippingAmount();
$currencyCode = $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode();

return [
'amount' => $this->formatPrice($isCBTCurrencyAvailable
? $quote->getShippingAddress()->getShippingAmount()
: $quote->getShippingAddress()->getBaseShippingAmount()
),
'currency' => $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode()
'amount' => $this->formatPrice($amount),
'currency' => $currencyCode
];
}

Expand All @@ -211,13 +214,16 @@ protected function getDiscounts(\Magento\Quote\Model\Quote $quote): ?array
return null;
}
$isCBTCurrencyAvailable = $this->checkCBTCurrencyAvailability->checkByQuote($quote);
$amount = $isCBTCurrencyAvailable
? $quote->getDiscountAmount()
: $quote->getBaseDiscountAmount();
$currencyCode = $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode();

return [
'displayName' => __('Discount'),
'amount' => [
'amount' => $this->formatPrice($isCBTCurrencyAvailable
? $quote->getDiscountAmount()
: $quote->getBaseDiscountAmount()),
'currency' => $isCBTCurrencyAvailable ? $quote->getQuoteCurrencyCode() : $quote->getBaseCurrencyCode()
'amount' => $this->formatPrice($amount),
'currency' => $currencyCode
]
];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ public function handle(array $handlingSubject, array $response)
throw new \Magento\Framework\Exception\LocalizedException($invalidCartItemsExceptionMessage);
}
if ($item->getQty() != $responseItems[$itemIndex]['quantity']) {
$qty = $item->getQty();
$isIntQty = floor($qty) == $qty;
if (!$isIntQty && $responseItems[$itemIndex]['quantity'] == 1) {
$amount = $isCBTCurrency ? $item->getPriceInclTax() : $item->getBasePriceInclTax();
if ($amount * $qty == $responseItems[$itemIndex]['price']['amount']) {
continue;
}
}
throw new \Magento\Framework\Exception\LocalizedException($invalidCartItemsExceptionMessage);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,35 @@

namespace Afterpay\Afterpay\Gateway\Response\MerchantConfiguration;

class CBTAvailableCurrenciesConfigurationHandler implements \Magento\Payment\Gateway\Response\HandlerInterface
use Afterpay\Afterpay\Model\Config;
use Magento\Payment\Gateway\Response\HandlerInterface;
use Magento\Framework\Serialize\SerializerInterface;

class CBTAvailableCurrenciesConfigurationHandler implements HandlerInterface
{
private $config;
private $serializer;

public function __construct(
\Afterpay\Afterpay\Model\Config $config
Config $config,
SerializerInterface $serializer
) {
$this->config = $config;
$this->serializer = $serializer;
}

public function handle(array $handlingSubject, array $response): void
{
$websiteId = (int)$handlingSubject['websiteId'];
$cbtAvailableCurrencies = [];
$cbtAvailableCurrencies = '';

if (isset($response['CBT']['enabled']) &&
isset($response['CBT']['limits']) &&
is_array($response['CBT']['limits'])
) {
foreach ($response['CBT']['limits'] as $limit) {
if (isset($limit['maximumAmount']['currency']) && isset($limit['maximumAmount']['amount'])) {
$cbtAvailableCurrencies[] = $limit['maximumAmount']['currency'] . ':' . $limit['maximumAmount']['amount'];
}
}
$cbtAvailableCurrencies = $this->serializer->serialize($response['CBT']['limits']);
}
$this->config->setCbtCurrencyLimits(implode(",", $cbtAvailableCurrencies), $websiteId);

$this->config->setCbtCurrencyLimits($cbtAvailableCurrencies, $websiteId);
}
}
2 changes: 1 addition & 1 deletion Gateway/Validator/Method/CurrencyValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public function __construct(
public function validate(array $validationSubject): \Magento\Payment\Gateway\Validator\ResultInterface
{
$quote = $this->checkoutSession->getQuote();
$currentCurrency = $quote->getQuoteCurrencyCode();
$currentCurrency = $quote->getStore()->getCurrentCurrencyCode();
$allowedCurrencies = $this->config->getAllowedCurrencies();
$cbtCurrencies = array_keys($this->config->getCbtCurrencyLimits());

Expand Down
2 changes: 1 addition & 1 deletion Model/Checks/IsCBTAvailable.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function checkByQuote(\Magento\Quote\Model\Quote $quote): bool
return $this->canUseCurrentCurrency;
}

$currentCurrencyCode = $quote->getQuoteCurrencyCode();
$currentCurrencyCode = $quote->getQuoteCurrencyCode() ?? $quote->getStore()->getCurrentCurrencyCode();
$amount = (float) $quote->getGrandTotal();
$this->canUseCurrentCurrency = $this->check($currentCurrencyCode, $amount);

Expand Down
Loading

0 comments on commit cb8cd50

Please sign in to comment.