diff --git a/.github/workflows/coding-standard.yml b/.github/workflows/coding-standard.yml index 0ff896abf..4ae22078a 100644 --- a/.github/workflows/coding-standard.yml +++ b/.github/workflows/coding-standard.yml @@ -7,7 +7,7 @@ jobs: runs-on: ubuntu-latest continue-on-error: true steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - uses: extdn/github-actions-m2/magento-coding-standard/8.1@master with: phpcs_severity: 10 @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-latest continue-on-error: true steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - uses: extdn/github-actions-m2/magento-mess-detector@master phpstan: @@ -26,7 +26,47 @@ jobs: runs-on: ubuntu-latest continue-on-error: true steps: - - uses: actions/checkout@v2 - - uses: extdn/github-actions-m2/magento-phpstan/8.1@master + - name: Setup PHP + uses: shivammathur/setup-php@v2 with: - composer_name: buckaroo/magento2 + php-version: 8.1 + tools: composer:v2 + + - uses: actions/checkout@v3 + + - name: Validate composer json + run: composer validate + + - name: Clear Composer cache + run: composer clear-cache + + - name: Setup Magento + run: | + pull_number=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH") + url="https://api.github.com/repos/buckaroo-it/Magento2/pulls/$pull_number/files" + echo $url + curl $url > files_changed + cat files_changed | grep '"filename"' | sed 's/\"filename\"\: \"//' | sed 's/\",//' | xargs ls + echo '{"http-basic": {"repo.magento.com": {"username": "${{ secrets.REPO_USERNAME }}","password": "${{ secrets.REPO_PASS }}"}}}' > auth.json + composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition=2.4.6-p2 ~/m246 + mkdir -p ~/m246/app/code/Buckaroo/Magento2/ + rsync -r --exclude='m246' ./ ~/m246/app/code/Buckaroo/Magento2/ + cd ~/m246 + bin/magento module:enable --all + bin/magento setup:di:compile + + - name: Install PHPStan + run: | + cd ~/m246 + composer require --dev phpstan/phpstan:^1.10 + ls -la vendor/bin/ + + - name: Install Buckaroo SDK + run: | + cd ~/m246 + composer require buckaroo/sdk + + - name: Run PHPStan + run: | + cd ~/m246 + vendor/bin/phpstan analyse --level 1 app/code/Buckaroo/Magento2/ -c dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/phpstan.neon \ No newline at end of file diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 21b885cbf..178d62a9b 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -18,7 +18,7 @@ jobs: - 3306:3306 options: --tmpfs /tmp:rw --tmpfs /var/lib/mysql:rw --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 es: - image: docker.io/wardenenv/elasticsearch:7.16 + image: docker.io/wardenenv/elasticsearch:7.8 ports: - 9200:9200 env: @@ -27,10 +27,10 @@ jobs: ES_JAVA_OPTS: "-Xms64m -Xmx512m" options: --health-cmd="curl localhost:9200/_cluster/health?wait_for_status=yellow&timeout=60s" --health-interval=10s --health-timeout=5s --health-retries=3 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: M2 Integration Tests with Magento 2 (Php 8.1) uses: extdn/github-actions-m2/magento-integration-tests/8.1@master with: module_name: Buckaroo_Magento2 composer_name: buckaroo/magento2 - ce_version: '2.4.4' + ce_version: '2.4.6' diff --git a/Api/Data/BuckarooGiftcardDataInterface.php b/Api/Data/BuckarooGiftcardDataInterface.php index e5c325657..4ab878187 100644 --- a/Api/Data/BuckarooGiftcardDataInterface.php +++ b/Api/Data/BuckarooGiftcardDataInterface.php @@ -16,4 +16,4 @@ public function getGiftcardModel(): Giftcard; * @return BuckarooGiftcardDataInterface */ public function setGiftcardModel(Giftcard $giftcard): BuckarooGiftcardDataInterface; -} \ No newline at end of file +} diff --git a/Api/Data/BuckarooResponseDataInterface.php b/Api/Data/BuckarooResponseDataInterface.php index e2c99652b..b4f6d70b9 100644 --- a/Api/Data/BuckarooResponseDataInterface.php +++ b/Api/Data/BuckarooResponseDataInterface.php @@ -9,4 +9,4 @@ interface BuckarooResponseDataInterface public function getResponse(): TransactionResponse; public function setResponse(TransactionResponse $transactionResponse): BuckarooResponseDataInterface; -} \ No newline at end of file +} diff --git a/Api/PushProcessorInterface.php b/Api/PushProcessorInterface.php index 5b7b0fcdc..9cbfa6a2b 100644 --- a/Api/PushProcessorInterface.php +++ b/Api/PushProcessorInterface.php @@ -9,4 +9,4 @@ interface PushProcessorInterface * @return bool */ public function processPush(PushRequestInterface $pushRequest): bool; -} \ No newline at end of file +} diff --git a/Block/Adminhtml/Config/Support/SupportTab.php b/Block/Adminhtml/Config/Support/SupportTab.php index e5ef234ee..3ff81f382 100644 --- a/Block/Adminhtml/Config/Support/SupportTab.php +++ b/Block/Adminhtml/Config/Support/SupportTab.php @@ -57,8 +57,8 @@ class SupportTab extends Template implements RendererInterface * Override the parent constructor to require our own dependencies. * * @param Context $context - * @param ModuleResource $moduleContext * @param SoftwareData $softwareData + * @param Curl $curl * @param array $data */ public function __construct( @@ -118,8 +118,7 @@ public function phpVersionCheck() $phpMajorMinor = $phpVersion[0] . '.' . $phpVersion[1]; $phpPatch = (int)$phpVersion[2]; - if ( - !isset($this->phpVersionSupport[$magentoMajorMinor]) || + if (!isset($this->phpVersionSupport[$magentoMajorMinor]) || !isset($this->phpVersionSupport[$magentoMajorMinor][$phpMajorMinor]) ) { return 0; diff --git a/Block/Adminhtml/System/Config/Fieldset/Payment.php b/Block/Adminhtml/System/Config/Fieldset/Payment.php index 89430031b..4debcc356 100644 --- a/Block/Adminhtml/System/Config/Fieldset/Payment.php +++ b/Block/Adminhtml/System/Config/Fieldset/Payment.php @@ -1,5 +1,4 @@ _backendConfig = $backendConfig; + $this->backendConfig = $backendConfig; parent::__construct($context, $authSession, $jsHelper, $data); } /** - * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @param AbstractElement $element * @return string * @SuppressWarnings(PHPMD.NPathComplexity) */ @@ -60,8 +66,8 @@ protected function _getHeaderTitleHtml($element) $groupConfig = $element->getGroup(); - $disabledAttributeString = $this->_isPaymentEnabled($element) ? '' : ' disabled="disabled"'; - $disabledClassString = $this->_isPaymentEnabled($element) ? '' : ' disabled'; + $disabledAttributeString = $this->isPaymentEnabled($element) ? '' : ' disabled="disabled"'; + $disabledClassString = $this->isPaymentEnabled($element) ? '' : ' disabled'; $htmlId = $element->getHtmlId(); $html .= '
'; if (!empty($groupConfig['more_url'])) { - $html .= '' . __( - 'Learn More' - ) . ''; + $html .= '' + . __('Learn More') . ''; } if (!empty($groupConfig['demo_url'])) { - $html .= '' . __( - 'View Demo' - ) . ''; + $html .= '' + . __('View Demo') . ''; } $html .= '
'; @@ -104,7 +108,20 @@ protected function _getHeaderTitleHtml($element) } /** - * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * Check whether current payment method is enabled + * + * @param AbstractElement $element + * @return bool + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + protected function isPaymentEnabled($element) + { + return (bool)(string)$this->backendConfig->getConfigDataValue('buckaroo_magento2/account/active') > 0; + } + + /** + * @param AbstractElement $element * @return string * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ @@ -114,7 +131,7 @@ protected function _getHeaderCommentHtml($element) } /** - * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @param AbstractElement $element * @return false * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ @@ -124,7 +141,7 @@ protected function _isCollapseState($element) } /** - * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @param AbstractElement $element * @return string * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ @@ -153,25 +170,12 @@ protected function _getExtraJs($element) } /** - * @param \Magento\Framework\Data\Form\Element\AbstractElement $element + * @param AbstractElement $element * @return string */ protected function _getFrontendClass($element) { - $enabledString = $this->_isPaymentEnabled($element) ? ' enabled' : ''; + $enabledString = $this->isPaymentEnabled($element) ? ' enabled' : ''; return parent::_getFrontendClass($element) . ' with-button' . $enabledString; } - - /** - * Check whether current payment method is enabled - * - * @param \Magento\Framework\Data\Form\Element\AbstractElement $element - * @return bool - * - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - protected function _isPaymentEnabled($element) - { - return (bool)(string) $this->_backendConfig->getConfigDataValue('buckaroo_magento2/account/active') > 0; - } } diff --git a/Block/Config/Form/Field/ColorPicker.php b/Block/Config/Form/Field/ColorPicker.php index a57d2d971..a40826921 100644 --- a/Block/Config/Form/Field/ColorPicker.php +++ b/Block/Config/Form/Field/ColorPicker.php @@ -37,4 +37,4 @@ protected function _getElementHtml(AbstractElement $element): string $element->setData('type', 'color'); return $element->getElementHtml(); } -} \ No newline at end of file +} diff --git a/Block/Config/Form/Field/Fieldset.php b/Block/Config/Form/Field/Fieldset.php index 7c21f0168..5d25fdce4 100644 --- a/Block/Config/Form/Field/Fieldset.php +++ b/Block/Config/Form/Field/Fieldset.php @@ -153,8 +153,7 @@ private function getScopeValue(): array */ protected function _getHeaderTitleHtml($element): string { - if ( - !isset($element->getGroup()['id']) || + if (!isset($element->getGroup()['id']) || !is_string($element->getGroup()['id']) ) { return parent::_getHeaderTitleHtml($element); diff --git a/Block/Config/Form/Field/LogoSelector.php b/Block/Config/Form/Field/LogoSelector.php index b4b712f37..9c958f925 100644 --- a/Block/Config/Form/Field/LogoSelector.php +++ b/Block/Config/Form/Field/LogoSelector.php @@ -29,7 +29,7 @@ class LogoSelector extends Field { protected $_template = 'Buckaroo_Magento2::in3_logo.phtml'; - protected Repository $assetRepo; + protected Repository $assetRepo; /** * @param Context $context @@ -56,8 +56,8 @@ protected function _getElementHtml(AbstractElement $element) { $element->setData('type', 'hidden'); $this->assign("input", $element->getElementHtml()); - $this->assign("inputId", $element->getHtmlId()); - $this->assign("inputValue", $element->getEscapedValue()); + $this->assign("inputId", $element->getHtmlId()); + $this->assign("inputValue", $element->getEscapedValue()); return $this->_toHtml(); } @@ -66,6 +66,6 @@ public function getLogos(): array return [ "in3.svg" => $this->assetRepo->getUrl("Buckaroo_Magento2::images/svg/in3.svg"), "in3-ideal.svg" => $this->assetRepo->getUrl("Buckaroo_Magento2::images/svg/in3-ideal.svg") - ]; + ]; } -} \ No newline at end of file +} diff --git a/Block/Config/Form/Field/VerificationMethod.php b/Block/Config/Form/Field/VerificationMethod.php index 2ff151062..20806be45 100644 --- a/Block/Config/Form/Field/VerificationMethod.php +++ b/Block/Config/Form/Field/VerificationMethod.php @@ -76,8 +76,7 @@ protected function _getFrontendClass($element): string */ protected function _getHeaderTitleHtml($element): string { - if ( - !isset($element->getGroup()['id']) || + if (!isset($element->getGroup()['id']) || !is_string($element->getGroup()['id']) ) { return parent::_getHeaderTitleHtml($element); diff --git a/Controller/Adminhtml/Giftcard/Save.php b/Controller/Adminhtml/Giftcard/Save.php index ccb10a491..e28f1e482 100644 --- a/Controller/Adminhtml/Giftcard/Save.php +++ b/Controller/Adminhtml/Giftcard/Save.php @@ -53,7 +53,6 @@ public function execute() if ($this->getRequest()->getParam('back')) { return $this->_redirect('*/*/edit', ['entity_id' => $giftcardModel->getId(), '_current' => true]); - } return $this->_redirect('*/*/'); diff --git a/Controller/Adminhtml/Notification/MarkUserNotified.php b/Controller/Adminhtml/Notification/MarkUserNotified.php index 9e63927a7..a3dfe5324 100644 --- a/Controller/Adminhtml/Notification/MarkUserNotified.php +++ b/Controller/Adminhtml/Notification/MarkUserNotified.php @@ -22,12 +22,13 @@ use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; +use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Controller\ResultInterface; use Magento\Framework\FlagManager; use Psr\Log\LoggerInterface; -class MarkUserNotified extends Action +class MarkUserNotified extends Action implements HttpPostActionInterface { /** * @var FlagManager $flagManager diff --git a/Controller/Applepay/Add.php b/Controller/Applepay/Add.php index 5c80a486e..c6801a8e1 100644 --- a/Controller/Applepay/Add.php +++ b/Controller/Applepay/Add.php @@ -63,7 +63,8 @@ public function execute() { $this->logger->addDebug(sprintf( '[ApplePay] | [Controller] | [%s:%s] - Add Product to Cart | request: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($this->getParams(), true) )); @@ -72,7 +73,8 @@ public function execute() $this->logger->addDebug(sprintf( '[ApplePay] | [Controller] | [%s:%s] - Add Product to Cart | response: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($data, true) )); diff --git a/Controller/Applepay/GetShippingMethods.php b/Controller/Applepay/GetShippingMethods.php index c11038e9d..fa424cf8f 100644 --- a/Controller/Applepay/GetShippingMethods.php +++ b/Controller/Applepay/GetShippingMethods.php @@ -78,7 +78,8 @@ public function execute() $this->logger->addDebug(sprintf( '[ApplePay] | [Controller] | [%s:%s] - Get Shipping Methods | request: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($postValues, true) )); @@ -121,7 +122,8 @@ public function execute() } catch (\Exception $exception) { $this->logger->addError(sprintf( '[ApplePay] | [Controller] | [%s:%s] - Get Shipping Methods | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $exception->getMessage() )); $errorMessage = __('Get shipping methods failed'); diff --git a/Controller/Applepay/SaveOrder.php b/Controller/Applepay/SaveOrder.php index 49c88f9a6..72a05a851 100644 --- a/Controller/Applepay/SaveOrder.php +++ b/Controller/Applepay/SaveOrder.php @@ -170,7 +170,8 @@ public function execute() ) { $this->logger->addDebug(sprintf( '[ApplePay] | [Controller] | [%s:%s] - Save Order | request: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($isPost, true) )); @@ -225,7 +226,8 @@ private function submitQuote($quote, $extra) } catch (\Throwable $th) { $this->logger->addError(sprintf( '[ApplePay] | [Controller] | [%s:%s] - Submit Quote | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); } @@ -244,7 +246,8 @@ private function handleResponse() $data = $buckarooResponseData->toArray(); $this->logger->addDebug(sprintf( '[ApplePay] | [Controller] | [%s:%s] - Save Order Handle Response | buckarooResponse: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($data, true) )); if ($buckarooResponseData->hasRedirect()) { @@ -290,7 +293,8 @@ private function processBuckarooResponse(TransactionResponse $buckarooResponseDa $url = $store->getBaseUrl() . '/' . $this->accountConfig->getSuccessRedirect($store); $this->logger->addDebug(sprintf( '[ApplePay] | [Controller] | [%s:%s] - Save Order - Redirect URL | redirectURL: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $url )); $data = [ diff --git a/Controller/Checkout/Giftcard.php b/Controller/Checkout/Giftcard.php index 79e898957..2558240a2 100644 --- a/Controller/Checkout/Giftcard.php +++ b/Controller/Checkout/Giftcard.php @@ -108,14 +108,16 @@ public function execute() } catch (ApiException $th) { $this->logger->addError(sprintf( '[Giftcard] | [Controller] | [%s:%s] - Apply Inline Giftcard | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); return $this->displayError($th->getMessage()); } catch (\Throwable $th) { $this->logger->addError(sprintf( '[Giftcard] | [Controller] | [%s:%s] - Apply Inline Giftcard | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); return $this->displayError(__('Unknown buckaroo error has occurred')); diff --git a/Controller/Checkout/Idin.php b/Controller/Checkout/Idin.php index da8837e48..0b5dfdd49 100644 --- a/Controller/Checkout/Idin.php +++ b/Controller/Checkout/Idin.php @@ -25,13 +25,14 @@ use Buckaroo\Transaction\Response\TransactionResponse; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\ResultFactory; use Magento\Payment\Gateway\Http\ClientInterface; use Magento\Payment\Gateway\Http\TransferFactoryInterface; use Magento\Payment\Gateway\Request\BuilderInterface; -class Idin extends Action +class Idin extends Action implements HttpPostActionInterface { /** * @var BuilderInterface @@ -110,7 +111,8 @@ public function execute() } catch (\Throwable $th) { $this->logger->addError(sprintf( '[iDIN] | [Controller] | [%s:%s] - Validate iDIN | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); return $this->json( diff --git a/Controller/CredentialsChecker/Index.php b/Controller/CredentialsChecker/Index.php index d060e3029..d0b5eab32 100644 --- a/Controller/CredentialsChecker/Index.php +++ b/Controller/CredentialsChecker/Index.php @@ -114,7 +114,6 @@ public function execute() return $this->doResponse([ 'success' => true ]); - } } diff --git a/Controller/Mrcash/Process.php b/Controller/Mrcash/Process.php index ea9387560..030824d05 100644 --- a/Controller/Mrcash/Process.php +++ b/Controller/Mrcash/Process.php @@ -20,6 +20,8 @@ namespace Buckaroo\Magento2\Controller\Mrcash; +use Magento\Framework\App\Action\HttpPostActionInterface; + class Process extends \Buckaroo\Magento2\Controller\Payconiq\Process { } diff --git a/Controller/Payconiq/Process.php b/Controller/Payconiq/Process.php index 030cb4fa5..1c2e0fd36 100644 --- a/Controller/Payconiq/Process.php +++ b/Controller/Payconiq/Process.php @@ -36,6 +36,7 @@ use Magento\Customer\Model\Session as CustomerSession; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\App\ResponseInterface; use Magento\Framework\Event\ManagerInterface; use Magento\Quote\Model\Quote; @@ -100,9 +101,21 @@ public function __construct( SearchCriteriaBuilder $searchCriteriaBuilder, TransactionRepositoryInterface $transactionRepository ) { - parent::__construct($context, $logger, $quote, $accountConfig, $orderRequestService, - $orderStatusFactory, $checkoutSession, $customerSession, $customerRepository, - $orderService, $eventManager, $quoteRecreate, $requestPushFactory); + parent::__construct( + $context, + $logger, + $quote, + $accountConfig, + $orderRequestService, + $orderStatusFactory, + $checkoutSession, + $customerSession, + $customerRepository, + $orderService, + $eventManager, + $quoteRecreate, + $requestPushFactory + ); $this->searchCriteriaBuilder = $searchCriteriaBuilder; $this->transactionRepository = $transactionRepository; @@ -128,7 +141,8 @@ public function execute() $errorMessage = 'Customer is different then the customer that start Payconiq process request.'; $this->logger->addError(sprintf( '[REDIRECT - Payconiq] | [Controller] | [%s:%s] - %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $errorMessage )); $this->messageManager->addErrorMessage($errorMessage); diff --git a/Controller/Pos/CheckOrderStatus.php b/Controller/Pos/CheckOrderStatus.php index 8f28e5c83..fbe268030 100644 --- a/Controller/Pos/CheckOrderStatus.php +++ b/Controller/Pos/CheckOrderStatus.php @@ -27,6 +27,7 @@ use Magento\Customer\Model\Session; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\Result\JsonFactory; use Magento\Framework\Data\Form\FormKey; @@ -37,7 +38,7 @@ /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class CheckOrderStatus extends Action +class CheckOrderStatus extends Action implements HttpPostActionInterface { /** * @var Order $order @@ -141,8 +142,8 @@ public function execute() . '?form_key=' . $this->formKey->getFormKey(); $extraData = [ 'brq_invoicenumber' => $params['orderId'], - 'brq_ordernumber' => $params['orderId'], - 'brq_statuscode' => $this->helper->getStatusCode('BUCKAROO_MAGENTO2_ORDER_FAILED'), + 'brq_ordernumber' => $params['orderId'], + 'brq_statuscode' => $this->helper->getStatusCode('BUCKAROO_MAGENTO2_ORDER_FAILED'), ]; $url = $url . '&' . http_build_query($extraData); diff --git a/Controller/Pos/SetTerminal.php b/Controller/Pos/SetTerminal.php index 0577d996a..6e83b9d7c 100644 --- a/Controller/Pos/SetTerminal.php +++ b/Controller/Pos/SetTerminal.php @@ -26,12 +26,13 @@ use Magento\Checkout\Model\ConfigProviderInterface; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpGetActionInterface; use Magento\Framework\App\ResponseInterface; use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory; use Magento\Framework\Stdlib\CookieManagerInterface; use Magento\Store\Model\StoreManagerInterface; -class SetTerminal extends Action +class SetTerminal extends Action implements HttpGetActionInterface { /** * @var array @@ -99,7 +100,8 @@ public function execute() $params = $this->getRequest()->getParams(); $this->logger->addDebug(sprintf( '[POS] | [Controller] | [%s:%s] - Set Terminal | request: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($params, true) )); diff --git a/Controller/Redirect/IdinProcess.php b/Controller/Redirect/IdinProcess.php index 1157a3fef..a3363c744 100644 --- a/Controller/Redirect/IdinProcess.php +++ b/Controller/Redirect/IdinProcess.php @@ -34,6 +34,7 @@ use Magento\Customer\Model\ResourceModel\CustomerFactory; use Magento\Customer\Model\Session as CustomerSession; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\App\ResponseInterface; use Magento\Framework\Event\ManagerInterface; use Magento\Quote\Model\Quote; @@ -41,7 +42,7 @@ /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class IdinProcess extends Process +class IdinProcess extends Process implements HttpPostActionInterface { /** * @var CustomerFactory @@ -82,9 +83,21 @@ public function __construct( RequestPushFactory $requestPushFactory, CustomerFactory $customerFactory ) { - parent::__construct($context, $logger, $quote, $accountConfig, $orderRequestService, - $orderStatusFactory, $checkoutSession, $customerSession, $customerRepository, - $orderService, $eventManager, $quoteRecreate, $requestPushFactory); + parent::__construct( + $context, + $logger, + $quote, + $accountConfig, + $orderRequestService, + $orderStatusFactory, + $checkoutSession, + $customerSession, + $customerRepository, + $orderService, + $eventManager, + $quoteRecreate, + $requestPushFactory + ); $this->customerResourceFactory = $customerFactory; } @@ -109,6 +122,8 @@ public function execute(): ResponseInterface return $this->redirectToCheckout(); } + + return $this->handleProcessedResponse('checkout'); } /** @@ -133,7 +148,8 @@ private function setCustomerIDIN(): bool $this->addErrorMessage(__('Unfortunately customer was not find by IDIN id: "%1"!', $idinCid)); $this->logger->addError(sprintf( '[REDIRECT - iDIN] | [Controller] | [%s:%s] - Customer was not find by IDIN id | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); return false; @@ -163,15 +179,15 @@ protected function redirectToCheckout(): ResponseInterface try { $this->checkoutSession->restoreQuote(); - } catch (\Exception $e) { $this->logger->addError(sprintf( '[REDIRECT - iDIN] | [Controller] | [%s:%s] - Could not restore the quote | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); } return $this->handleProcessedResponse('checkout', ['_query' => ['bk_e' => 1]]); } -} \ No newline at end of file +} diff --git a/Controller/Redirect/Process.php b/Controller/Redirect/Process.php index 436fdbc6c..0c28872de 100644 --- a/Controller/Redirect/Process.php +++ b/Controller/Redirect/Process.php @@ -37,6 +37,7 @@ use Magento\Customer\Model\Session as CustomerSession; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; +use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\App\Request\Http as Http; use Magento\Framework\App\ResponseInterface; use Magento\Framework\Event\ManagerInterface; @@ -51,7 +52,7 @@ /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Process extends Action +class Process extends Action implements HttpPostActionInterface { private const GENERAL_ERROR_MESSAGE = 'Unfortunately an error occurred while processing your payment. ' . 'Please try again. If this error persists, please choose a different payment method.'; @@ -191,7 +192,8 @@ public function execute() { $this->logger->addDebug(sprintf( '[REDIRECT] | [Controller] | [%s:%s] - Original Request | originalRequest: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($this->redirectRequest->getOriginalRequest(), true) )); @@ -228,7 +230,8 @@ public function execute() $this->logger->addDebug(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Status Code | statusCode: %s', $this->payment->getMethod(), - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $statusCode )); @@ -267,14 +270,15 @@ protected function setPaymentOutOfTransit(OrderPaymentInterface $payment): void */ public function skipWaitingOnConsumerForProcessingOrder(): bool { - if (in_array($this->payment->getMethod(), + if (in_array( + $this->payment->getMethod(), [ 'buckaroo_magento2_creditcards', 'buckaroo_magento2_paylink', 'buckaroo_magento2_payperemail', 'buckaroo_magento2_transfer' - ])) { - + ] + )) { if ($this->payment->getAdditionalInformation(BuckarooAdapter::BUCKAROO_ORIGINAL_TRANSACTION_KEY_KEY) != $this->redirectRequest->getTransactions()) { return true; @@ -370,7 +374,8 @@ private function sendKlarnaKpOrderConfirmation(int $statusCode): void $this->logger->addDebug(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Send Klarna Reservation Mail', $this->payment->getMethod(), - __METHOD__, __LINE__ + __METHOD__, + __LINE__ )); $this->orderRequestService->sendOrderEmail($this->order, true); } @@ -391,7 +396,8 @@ private function setLastQuoteOrder(): void $this->logger->addDebug(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Set Last Quote Order | currentQuoteOrder: %s', $this->payment->getMethod(), - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export([ $this->checkoutSession->getLastSuccessQuoteId(), $this->checkoutSession->getLastQuoteId(), @@ -442,7 +448,8 @@ protected function redirectSuccess(): ResponseInterface $this->logger->addDebug(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Redirect Success | redirectURL: %s', $this->payment->getMethod(), - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $url, )); @@ -507,7 +514,8 @@ private function processPendingRedirect($statusCode): ResponseInterface $this->logger->addDebug(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Redirect Pending Set Status | pendingStatus: %s', $this->payment->getMethod(), - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($pendingStatus, true), )); $this->order->setStatus($pendingStatus); @@ -523,7 +531,9 @@ private function processPendingRedirect($statusCode): ResponseInterface $this->logger->addDebug(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Redirect Pending NOT Sofort - Remove Coupon & Giftcard', $this->payment->getMethod(), - __METHOD__, __LINE__)); + __METHOD__, + __LINE__ + )); $this->removeCoupon(); $this->removeAmastyGiftcardOnFailed(); @@ -605,7 +615,8 @@ protected function removeAmastyGiftcardOnFailed(): void $this->logger->addError(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Remove Amasty Giftcard | [ERROR]: %s', $this->payment->getMethod(), - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); return; @@ -628,11 +639,12 @@ protected function handleFailed($statusCode): ResponseInterface if (!$this->getSkipHandleFailedRecreate() && (!$this->quoteRecreate->recreate($this->quote))) { - $this->logger->addError(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Could not Recreate Quote on Failed ', $this->payment->getMethod(), - __METHOD__, __LINE__)); + __METHOD__, + __LINE__ + )); } /* @@ -652,13 +664,17 @@ protected function handleFailed($statusCode): ResponseInterface $this->logger->addError(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Could not Cancel the Order.', $this->payment->getMethod(), - __METHOD__, __LINE__)); + __METHOD__, + __LINE__ + )); } $this->logger->addDebug(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Redirect Failure', $this->payment->getMethod(), - __METHOD__, __LINE__)); + __METHOD__, + __LINE__ + )); return $this->redirectFailure(); } @@ -730,7 +746,9 @@ private function redirectOnCheckoutForFailedTransaction(): ResponseInterface $this->logger->addDebug(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Redirect Failure To Checkout', $this->payment->getMethod(), - __METHOD__, __LINE__)); + __METHOD__, + __LINE__ + )); return $this->handleProcessedResponse('checkout', ['_fragment' => 'payment', '_query' => ['bk_e' => 1]]); } @@ -745,12 +763,12 @@ protected function setCustomerAndRestoreQuote(string $status): void { if (!$this->customerSession->isLoggedIn() && $this->order->getCustomerId() > 0) { $this->logger->addDebug(sprintf( - '[REDIRECT - %s] | [Controller] | [%s:%s] - Redirect %s To Checkout - Customer is not logged in', - $this->payment->getMethod(), - __METHOD__, __LINE__, - $status - ) - ); + '[REDIRECT - %s] | [Controller] | [%s:%s] - Redirect %s To Checkout - Customer is not logged in', + $this->payment->getMethod(), + __METHOD__, + __LINE__, + $status + )); try { $customer = $this->customerRepository->getById($this->order->getCustomerId()); $this->customerSession->setCustomerDataAsLoggedIn($customer); @@ -762,8 +780,10 @@ protected function setCustomerAndRestoreQuote(string $status): void $this->logger->addDebug(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Redirect %s To Checkout - Restore Quote', $this->payment->getMethod(), - __METHOD__, __LINE__, - $status)); + __METHOD__, + __LINE__, + $status + )); } if ($status == 'failed') { $this->setSkipHandleFailedRecreate(); @@ -774,9 +794,11 @@ protected function setCustomerAndRestoreQuote(string $status): void '[REDIRECT - %s] | [Controller] | [%s:%s] - Redirect %s To Checkout ' . '- Could not load customer | [ERROR]: %s', $this->payment->getMethod(), - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $status, - $e->getMessage())); + $e->getMessage() + )); } } } @@ -833,7 +855,9 @@ protected function redirectToCheckout(): ResponseInterface $this->logger->addDebug(sprintf( '[REDIRECT - %s] | [Controller] | [%s:%s] - Redirect To Checkout', $this->payment->getMethod(), - __METHOD__, __LINE__)); + __METHOD__, + __LINE__ + )); $this->setCustomerAndRestoreQuote('success'); diff --git a/Cron/LogCleaner.php b/Cron/LogCleaner.php index ee816b7dc..6be4c6132 100644 --- a/Cron/LogCleaner.php +++ b/Cron/LogCleaner.php @@ -131,7 +131,8 @@ private function proceedDb(int $retentionPeriod) } catch (\Exception $e) { $this->logger->error(sprintf( '[LOGGING] | [CRON] | [%s:%s] - Delete logs from data base. Proceed DB error. | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); } @@ -174,7 +175,8 @@ private function getAllFiles(string $path): array } catch (FileSystemException $e) { $this->logger->error(sprintf( '[LOGGING] | [CRON] | [%s:%s] - Get all files from log directory. | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); } diff --git a/Gateway/Command/GatewayCommand.php b/Gateway/Command/GatewayCommand.php index 618fdb25b..57d2c9b24 100644 --- a/Gateway/Command/GatewayCommand.php +++ b/Gateway/Command/GatewayCommand.php @@ -87,11 +87,17 @@ class GatewayCommand implements CommandInterface */ private ?SkipCommandInterface $skipCommand; + /** + * @var SpamLimitService + */ + private SpamLimitService $spamLimitService; + /** * @param BuilderInterface $requestBuilder * @param TransferFactoryInterface $transferFactory * @param ClientInterface $client * @param LoggerInterface $logger + * @param SpamLimitService $spamLimitService * @param HandlerInterface|null $handler * @param ValidatorInterface|null $validator * @param ErrorMessageMapperInterface|null $errorMessageMapper @@ -153,7 +159,7 @@ public function execute(array $commandSubject): void try { $paymentInstance = $paymentDO->getPayment()->getMethodInstance(); $this->spamLimitService->updateRateLimiterCount($paymentDO->getPayment()->getMethodInstance()); - }catch (LimitReachException $th) { + } catch (LimitReachException $th) { $this->spamLimitService->setMaxAttemptsFlags($paymentInstance, $th->getMessage()); return; } diff --git a/Gateway/Http/Client/Json.php b/Gateway/Http/Client/Json.php index d8817542b..ae1fea0c4 100644 --- a/Gateway/Http/Client/Json.php +++ b/Gateway/Http/Client/Json.php @@ -71,7 +71,8 @@ public function doRequest(array $data, $mode) $this->logger->addDebug(sprintf( '[HTTP_JSON] | [Gateway] | [%s:%s] - Create post request to payment engine | request: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($data, true) )); @@ -114,7 +115,8 @@ public function doStatusRequest($transactionId, $mode) $this->logger->addDebug(sprintf( '[HTTP_JSON] | [Gateway] | [%s:%s] - Create a status request by transaction_id | request: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($options, true) )); @@ -234,7 +236,8 @@ public function getResponse(string $uri, array $data = []) } catch (\Exception $e) { $this->logger->addError(sprintf( '[HTTP_JSON] | [Gateway] | [%s:%s] - Get Response after JSON request | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); return false; @@ -242,7 +245,8 @@ public function getResponse(string $uri, array $data = []) $this->logger->addDebug(sprintf( '[HTTP_JSON] | [Gateway] | [%s:%s] - Get Response after JSON request | response: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export(['response' => $response, 'clientStatus' => $this->client->getStatus()], true) )); diff --git a/Gateway/Request/AddressHandler/AbstractAddressHandler.php b/Gateway/Request/AddressHandler/AbstractAddressHandler.php index 2575a0a04..5d05d8bff 100644 --- a/Gateway/Request/AddressHandler/AbstractAddressHandler.php +++ b/Gateway/Request/AddressHandler/AbstractAddressHandler.php @@ -92,7 +92,6 @@ protected function updateShippingAddressCommonMapping(array $mapping, array &$re && $requestData[$key]['Name'] == $mappingItem[0]) { $requestData[$key]['_'] = $mappingItem[1]; $found = true; - } } if (!$found) { diff --git a/Gateway/Request/AddressHandler/DPDPickupAddressHandler.php b/Gateway/Request/AddressHandler/DPDPickupAddressHandler.php index 7c4b83644..4d9e4b241 100644 --- a/Gateway/Request/AddressHandler/DPDPickupAddressHandler.php +++ b/Gateway/Request/AddressHandler/DPDPickupAddressHandler.php @@ -86,7 +86,8 @@ public function updateShippingAddressByDpdParcel(CartInterface $quote, array &$r if (!$fullStreet && $quote->getDpdParcelshopId()) { $this->logger->addDebug(sprintf( '[CREATE_ORDER] | [Gateway] | [%s:%s] - Set shipping address fields by DPD Parcel | cookie: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($_COOKIE, true) )); $fullStreet = $_COOKIE['dpd-selected-parcelshop-street'] ?? ''; @@ -110,7 +111,8 @@ public function updateShippingAddressByDpdParcel(CartInterface $quote, array &$r $this->logger->addDebug(sprintf( '[CREATE_ORDER] | [Gateway] | [%s:%s] - Set shipping address fields by DPD Parcel | newAddress: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($mapping, true) )); diff --git a/Gateway/Request/AddressHandler/MyParcelAddressHandler.php b/Gateway/Request/AddressHandler/MyParcelAddressHandler.php index 35fc53026..8461f0581 100644 --- a/Gateway/Request/AddressHandler/MyParcelAddressHandler.php +++ b/Gateway/Request/AddressHandler/MyParcelAddressHandler.php @@ -72,7 +72,8 @@ public function handle(Order $order, OrderAddressInterface $shippingAddress): Or $this->logger->addError(sprintf( '[CREATE_ORDER] | [Gateway] | [%s:%s] - Error related to json_decode' . ' (MyParcel plugin compatibility) | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $je->getMessage() )); } @@ -116,7 +117,8 @@ protected function updateShippingAddressByMyParcel(array $myParcelLocation, arra $this->logger->addDebug(sprintf( '[CREATE_ORDER] | [Gateway] | [%s:%s] - Set shipping address fields by myParcelNL | newAddress: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($mapping, true) )); @@ -143,7 +145,8 @@ protected function updateShippingAddressByMyParcelV2(array $myParcelLocation, ar $this->logger->addDebug(sprintf( '[CREATE_ORDER] | [Gateway] | [%s:%s] - Set shipping address fields by myParcelNL V2 | newAddress: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($mapping, true) )); diff --git a/Gateway/Request/Articles/ArticlesHandler/AbstractArticlesHandler.php b/Gateway/Request/Articles/ArticlesHandler/AbstractArticlesHandler.php index 9c5b0df9e..162eded81 100644 --- a/Gateway/Request/Articles/ArticlesHandler/AbstractArticlesHandler.php +++ b/Gateway/Request/Articles/ArticlesHandler/AbstractArticlesHandler.php @@ -321,8 +321,7 @@ protected function getItemsLines(): array */ protected function skipItem($item): bool { - if (empty($item) - || $item->getRowTotalInclTax() == 0 + if ($item->getRowTotalInclTax() == 0 || $item->hasParentItemId() ) { return true; diff --git a/Gateway/Request/BasicParameter/CustomParametersDataBuilder.php b/Gateway/Request/BasicParameter/CustomParametersDataBuilder.php index 2aadd698b..1704ca146 100644 --- a/Gateway/Request/BasicParameter/CustomParametersDataBuilder.php +++ b/Gateway/Request/BasicParameter/CustomParametersDataBuilder.php @@ -238,7 +238,7 @@ private function setStreetData(string $addressData, array $customerData) $customerData[$addressData] = 'street'; foreach ($customerData as $customerDataKey => $value) { - if (in_array($value, ['street', 'housenumber', 'houseadditionalnumber']) ) { + if (in_array($value, ['street', 'housenumber', 'houseadditionalnumber'])) { $customerData[$customerDataKey] = $streetFormat[$value] ?? ''; } } diff --git a/Gateway/Request/SaveIssuerDataBuilder.php b/Gateway/Request/SaveIssuerDataBuilder.php index 9d2544776..0866e6f88 100644 --- a/Gateway/Request/SaveIssuerDataBuilder.php +++ b/Gateway/Request/SaveIssuerDataBuilder.php @@ -77,4 +77,4 @@ public function saveLastUsedIssuer($payment): void ); } } -} \ No newline at end of file +} diff --git a/Gateway/Request/VersionDataBuilder.php b/Gateway/Request/VersionDataBuilder.php index 3b6c06c69..ecff8c122 100644 --- a/Gateway/Request/VersionDataBuilder.php +++ b/Gateway/Request/VersionDataBuilder.php @@ -35,4 +35,4 @@ public function build(array $buildSubject) return []; } -} \ No newline at end of file +} diff --git a/Gateway/Response/TransactionIdHandler.php b/Gateway/Response/TransactionIdHandler.php index dc4c447a7..4c233b292 100644 --- a/Gateway/Response/TransactionIdHandler.php +++ b/Gateway/Response/TransactionIdHandler.php @@ -48,7 +48,6 @@ public function handle(array $handlingSubject, array $response): void $transactionKey = $transactionResponse->getTransactionKey(); if (!empty($transactionKey)) { - $payment->setTransactionId($transactionKey); /** * Save the payment's transaction key. diff --git a/Gateway/Validator/IssuerValidator.php b/Gateway/Validator/IssuerValidator.php index 6267638f5..8005e782b 100644 --- a/Gateway/Validator/IssuerValidator.php +++ b/Gateway/Validator/IssuerValidator.php @@ -21,12 +21,10 @@ namespace Buckaroo\Magento2\Gateway\Validator; -use Buckaroo\Magento2\Gateway\Helper\SubjectReader; use Buckaroo\Magento2\Model\ConfigProvider\Method\ConfigProviderInterface; use Buckaroo\Magento2\Model\ConfigProvider\Method\Factory; use Magento\Framework\App\Request\Http as HttpRequest; use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Exception\NotFoundException; use Magento\Framework\Serialize\Serializer\Json; use Magento\Payment\Gateway\Validator\AbstractValidator; use Magento\Payment\Gateway\Validator\ResultInterface; diff --git a/Gateway/Validator/SpamLimitValidator.php b/Gateway/Validator/SpamLimitValidator.php index 8672ba32a..809f5e06f 100644 --- a/Gateway/Validator/SpamLimitValidator.php +++ b/Gateway/Validator/SpamLimitValidator.php @@ -29,11 +29,6 @@ class SpamLimitValidator extends AbstractValidator { - /** - * @var ResultInterfaceFactory - */ - private $resultInterfaceFactory; - /** * @var SpamLimitService */ @@ -49,7 +44,6 @@ public function __construct( ) { parent::__construct($resultFactory); $this->spamLimitService = $spamLimitService; - } /** @@ -64,11 +58,13 @@ public function validate(array $validationSubject): ResultInterface $isValid = true; if ($this->spamLimitService->isSpamLimitActive($paymentMethodInstance) - && $this->spamLimitService->isSpamLimitReached($paymentMethodInstance, - $this->spamLimitService->getPaymentAttemptsStorage())) { + && $this->spamLimitService->isSpamLimitReached( + $paymentMethodInstance, + $this->spamLimitService->getPaymentAttemptsStorage() + )) { $isValid = false; } return $this->createResult($isValid); } -} \ No newline at end of file +} diff --git a/Helper/Data.php b/Helper/Data.php index 4a928a1eb..7c148ee05 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -310,8 +310,11 @@ public function isMobile(): bool { $userAgent = $this->httpHeader->getHttpUserAgent(); return preg_match( - '/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$userAgent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', - substr($userAgent,0,4) + '/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', + $userAgent + ) || preg_match( + '/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', + substr($userAgent, 0, 4) ); } diff --git a/Helper/PaymentGroupTransaction.php b/Helper/PaymentGroupTransaction.php index ca744f9b3..185ce10f6 100644 --- a/Helper/PaymentGroupTransaction.php +++ b/Helper/PaymentGroupTransaction.php @@ -92,7 +92,8 @@ public function saveGroupTransaction($response) { $this->logger->addDebug(sprintf( '[GROUP_TRANSACTION] | [Helper] | [%s:%s] - Save group transaction in database | response: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($response, true) )); diff --git a/Logging/BuckarooLoggerInterface.php b/Logging/BuckarooLoggerInterface.php index 546e9acaa..1fd1ef984 100644 --- a/Logging/BuckarooLoggerInterface.php +++ b/Logging/BuckarooLoggerInterface.php @@ -30,4 +30,4 @@ public function addError(string $message): bool; public function addWarning(string $message): bool; public function debug($message, array $context = []): void; -} \ No newline at end of file +} diff --git a/Model/Adapter/BuckarooAdapter.php b/Model/Adapter/BuckarooAdapter.php index 038512d3f..5d19b575d 100644 --- a/Model/Adapter/BuckarooAdapter.php +++ b/Model/Adapter/BuckarooAdapter.php @@ -127,7 +127,8 @@ public function execute(string $action, string $method, array $data): Transactio } catch (\Throwable $th) { $this->logger->addError(sprintf( '[SDK] | [Adapter] | [%s:%s] - Execute request using Buckaroo SDK | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); @@ -148,7 +149,8 @@ public function getIdealIssuers(): array } catch (\Throwable $th) { $this->logger->addError(sprintf( '[SDK] | [Adapter] | [%s:%s] - Get ideal issuers | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); return []; diff --git a/Model/BuckarooStatusCode.php b/Model/BuckarooStatusCode.php index 91d04fa14..4d154249f 100644 --- a/Model/BuckarooStatusCode.php +++ b/Model/BuckarooStatusCode.php @@ -130,4 +130,4 @@ public function getPendingStatuses(): array 'BUCKAROO_MAGENTO2_STATUSCODE_WAITING_ON_USER_INPUT' ]; } -} \ No newline at end of file +} diff --git a/Model/ConfigProvider/Account.php b/Model/ConfigProvider/Account.php index 75224490f..e62f91855 100644 --- a/Model/ConfigProvider/Account.php +++ b/Model/ConfigProvider/Account.php @@ -215,9 +215,9 @@ protected function getMethodConfigProvider($paymentMethod) * @param string|null $label * @return string */ - public function getParsedLabel(Store $store, OrderInterface $order,string $label = null) + public function getParsedLabel(Store $store, OrderInterface $order, string $label = null) { - if($label === null) { + if ($label === null) { $label = $this->getTransactionLabel($store); } @@ -702,6 +702,4 @@ public function getIdinCategory($store = null) $store ); } - - } diff --git a/Model/ConfigProvider/Method/AbstractConfigProvider.php b/Model/ConfigProvider/Method/AbstractConfigProvider.php index 85edc2583..b0bc2863c 100644 --- a/Model/ConfigProvider/Method/AbstractConfigProvider.php +++ b/Model/ConfigProvider/Method/AbstractConfigProvider.php @@ -200,7 +200,7 @@ protected function formatIssuers() { return array_map( function ($issuer) { - if(isset($issuer['imgName'])) { + if (isset($issuer['imgName'])) { $issuer['img'] = $this->getImageUrl("ideal/{$issuer['imgName']}", "svg"); } return $issuer; @@ -211,7 +211,7 @@ function ($issuer) { public function getCreditcardLogo(string $code): string { - if($code === 'cartebleuevisa') { + if ($code === 'cartebleuevisa') { $code = 'cartebleue'; } diff --git a/Model/ConfigProvider/Method/CapayableIn3.php b/Model/ConfigProvider/Method/CapayableIn3.php index 5117e90d2..c9e820e9a 100644 --- a/Model/ConfigProvider/Method/CapayableIn3.php +++ b/Model/ConfigProvider/Method/CapayableIn3.php @@ -77,10 +77,10 @@ public function getConfig() public function isV3($storeId = null): bool { return $this->scopeConfig->getValue( - self::XPATH_CAPAYABLEIN3_API_VERSION, - ScopeInterface::SCOPE_STORE, - $storeId - ) !== 'V2'; + self::XPATH_CAPAYABLEIN3_API_VERSION, + ScopeInterface::SCOPE_STORE, + $storeId + ) !== 'V2'; } public function getLogo($storeId = null): string diff --git a/Model/ConfigProvider/Method/Creditcard.php b/Model/ConfigProvider/Method/Creditcard.php index eaf2009b5..df64bd3c5 100644 --- a/Model/ConfigProvider/Method/Creditcard.php +++ b/Model/ConfigProvider/Method/Creditcard.php @@ -307,11 +307,11 @@ public function getMaestroUnsecureHold($store = null) } /** - * Selection type radio checkbox or drop down - * - * @param null|int|string $store - * @return mixed - */ + * Selection type radio checkbox or drop down + * + * @param null|int|string $store + * @return mixed + */ public function getSelectionType($store = null) { $methodConfig = $this->scopeConfig->getValue( diff --git a/Model/ConfigProvider/Method/Paypal.php b/Model/ConfigProvider/Method/Paypal.php index 589308f3b..07cc18209 100644 --- a/Model/ConfigProvider/Method/Paypal.php +++ b/Model/ConfigProvider/Method/Paypal.php @@ -190,7 +190,9 @@ public function getButtonColor($store = null): string */ public function getButtonShape($store = null): string { - return $this->getConfigFromXpath(self::XPATH_PAYPAL_EXPRESS_BUTTON_IS_ROUNDED, $store) === "1" ? 'pill' : 'rect'; + return $this->getConfigFromXpath(self::XPATH_PAYPAL_EXPRESS_BUTTON_IS_ROUNDED, $store) === "1" + ? 'pill' + : 'rect'; } diff --git a/Model/Giftcard/Api/PayResponse.php b/Model/Giftcard/Api/PayResponse.php index 9819a20e7..d7b1b8b90 100644 --- a/Model/Giftcard/Api/PayResponse.php +++ b/Model/Giftcard/Api/PayResponse.php @@ -102,4 +102,4 @@ public function getRemainingAmountMessage() { return $this->getData('remainingAmountMessage'); } -} \ No newline at end of file +} diff --git a/Model/Giftcard/Remove.php b/Model/Giftcard/Remove.php index 74760328c..4232023af 100644 --- a/Model/Giftcard/Remove.php +++ b/Model/Giftcard/Remove.php @@ -77,11 +77,11 @@ public function remove(string $transactionId, string $orderId, $payment) ); } - $this->removeCommand->execute([ + $this->removeCommand->execute([ 'payment' => $this->paymentDataObjectFactory->create($payment), 'giftcardTransaction' => $giftcardTransaction, 'amount' => $giftcardTransaction->getAmount() - ]); + ]); } /** diff --git a/Model/Giftcard/RemoveException.php b/Model/Giftcard/RemoveException.php index a273fa5a0..f2192a38e 100644 --- a/Model/Giftcard/RemoveException.php +++ b/Model/Giftcard/RemoveException.php @@ -23,4 +23,4 @@ class RemoveException extends \Exception { -} \ No newline at end of file +} diff --git a/Model/Giftcard/Response/Giftcard.php b/Model/Giftcard/Response/Giftcard.php index f9f67fc87..8153554f0 100644 --- a/Model/Giftcard/Response/Giftcard.php +++ b/Model/Giftcard/Response/Giftcard.php @@ -186,8 +186,7 @@ public function isSuccessful(): bool */ public function getRemainderAmount() { - if ( - !isset($this->response->data()['RequiredAction']['PayRemainderDetails']['RemainderAmount']) || + if (!isset($this->response->data()['RequiredAction']['PayRemainderDetails']['RemainderAmount']) || !is_scalar($this->response->data()['RequiredAction']['PayRemainderDetails']['RemainderAmount']) ) { return 0; @@ -202,8 +201,7 @@ public function getRemainderAmount() */ public function getAmountDebit() { - if ( - empty($this->response->getAmount()) || + if (empty($this->response->getAmount()) || !is_scalar($this->response->getAmount()) ) { return 0; @@ -222,7 +220,6 @@ public function getCurrency(): ?string return null; } return $this->response->data()['RequiredAction']['PayRemainderDetails']['Currency']; - } public function rollbackAllPartialPayments($order) @@ -235,10 +232,11 @@ public function rollbackAllPartialPayments($order) } catch (\Throwable $th) { $this->logger->addDebug(sprintf( '[GIFTCARD] | [Model] | [%s:%s] - Rollback all Partial Payment | [ERROR]: %s', - __METHOD__, __LINE__, - $th->getMessage())); + __METHOD__, + __LINE__, + $th->getMessage() + )); } - } /** @@ -260,8 +258,7 @@ protected function saveGroupTransaction() protected function cancelOrder() { $order = $this->createOrderFromQuote(); - if ( - $order instanceof OrderInterface && + if ($order instanceof OrderInterface && $order->getEntityId() !== null ) { $this->orderManagement->cancel($order->getEntityId()); diff --git a/Model/GroupTransaction.php b/Model/GroupTransaction.php index 72595f206..7a7f96141 100644 --- a/Model/GroupTransaction.php +++ b/Model/GroupTransaction.php @@ -160,4 +160,4 @@ public function getRemainingAmount() { return $this->getAmount() - $this->getRefundedAmount(); } -} \ No newline at end of file +} diff --git a/Model/GuestPaymentInformationManagement.php b/Model/GuestPaymentInformationManagement.php index da598baec..6a8f321db 100644 --- a/Model/GuestPaymentInformationManagement.php +++ b/Model/GuestPaymentInformationManagement.php @@ -49,8 +49,7 @@ * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class GuestPaymentInformationManagement extends MagentoGuestPaymentInformationManagement - implements GuestPaymentInformationManagementInterface +class GuestPaymentInformationManagement extends MagentoGuestPaymentInformationManagement implements GuestPaymentInformationManagementInterface { /** * @var Factory @@ -153,7 +152,8 @@ public function buckarooSavePaymentInformationAndPlaceOrder( $buckarooResponse = $this->buckarooResponseData->getResponse()->toArray(); $this->logger->debug(sprintf( '[PLACE_ORDER] | [Webapi] | [%s:%s] - Guest Users | buckarooResponse: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, print_r($buckarooResponse, true) )); diff --git a/Model/Method/Capayable/In3V3Builder.php b/Model/Method/Capayable/In3V3Builder.php index 92dd73caa..ccba40df1 100644 --- a/Model/Method/Capayable/In3V3Builder.php +++ b/Model/Method/Capayable/In3V3Builder.php @@ -29,113 +29,55 @@ class In3V3Builder { /** @var AddressFormatter */ public $addressFormatter; - + public function __construct( AddressFormatter $addressFormatter ) { $this->addressFormatter = $addressFormatter; } - - - public function build($payment) { + public function build($payment) + { return [ - 'Name' => 'In3', - 'Action' => 'Pay', + 'Name' => 'In3', + 'Action' => 'Pay', 'RequestParameter' => array_merge( $this->getArticles($payment), $this->getBillingCustomer( $payment->getOrder()->getBillingAddress(), $this->getBirthDate($payment), - $this->getPhone($payment->getOrder()->getBillingAddress() ,$payment) + $this->getPhone($payment->getOrder()->getBillingAddress(), $payment) ), $this->getShippingAddress($payment->getOrder()->getShippingAddress()) ) ]; } - /** - * Get formated shipping address - * - * @param Address $billingAddress - * - * @return void - */ - protected function getShippingAddress( - Address $shippingAddress, - ): array + protected function getArticles($payment) { - $i = 1; - - $streetData = $this->addressFormatter->formatStreet($shippingAddress->getStreet()); - - $data = [ - $this->row($streetData['street'], 'Street', 'ShippingCustomer', $i), - $this->row($streetData['house_number'], 'StreetNumber', 'ShippingCustomer', $i), - $this->row($shippingAddress->getPostcode(), 'PostalCode', 'ShippingCustomer', $i), - $this->row($shippingAddress->getCity(), 'City', 'ShippingCustomer', $i), - $this->row($shippingAddress->getCountryId(), 'CountryCode', 'ShippingCustomer', $i), - ]; - - if (strlen($streetData['number_addition']) > 0) { - $data[] = $this->row($streetData['number_addition'], 'StreetNumberSuffix', 'ShippingCustomer', $i); - } - - if(strlen((string)$shippingAddress->getRegion())) { - $data[] = $this->row($shippingAddress->getRegion(), 'Region', 'ShippingCustomer', $i); - } - - return $data; - } - - /** - * Get formated billing customer - * - * @param Address $billingAddress - * - * @return void - */ - protected function getBillingCustomer( - Address $billingAddress, - string $birthDate, - string $phone - ): array - { - $i = 2; - - $streetData = $this->addressFormatter->formatStreet($billingAddress->getStreet()); - - $customerNumber = "guest"; + $order = $payment->getOrder(); + $products = $this->getProducts($order->getAllItems()); - if($billingAddress->getEntityId() !== null) { - $customerNumber = $billingAddress->getEntityId(); - } - $data = [ - $this->row((string)$customerNumber, 'CustomerNumber', 'BillingCustomer', $i), - $this->row($billingAddress->getFirstname(), 'FirstName', 'BillingCustomer', $i), - $this->row($billingAddress->getLastname(), 'LastName', 'BillingCustomer', $i), - $this->row($this->getInitials($billingAddress), 'Initials', 'BillingCustomer', $i), - $this->row($birthDate, 'BirthDate', 'BillingCustomer', $i), - $this->row($phone, 'Phone', 'BillingCustomer', $i), - $this->row($billingAddress->getEmail(), 'Email', 'BillingCustomer', $i), - $this->row("B2C", 'Category', 'BillingCustomer', $i), - - $this->row($streetData['street'], 'Street', 'BillingCustomer', $i), - $this->row($streetData['house_number'], 'StreetNumber', 'BillingCustomer', $i), - $this->row($billingAddress->getPostcode(), 'PostalCode', 'BillingCustomer', $i), - $this->row($billingAddress->getCity(), 'City', 'BillingCustomer', $i), - $this->row($billingAddress->getCountryId(), 'CountryCode', 'BillingCustomer', $i), - ]; + $costs = array_merge( + $this->getDiscountLine($order), + $this->getFeeLine($order), + $this->getShippingCostsLine($order) + ); - if (strlen((string)$streetData['number_addition']) > 0) { - $data[] = $this->row($streetData['number_addition'], 'StreetNumberSuffix', 'BillingCustomer', $i); - } + $articles = array_merge( + $products, + count($costs) ? $costs : [] + ); - if(strlen((string)$billingAddress->getRegion())) { - $data[] = $this->row($billingAddress->getRegion(), 'Region', 'BillingCustomer', $i); + $roundingErrors = $this->getRoundingErrors($payment, $articles); + if (is_array($roundingErrors)) { + $articles = array_merge( + $articles, + [$roundingErrors] + ); } - return $data; + return $this->formatArticle($articles); } /** @@ -153,16 +95,16 @@ protected function getProducts(array $orderItems) /** @var OrderItemInterface $item */ foreach ($orderItems as $item) { - if (empty($item) || $item->getParentItem() !== null) { + if ($item->getParentItem() !== null) { continue; } - + $productData[] = [ - 'id' => $item->getSku(), - 'description'=> $item->getName(), - 'qty' => $item->getQtyOrdered(), - 'price' => $item->getBasePriceInclTax(), - 'vat' => $item->getTaxPercent(), + 'id' => $item->getSku(), + 'description' => $item->getName(), + 'qty' => $item->getQtyOrdered(), + 'price' => $item->getBasePriceInclTax(), + 'vat' => $item->getTaxPercent(), ]; $i++; @@ -175,49 +117,82 @@ protected function getProducts(array $orderItems) return $productData; } - protected function getArticles($payment) { - $order = $payment->getOrder(); - $products = $this->getProducts($order->getAllItems()); + /** + * @param OrderInterface $order + * + * @return array + */ + protected function getDiscountLine($order) + { + $discount = abs((double)$order->getDiscountAmount()); - $costs = array_merge( - $this->getDiscountLine($order), - $this->getFeeLine($order), - $this->getShippingCostsLine($order) - ); + if ($discount <= 0) { + return []; + } - $articles = array_merge( - $products, - count($costs) ? $costs: [] - ); + $discount = (-1 * round($discount, 2)); - $roundingErrors = $this->getRoundingErrors($payment, $articles); - if(is_array($roundingErrors)) { - $articles = array_merge( - $articles, - [$roundingErrors] - ); - } - - return $this->formatArticle($articles); + return [ + [ + 'id' => 'discount', + 'description' => 'Discount Errors', + 'qty' => 1, + 'price' => $discount, + 'vat' => 0, + ] + ]; } - private function formatArticle($articles) + /** + * @param OrderInterface $order + * + * @return array + */ + protected function getFeeLine($order) { - $formated = []; + $fee = (double)$order->getBuckarooFee(); - foreach ($articles as $i => $article) { - $formated = array_merge($formated, [ - $this->row($article['id'], 'Identifier', 'Article', $i+3), - $this->row($article['description'], 'Description', 'Article', $i+3), - $this->row($article['qty'], 'Quantity', 'Article', $i+3), - $this->row($article['price'], 'GrossUnitPrice', 'Article', $i+3), - $this->row($article['vat'], 'VatPercentage', 'Article', $i+3) - ]); + if ($fee <= 0) { + return []; } - return $formated; + + $feeTax = (double)$order->getBuckarooFeeTaxAmount(); + $feeInclTax = round($fee + $feeTax, 2); + return [ + [ + 'id' => 'fee', + 'description' => 'Payment Fee', + 'qty' => 1, + 'price' => $feeInclTax, + 'vat' => 0, + ] + ]; + } + + /** + * @param OrderInterface $order + * + * @return array + */ + protected function getShippingCostsLine($order) + { + $shippingAmount = $order->getShippingInclTax(); + if ($shippingAmount <= 0) { + return []; + } + + return [ + [ + 'id' => 'shipping', + 'description' => 'Shipping', + 'qty' => 1, + 'price' => $shippingAmount, + 'vat' => 0, + ] + ]; } - /** + /** * @param $payment * @param array $articles * @@ -227,116 +202,131 @@ protected function getRoundingErrors($payment, array $articles) { $total = array_sum( array_map(function ($article) { - return round((float)$article['price'],2) * (int)$article['qty'] ; + return round((float)$article['price'], 2) * (int)$article['qty']; }, $articles) ); $orderAmount = $payment->getData('amount_ordered'); - $amount = round($orderAmount, 2) - round($total,2); + $amount = round($orderAmount, 2) - round($total, 2); - if(abs($amount) < 0.01) { + if (abs($amount) < 0.01) { return null; } - return [[ - 'id' => 'rounding_errors', - 'description'=> 'Rounding Errors', - 'qty' => 1, - 'price' => $amount, - 'vat' => 0, - ]]; + return [ + [ + 'id' => 'rounding_errors', + 'description' => 'Rounding Errors', + 'qty' => 1, + 'price' => $amount, + 'vat' => 0, + ] + ]; } - /** - * @param OrderInterface $order - * - * @return array - */ - protected function getDiscountLine($order) + private function formatArticle($articles) { - $discount = abs((double)$order->getDiscountAmount()); + $formated = []; - if ($discount <= 0) { - return []; + foreach ($articles as $i => $article) { + $formated = array_merge($formated, [ + $this->row($article['id'], 'Identifier', 'Article', $i + 3), + $this->row($article['description'], 'Description', 'Article', $i + 3), + $this->row($article['qty'], 'Quantity', 'Article', $i + 3), + $this->row($article['price'], 'GrossUnitPrice', 'Article', $i + 3), + $this->row($article['vat'], 'VatPercentage', 'Article', $i + 3) + ]); } - - $discount = (-1 * round($discount, 2)); - - return [[ - 'id' => 'discount', - 'description'=> 'Discount Errors', - 'qty' => 1, - 'price' => $discount, - 'vat' => 0, - ]]; + return $formated; } /** - * @param OrderInterface $order + * Get row + * + * @param mixed $value + * @param string $name + * @param string|int|null $groupType + * @param string|int|null $groupId * * @return array */ - protected function getFeeLine($order) + private function row($value, $name, $groupType = null, $groupId = null) { - $fee = (double)$order->getBuckarooFee(); + $row = [ + '_' => $value, + 'Name' => $name + ]; - if ($fee <= 0) { - return []; + if ($groupType !== null) { + $row['Group'] = $groupType; } - $feeTax = (double)$order->getBuckarooFeeTaxAmount(); - $feeInclTax = round($fee + $feeTax, 2); - return [[ - 'id' => 'fee', - 'description'=> 'Payment Fee', - 'qty' => 1, - 'price' => $feeInclTax, - 'vat' => 0, - ]]; + if ($groupId !== null) { + $row['GroupID'] = $groupId; + } + + return $row; } /** - * @param OrderInterface $order + * Get formated billing customer * - * @return array + * @param Address $billingAddress + * + * @return void */ - protected function getShippingCostsLine($order) - { - $shippingAmount = $order->getShippingInclTax(); - if ($shippingAmount <= 0) { - return []; + protected function getBillingCustomer( + Address $billingAddress, + string $birthDate, + string $phone + ): array { + $i = 2; + + $streetData = $this->addressFormatter->formatStreet($billingAddress->getStreet()); + + $customerNumber = "guest"; + + if ($billingAddress->getEntityId() !== null) { + $customerNumber = $billingAddress->getEntityId(); + } + $data = [ + $this->row((string)$customerNumber, 'CustomerNumber', 'BillingCustomer', $i), + $this->row($billingAddress->getFirstname(), 'FirstName', 'BillingCustomer', $i), + $this->row($billingAddress->getLastname(), 'LastName', 'BillingCustomer', $i), + $this->row($this->getInitials($billingAddress), 'Initials', 'BillingCustomer', $i), + $this->row($birthDate, 'BirthDate', 'BillingCustomer', $i), + $this->row($phone, 'Phone', 'BillingCustomer', $i), + $this->row($billingAddress->getEmail(), 'Email', 'BillingCustomer', $i), + $this->row("B2C", 'Category', 'BillingCustomer', $i), + + $this->row($streetData['street'], 'Street', 'BillingCustomer', $i), + $this->row($streetData['house_number'], 'StreetNumber', 'BillingCustomer', $i), + $this->row($billingAddress->getPostcode(), 'PostalCode', 'BillingCustomer', $i), + $this->row($billingAddress->getCity(), 'City', 'BillingCustomer', $i), + $this->row($billingAddress->getCountryId(), 'CountryCode', 'BillingCustomer', $i), + ]; + + if (strlen((string)$streetData['number_addition']) > 0) { + $data[] = $this->row($streetData['number_addition'], 'StreetNumberSuffix', 'BillingCustomer', $i); + } + + if (strlen((string)$billingAddress->getRegion())) { + $data[] = $this->row($billingAddress->getRegion(), 'Region', 'BillingCustomer', $i); } - return [[ - 'id' => 'shipping', - 'description'=> 'Shipping', - 'qty' => 1, - 'price' => $shippingAmount, - 'vat' => 0, - ]]; + return $data; } /** - * Get phone + * Get initials * * @param Address $address - * @param OrderPaymentInterface|InfoInterface $payment * * @return string */ - private function getPhone(Address $address, $payment) { - $phone = $address->getTelephone(); - - if ($payment->getAdditionalInformation('customer_telephone') !== null) { - $phone = $payment->getAdditionalInformation('customer_telephone'); - } - - $phoneData = $this->addressFormatter->formatTelephone( - $phone, - $address->getCountryId() - ); - - return $phoneData['clean']; + private function getInitials(Address $address): string + { + return substr($address->getFirstname(), 0, 1) . substr($address->getLastname(), 0, 1); } /** @@ -346,9 +336,10 @@ private function getPhone(Address $address, $payment) { * * @return string|null */ - private function getBirthDate($payment) { + private function getBirthDate($payment) + { $birthDate = $payment->getAdditionalInformation('customer_DoB'); - if(!is_string($birthDate)) { + if (!is_string($birthDate)) { return null; } @@ -356,42 +347,59 @@ private function getBirthDate($payment) { } /** - * Get initials + * Get phone * * @param Address $address + * @param OrderPaymentInterface|InfoInterface $payment * * @return string */ - private function getInitials(Address $address): string + private function getPhone(Address $address, $payment) { - return substr($address->getFirstname(), 0, 1) . substr($address->getLastname(), 0, 1); + $phone = $address->getTelephone(); + + if ($payment->getAdditionalInformation('customer_telephone') !== null) { + $phone = $payment->getAdditionalInformation('customer_telephone'); + } + + $phoneData = $this->addressFormatter->formatTelephone( + $phone, + $address->getCountryId() + ); + + return $phoneData['clean']; } /** - * Get row + * Get formated shipping address * - * @param mixed $value - * @param string $name - * @param string|int|null $groupType - * @param string|int|null $groupId + * @param Address $billingAddress * * @return void */ - private function row($value, $name, $groupType = null, $groupId = null) - { - $row = [ - '_' => $value, - 'Name' => $name + protected function getShippingAddress( + Address $shippingAddress, + ): array { + $i = 1; + + $streetData = $this->addressFormatter->formatStreet($shippingAddress->getStreet()); + + $data = [ + $this->row($streetData['street'], 'Street', 'ShippingCustomer', $i), + $this->row($streetData['house_number'], 'StreetNumber', 'ShippingCustomer', $i), + $this->row($shippingAddress->getPostcode(), 'PostalCode', 'ShippingCustomer', $i), + $this->row($shippingAddress->getCity(), 'City', 'ShippingCustomer', $i), + $this->row($shippingAddress->getCountryId(), 'CountryCode', 'ShippingCustomer', $i), ]; - if ($groupType !== null) { - $row['Group'] = $groupType; + if (strlen($streetData['number_addition']) > 0) { + $data[] = $this->row($streetData['number_addition'], 'StreetNumberSuffix', 'ShippingCustomer', $i); } - if ($groupId !== null) { - $row['GroupID'] = $groupId; + if (strlen((string)$shippingAddress->getRegion())) { + $data[] = $this->row($shippingAddress->getRegion(), 'Region', 'ShippingCustomer', $i); } - return $row; + return $data; } } diff --git a/Model/Method/LimitReachException.php b/Model/Method/LimitReachException.php index 6044e741a..fd3fe0785 100644 --- a/Model/Method/LimitReachException.php +++ b/Model/Method/LimitReachException.php @@ -23,4 +23,4 @@ class LimitReachException extends \Exception { -} \ No newline at end of file +} diff --git a/Model/PaymentInformationManagement.php b/Model/PaymentInformationManagement.php index d47ea0661..b5d56e5d1 100644 --- a/Model/PaymentInformationManagement.php +++ b/Model/PaymentInformationManagement.php @@ -128,7 +128,8 @@ public function buckarooSavePaymentInformationAndPlaceOrder( $buckarooResponse = $this->buckarooResponseData->getResponse()->toArray(); $this->logger->debug(sprintf( '[PLACE_ORDER] | [Webapi] | [%s:%s] - Logged In Users | buckarooResponse: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, print_r($buckarooResponse, true) )); diff --git a/Model/PaypalExpress/OrderCreate.php b/Model/PaypalExpress/OrderCreate.php index b29f5314a..56d5df50b 100644 --- a/Model/PaypalExpress/OrderCreate.php +++ b/Model/PaypalExpress/OrderCreate.php @@ -130,14 +130,16 @@ public function execute( } catch (NoSuchEntityException $th) { $this->logger->addError(sprintf( '[CREATE_ORDER - PayPal Express] | [Model] | [%s:%s] - Create Order - No such entity | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); throw new PaypalExpressException(__("Failed to create order"), 1, $th); } catch (\Throwable $th) { $this->logger->addError(sprintf( '[CREATE_ORDER - PayPal Express] | [Model] | [%s:%s] - Create Order | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); throw $th; diff --git a/Model/PaypalExpress/QuoteCreate.php b/Model/PaypalExpress/QuoteCreate.php index dabad6de2..9ead042e6 100644 --- a/Model/PaypalExpress/QuoteCreate.php +++ b/Model/PaypalExpress/QuoteCreate.php @@ -26,6 +26,8 @@ use Buckaroo\Magento2\Api\PaypalExpressQuoteCreateInterface; use Buckaroo\Magento2\Api\Data\ExpressMethods\ShippingAddressRequestInterface; use Buckaroo\Magento2\Api\Data\PaypalExpress\QuoteCreateResponseInterfaceFactory; +use Magento\Quote\Api\Data\CartInterface; +use Magento\Quote\Model\Quote; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -47,6 +49,11 @@ class QuoteCreate implements PaypalExpressQuoteCreateInterface */ private $quoteService; + /** + * @var Quote|CartInterface + */ + private Quote|CartInterface $quote; + /** * @param QuoteCreateResponseInterfaceFactory $responseFactory * @param QuoteService $quoteService @@ -85,7 +92,8 @@ public function execute( } catch (\Throwable $th) { $this->logger->addError(sprintf( '[CREATE_QUOTE - PayPal Express] | [Model] | [%s:%s] - Create Quote | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); throw new PaypalExpressException(__("Failed to add address quote"), 1, $th); diff --git a/Model/PaypalStateCodes.php b/Model/PaypalStateCodes.php index 5088f191a..aeb04563a 100644 --- a/Model/PaypalStateCodes.php +++ b/Model/PaypalStateCodes.php @@ -29,7 +29,7 @@ class PaypalStateCodes * * @var array */ - private array $_codes = [ + private array $codes = [ 'CA' => [ 'AB' => ['Alberta'], 'BC' => ['British Columbia'], @@ -583,14 +583,14 @@ class PaypalStateCodes */ public function getValuesFromCodes(string $countryCode = null, string $stateCode = null) { - // We need a countryCode + stateCode and for it to exist in _codes - if (!$countryCode || !$stateCode || !isset($this->_codes[$countryCode])) { + // We need a countryCode + stateCode and for it to exist in codes + if (!$countryCode || !$stateCode || !isset($this->codes[$countryCode])) { return false; } - // If statecode is both given and exists in _codes, return its array value - if (isset($this->_codes[$countryCode][$stateCode])) { - return $this->_codes[$countryCode][$stateCode]; + // If statecode is both given and exists in codes, return its array value + if (isset($this->codes[$countryCode][$stateCode])) { + return $this->codes[$countryCode][$stateCode]; } // Nothing found, return false instead @@ -606,13 +606,13 @@ public function getValuesFromCodes(string $countryCode = null, string $stateCode */ public function getCodeFromValue(string $countryCode = null, string $value = null) { - // We need a countryCode + value and for it to exist in _codes - if (!$countryCode || !$value || !isset($this->_codes[$countryCode])) { + // We need a countryCode + value and for it to exist in codes + if (!$countryCode || !$value || !isset($this->codes[$countryCode])) { return false; } // Loop through and do an in_array search (some state codes have multiple names) - foreach ($this->_codes[$countryCode] as $stateCode => $stateValues) { + foreach ($this->codes[$countryCode] as $stateCode => $stateValues) { if (in_array($value, $stateValues)) { // As soon as we find one, return the code return $stateCode; @@ -632,11 +632,11 @@ public function getCodeFromValue(string $countryCode = null, string $value = nul public function getCodes($countryCode = null) { if (!$countryCode) { - return $this->_codes; + return $this->codes; } - if (isset($this->_codes[$countryCode])) { - return $this->_codes[$countryCode]; + if (isset($this->codes[$countryCode])) { + return $this->codes[$countryCode]; } // Nothing found based on countryCode, but it was given, return false instead diff --git a/Model/Push/AfterpayProcessor.php b/Model/Push/AfterpayProcessor.php index 1de3157a4..7e177cf47 100644 --- a/Model/Push/AfterpayProcessor.php +++ b/Model/Push/AfterpayProcessor.php @@ -64,8 +64,17 @@ public function __construct( Account $configAccount, Afterpay20 $afterpayConfig ) { - parent::__construct($orderRequestService, $pushTransactionType, $logger, $helper, $transaction, - $groupTransaction, $buckarooStatusCode, $orderStatusFactory, $configAccount); + parent::__construct( + $orderRequestService, + $pushTransactionType, + $logger, + $helper, + $transaction, + $groupTransaction, + $buckarooStatusCode, + $orderStatusFactory, + $configAccount + ); $this->afterpayConfig = $afterpayConfig; } @@ -86,4 +95,4 @@ protected function invoiceShouldBeSaved(array &$paymentDetails): bool } return true; } -} \ No newline at end of file +} diff --git a/Model/Push/CancelAuthorizeProcessor.php b/Model/Push/CancelAuthorizeProcessor.php index 1849c5652..06d645170 100644 --- a/Model/Push/CancelAuthorizeProcessor.php +++ b/Model/Push/CancelAuthorizeProcessor.php @@ -19,7 +19,8 @@ public function processPush(PushRequestInterface $pushRequest): bool } catch (\Exception $e) { $this->logger->addError(sprintf( '[PUSH_CANCEL_AUTHORIZE] | [Webapi] | [%s:%s] - cancelled order authorization | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getLogMessage() )); } @@ -27,9 +28,10 @@ public function processPush(PushRequestInterface $pushRequest): bool $this->logger->addDebug(sprintf( '[PUSH_CANCEL_AUTHORIZE] | [Webapi] | [%s:%s] - Order autorize has been canceld,' . ' trying to update payment transactions', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, )); return true; } -} \ No newline at end of file +} diff --git a/Model/Push/CreditManagmentProcessor.php b/Model/Push/CreditManagmentProcessor.php index 26f5044a1..2b47776da 100644 --- a/Model/Push/CreditManagmentProcessor.php +++ b/Model/Push/CreditManagmentProcessor.php @@ -28,7 +28,6 @@ public function processPush(PushRequestInterface $pushRequest): bool return true; } return false; - } /** @@ -97,4 +96,4 @@ private function sendCm3ConfirmationMail(): void $this->orderRequestService->sendOrderEmail($this->order); } } -} \ No newline at end of file +} diff --git a/Model/Push/DefaultProcessor.php b/Model/Push/DefaultProcessor.php index 1f32c719c..1bb4ff6fa 100644 --- a/Model/Push/DefaultProcessor.php +++ b/Model/Push/DefaultProcessor.php @@ -344,7 +344,8 @@ protected function receivePushCheckDuplicates(int $receivedStatusCode = null, st $this->logger->addDebug(sprintf( '[PUSH] | [Webapi] | [%s:%s] - Check for duplicate transaction pushes | order: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export([ 'receivedTrxStatuses' => $receivedTrxStatuses, 'receivedStatusCode' => $receivedStatusCode @@ -353,7 +354,6 @@ protected function receivePushCheckDuplicates(int $receivedStatusCode = null, st if ($receivedTrxStatuses && is_array($receivedTrxStatuses) - && !empty($trxId) && isset($receivedTrxStatuses[$trxId]) && ($receivedTrxStatuses[$trxId] == $receivedStatusCode) ) { @@ -400,7 +400,8 @@ protected function setReceivedTransactionStatuses(): void } $receivedTxStatuses = $this->payment->getAdditionalInformation( - self::BUCKAROO_RECEIVED_TRANSACTIONS_STATUSES) ?? []; + self::BUCKAROO_RECEIVED_TRANSACTIONS_STATUSES + ) ?? []; $receivedTxStatuses[$txId] = $statusCode; $this->payment->setAdditionalInformation(self::BUCKAROO_RECEIVED_TRANSACTIONS_STATUSES, $receivedTxStatuses); @@ -428,7 +429,8 @@ protected function canUpdateOrderStatus(): bool $currentStateAndStatus = [$this->order->getState(), $this->order->getStatus()]; $this->logger->addDebug(sprintf( '[PUSH] | [Webapi] | [%s:%s] - Checks if the order can be updated | currentStateAndStatus: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($currentStateAndStatus, true) )); @@ -450,7 +452,8 @@ protected function canUpdateOrderStatus(): bool ) { $this->logger->addDebug(sprintf( '[PUSH] | [Webapi] | [%s:%s] - Resetting from CANCELED to STATE_NEW/PENDING', - __METHOD__, __LINE__ + __METHOD__, + __LINE__ )); $this->order->setState(Order::STATE_NEW); @@ -657,7 +660,6 @@ protected function processPushByStatus(): bool $this->orderRequestService->setOrderNotificationNote($statusMessage); return true; - } /** @@ -685,7 +687,8 @@ public function processSucceededPush(string $newStatus, string $message): bool { $this->logger->addDebug(sprintf( '[PUSH] | [Webapi] | [%s:%s] - Process the successful push response from Buckaroo | newStatus: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($newStatus, true) )); @@ -751,7 +754,8 @@ private function processSucceededPushAuthorization(): void ) { $this->logger->addDebug(sprintf( '[PUSH] | [Webapi] | [%s:%s] - Process succeeded push authorization | paymentMethod: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($this->payment->getMethod(), true) )); $this->order->setState(Order::STATE_PROCESSING); @@ -788,7 +792,8 @@ protected function sendOrderEmail(): void ) { $this->logger->addDebug(sprintf( '[PUSH] | [Webapi] | [%s:%s] - Send Order Email | orderConfirmationEmail: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($this->configAccount->getOrderConfirmationEmail($store), true) )); @@ -941,7 +946,8 @@ public function processFailedPush(string $newStatus, string $message): bool { $this->logger->addDebug(sprintf( '[PUSH] | [Webapi] | [%s:%s] - Process the failed push response from Buckaroo | newStatus: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($newStatus, true) )); @@ -971,7 +977,8 @@ public function processFailedPush(string $newStatus, string $message): bool if ($buckarooCancelOnFailed && $this->order->canCancel()) { $this->logger->addDebug(sprintf( '[PUSH] | [Webapi] | [%s:%s] - Process the failed push response from Buckaroo. Cancel Order: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $message )); @@ -996,7 +1003,8 @@ public function processFailedPush(string $newStatus, string $message): bool } catch (\Throwable $th) { $this->logger->addError(sprintf( '[PUSH] | [Webapi] | [%s:%s] - Process failed push from Buckaroo. Cancel Order| [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); } @@ -1084,4 +1092,4 @@ protected function invoiceShouldBeSaved(array &$paymentDetails): bool { return true; } -} \ No newline at end of file +} diff --git a/Model/Push/GroupTransactionPushProcessor.php b/Model/Push/GroupTransactionPushProcessor.php index e8e2527c4..7af5d9b59 100644 --- a/Model/Push/GroupTransactionPushProcessor.php +++ b/Model/Push/GroupTransactionPushProcessor.php @@ -139,7 +139,7 @@ public function processPush(PushRequestInterface $pushRequest): bool return true; } - if($this->isCanceledGroupTransaction()) { + if ($this->isCanceledGroupTransaction()) { $this->cancelGroupTransactionOrder(); return true; } @@ -205,7 +205,8 @@ protected function handleGroupTransactionFailed() } catch (\Throwable $th) { $this->logger->addError(sprintf( '[SDK] | [Adapter] | [%s:%s] - Handle push group transaction fail | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); } @@ -336,4 +337,4 @@ private function savePartGroupTransaction() } } } -} \ No newline at end of file +} diff --git a/Model/Push/KlarnaKpProcessor.php b/Model/Push/KlarnaKpProcessor.php index 14c6a7e9d..f5c45296e 100644 --- a/Model/Push/KlarnaKpProcessor.php +++ b/Model/Push/KlarnaKpProcessor.php @@ -64,8 +64,17 @@ public function __construct( Account $configAccount, Klarnakp $klarnakpConfig ) { - parent::__construct($orderRequestService, $pushTransactionType, $logger, $helper, $transaction, - $groupTransaction, $buckarooStatusCode, $orderStatusFactory, $configAccount); + parent::__construct( + $orderRequestService, + $pushTransactionType, + $logger, + $helper, + $transaction, + $groupTransaction, + $buckarooStatusCode, + $orderStatusFactory, + $configAccount + ); $this->klarnakpConfig = $klarnakpConfig; } @@ -141,4 +150,4 @@ protected function invoiceShouldBeSaved(array &$paymentDetails): bool return true; } -} \ No newline at end of file +} diff --git a/Model/Push/KlarnaProcessor.php b/Model/Push/KlarnaProcessor.php index e2399f8f9..08b57e673 100644 --- a/Model/Push/KlarnaProcessor.php +++ b/Model/Push/KlarnaProcessor.php @@ -47,4 +47,4 @@ protected function invoiceShouldBeSaved(array &$paymentDetails): bool return true; } -} \ No newline at end of file +} diff --git a/Model/Push/LockedPushProcessor.php b/Model/Push/LockedPushProcessor.php index 197118c62..4749e44cc 100644 --- a/Model/Push/LockedPushProcessor.php +++ b/Model/Push/LockedPushProcessor.php @@ -72,10 +72,18 @@ public function __construct( Account $configAccount, LockManagerInterface $lockManager ) { - parent::__construct($orderRequestService, $pushTransactionType, $logger, $helper, $transaction, - $groupTransaction, $buckarooStatusCode, $orderStatusFactory, $configAccount); + parent::__construct( + $orderRequestService, + $pushTransactionType, + $logger, + $helper, + $transaction, + $groupTransaction, + $buckarooStatusCode, + $orderStatusFactory, + $configAccount + ); $this->lockManager = $lockManager; - } /** @@ -140,4 +148,4 @@ protected function stopLockedPush(string $lockName): void ); } } -} \ No newline at end of file +} diff --git a/Model/Push/PayPerEmailProcessor.php b/Model/Push/PayPerEmailProcessor.php index 51e3cc9b1..30c80d933 100644 --- a/Model/Push/PayPerEmailProcessor.php +++ b/Model/Push/PayPerEmailProcessor.php @@ -85,10 +85,19 @@ public function __construct( LockManagerInterface $lockManager, PayPerEmail $configPayPerEmail ) { - parent::__construct($orderRequestService, $pushTransactionType, $logger, $helper, $transaction, - $groupTransaction, $buckarooStatusCode, $orderStatusFactory, $configAccount, $lockManager); + parent::__construct( + $orderRequestService, + $pushTransactionType, + $logger, + $helper, + $transaction, + $groupTransaction, + $buckarooStatusCode, + $orderStatusFactory, + $configAccount, + $lockManager + ); $this->configPayPerEmail = $configPayPerEmail; - } /** @@ -131,7 +140,8 @@ public function processPush(PushRequestInterface $pushRequest): bool if ($isDifferentPaymentMethod && $this->configPayPerEmail->isEnabledB2B()) { $this->logger->addDebug(sprintf( '[PUSH - PayPerEmail] | [Webapi] | [%s:%s] - Update Order State | currentState: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $this->order->getState() )); if ($this->order->getState() === Order::STATE_COMPLETE) { @@ -261,7 +271,6 @@ private function setPaymentMethodIfDifferent(): bool if (!empty($this->pushRequest->getTransactionMethod()) && $status == 'BUCKAROO_MAGENTO2_STATUSCODE_SUCCESS' && $this->pushRequest->getTransactionMethod() != 'payperemail') { - $transactionMethod = strtolower($this->pushRequest->getTransactionMethod()); $this->payment->setAdditionalInformation('isPayPerEmail', $transactionMethod); @@ -322,7 +331,8 @@ public function isPayPerEmailB2BModePush(): bool && $this->configPayPerEmail->isEnabledB2B()) { $this->logger->addDebug(sprintf( '[PUSH - PayPerEmail] | [Webapi] | [%s:%s] - The transaction is PayPerEmail B2B', - __METHOD__, __LINE__ + __METHOD__, + __LINE__ )); $this->isPayPerEmailB2BModePushInitial = true; } @@ -355,7 +365,8 @@ protected function getNewStatus() $this->logger->addDebug(sprintf( '[PUSH - PayPerEmail] | [Webapi] | [%s:%s] - Get New Status | newStatus: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($newStatus, true) )); @@ -364,7 +375,8 @@ protected function getNewStatus() $newStatus = $this->configAccount->getOrderStatusSuccess(); $this->logger->addDebug(sprintf( '[PUSH - PayPerEmail] | [Webapi] | [%s:%s] - Get New Status | newStatus: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export([$this->pushTransactionType->getStatusKey(), $newStatus], true) )); } @@ -413,7 +425,7 @@ protected function getPaymentDetails($message) /** * @param array $paymentDetails * @return bool - * @throws \Exception + * @throws \Exception */ protected function invoiceShouldBeSaved(array &$paymentDetails): bool { @@ -437,4 +449,4 @@ protected function invoiceShouldBeSaved(array &$paymentDetails): bool } return true; } -} \ No newline at end of file +} diff --git a/Model/Push/PaypalProcessor.php b/Model/Push/PaypalProcessor.php index a58435853..77ef27de1 100644 --- a/Model/Push/PaypalProcessor.php +++ b/Model/Push/PaypalProcessor.php @@ -63,10 +63,18 @@ public function __construct( Account $configAccount, PaypalConfig $paypalConfig ) { - parent::__construct($orderRequestService, $pushTransactionType, $logger, $helper, $transaction, - $groupTransaction, $buckarooStatusCode, $orderStatusFactory, $configAccount); + parent::__construct( + $orderRequestService, + $pushTransactionType, + $logger, + $helper, + $transaction, + $groupTransaction, + $buckarooStatusCode, + $orderStatusFactory, + $configAccount + ); $this->paypalConfig = $paypalConfig; - } /** @@ -88,10 +96,11 @@ protected function getNewStatus() $this->logger->addDebug(sprintf( '[PUSH - PayPerEmail] | [Webapi] | [%s:%s] - Get New Status | newStatus: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($newStatus, true) )); return $newStatus; } -} \ No newline at end of file +} diff --git a/Model/Push/PushProcessorsFactory.php b/Model/Push/PushProcessorsFactory.php index c5f03b23b..d057fadad 100644 --- a/Model/Push/PushProcessorsFactory.php +++ b/Model/Push/PushProcessorsFactory.php @@ -88,7 +88,6 @@ public function get(?PushTransactionType $pushTransactionType): ?PushProcessorIn } $this->pushProcessor = $this->objectManager->get($pushProcessorClass); - } return $this->pushProcessor; } @@ -141,4 +140,4 @@ private function getPushProcessorClass(?PushTransactionType $pushTransactionType return $pushProcessorClass; } -} \ No newline at end of file +} diff --git a/Model/Push/PushTransactionType.php b/Model/Push/PushTransactionType.php index 0d7986b9a..509419d6a 100644 --- a/Model/Push/PushTransactionType.php +++ b/Model/Push/PushTransactionType.php @@ -23,7 +23,6 @@ use Buckaroo\Magento2\Api\PushRequestInterface; use Buckaroo\Magento2\Model\BuckarooStatusCode; -use Buckaroo\Magento2\Service\Push\OrderRequestService; use Magento\Sales\Model\Order; /** @@ -102,11 +101,6 @@ class PushTransactionType */ private Order $order; - /** - * @var OrderRequestService - */ - private OrderRequestService $orderRequestService; - /** * @var BuckarooStatusCode */ @@ -459,4 +453,4 @@ public function setIsFromPayPerEmail(bool $isFromPayPerEmail): void { $this->isFromPayPerEmail = $isFromPayPerEmail; } -} \ No newline at end of file +} diff --git a/Model/Push/RefundProcessor.php b/Model/Push/RefundProcessor.php index 259a3a89a..fd630da45 100644 --- a/Model/Push/RefundProcessor.php +++ b/Model/Push/RefundProcessor.php @@ -69,8 +69,17 @@ public function __construct( Account $configAccount, RefundPush $refundPush ) { - parent::__construct($orderRequestService, $pushTransactionType, $logger, $helper, $transaction, - $groupTransaction, $buckarooStatusCode,$orderStatusFactory, $configAccount); + parent::__construct( + $orderRequestService, + $pushTransactionType, + $logger, + $helper, + $transaction, + $groupTransaction, + $buckarooStatusCode, + $orderStatusFactory, + $configAccount + ); $this->refundPush = $refundPush; } @@ -97,8 +106,10 @@ public function processPush(PushRequestInterface $pushRequest): bool return true; } else { throw new BuckarooException( - __('Refund failed ! Status : %1 and the order does not contain an invoice', - $this->pushTransactionType->getStatusKey()) + __( + 'Refund failed ! Status : %1 and the order does not contain an invoice', + $this->pushTransactionType->getStatusKey() + ) ); } } @@ -133,4 +144,4 @@ private function skipPendingRefundPush(PushRequestInterface $pushRequest): bool return true; } -} \ No newline at end of file +} diff --git a/Model/Push/TransferProcessor.php b/Model/Push/TransferProcessor.php index 354ca88a7..7bac71eda 100644 --- a/Model/Push/TransferProcessor.php +++ b/Model/Push/TransferProcessor.php @@ -55,7 +55,8 @@ protected function invoiceShouldBeSaved(array &$paymentDetails): bool $this->logger->addDebug(sprintf( '[PUSH - Transfer] | [Webapi] | [%s:%s] - Update totals by amount from request | order: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export([ 'orderId' => $this->order->getId(), 'totalDue' => $this->order->getTotalDue(), @@ -100,4 +101,4 @@ protected function invoiceShouldBeSaved(array &$paymentDetails): bool return $saveInvoice; } -} \ No newline at end of file +} diff --git a/Model/Refund/Push.php b/Model/Refund/Push.php index 55ee36ec4..4e59babd0 100644 --- a/Model/Refund/Push.php +++ b/Model/Refund/Push.php @@ -135,7 +135,8 @@ public function receiveRefundPush(PushRequestInterface $postData, bool $signatur $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - Trying to refund order out of paymentplaza | orderId: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $this->order->getId() )); @@ -143,7 +144,8 @@ public function receiveRefundPush(PushRequestInterface $postData, bool $signatur $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - Refund order failed - ' . 'the configuration is set not to accept refunds out of Payment Plaza | orderId: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $this->order->getId() )); throw new BuckarooException(__('Buckaroo refund is disabled')); @@ -152,7 +154,8 @@ public function receiveRefundPush(PushRequestInterface $postData, bool $signatur if (!$signatureValidation && !$this->order->canCreditmemo()) { $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - Refund order failed - validation incorrect | signature: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export([ 'signature' => $signatureValidation, 'canOrderCredit' => $this->order->canCreditmemo() @@ -169,7 +172,8 @@ public function receiveRefundPush(PushRequestInterface $postData, bool $signatur if (count($creditmemosByTransactionId) > 0) { $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - The transaction has already been refunded', - __METHOD__, __LINE__ + __METHOD__, + __LINE__ )); return false; } @@ -178,7 +182,8 @@ public function receiveRefundPush(PushRequestInterface $postData, bool $signatur $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - Order successful refunded | creditmemo: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $creditmemo ? 'success' : 'false' )); @@ -210,7 +215,8 @@ public function createCreditmemo(): bool if (!$creditmemo->isValidGrandTotal()) { $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - The credit memo\'s total must be positive', - __METHOD__, __LINE__ + __METHOD__, + __LINE__ )); throw new LocalizedException( __('The credit memo\'s total must be positive.') @@ -229,7 +235,8 @@ public function createCreditmemo(): bool $this->logger->addError(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - Failed to create the creditmemo' . 'method saveCreditmemo return value: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, print_r($creditmemo, true) )); @@ -240,7 +247,8 @@ public function createCreditmemo(): bool } catch (LocalizedException $e) { $this->logger->addError(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - Buckaroo failed to create the credit memo\'s | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getLogMessage() )); } @@ -267,7 +275,8 @@ public function getCreditmemoData(): array $adjustment = $this->getAdjustmentRefundData(); $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - This is an adjustment refund of %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $totalAmountToRefund )); $data['shipping_amount'] = '0'; @@ -278,7 +287,8 @@ public function getCreditmemoData(): array } else { $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - With this refund of %s the grand total will be refunded', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $this->creditAmount )); $data['shipping_amount'] = $this->caluclateShippingCostToRefund(); @@ -290,7 +300,8 @@ public function getCreditmemoData(): array $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - The credit memo data | data: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, print_r($data, true) )); @@ -359,7 +370,8 @@ public function getCreditmemoDataItems(): array $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - Total items to be refunded: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, print_r($items, true) )); @@ -445,7 +457,8 @@ public function calculateRemainder() $this->logger->addDebug(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - Calculate the remainder | totals: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export([ 'totalAmountToRefund' => $this->totalAmountToRefund(), 'orderBaseGrandTotal' => $this->order->getBaseGrandTotal(), @@ -487,7 +500,8 @@ public function initCreditmemo(array $creditData) } catch (LocalizedException $e) { $this->logger->addError(sprintf( '[PUSH_REFUND] | [Webapi] | [%s:%s] - Buckaroo can not initialize the credit memo\'s by order: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getLogMessage() )); } diff --git a/Model/RequestPush/AbstractPushRequest.php b/Model/RequestPush/AbstractPushRequest.php index 72484ac04..6f70624a6 100644 --- a/Model/RequestPush/AbstractPushRequest.php +++ b/Model/RequestPush/AbstractPushRequest.php @@ -23,6 +23,16 @@ class AbstractPushRequest { + /** + * @var array + */ + protected array $request = []; + + /** + * @var array + */ + protected array $originalRequest; + /** * Check if methods was called with specific numbers of arguments * @@ -126,4 +136,20 @@ public function hasPostData(string $name, $value): bool return false; } + + /** + * Get property from additional information + * + * @param string $propertyName + * @return string|null + */ + public function getAdditionalInformation(string $propertyName): ?string + { + $propertyName = 'add_' . strtolower($propertyName); + if (isset($this->request[$propertyName])) { + return $this->request[$propertyName]; + } + + return null; + } } diff --git a/Model/RequestPush/HttppostPushRequest.php b/Model/RequestPush/HttppostPushRequest.php index f17c48d88..681b62006 100644 --- a/Model/RequestPush/HttppostPushRequest.php +++ b/Model/RequestPush/HttppostPushRequest.php @@ -39,16 +39,6 @@ */ class HttppostPushRequest extends AbstractPushRequest implements PushRequestInterface { - /** - * @var array - */ - private array $request = []; - - /** - * @var array - */ - private array $originalRequest; - /** * @var ValidatorPush $validator */ @@ -259,19 +249,6 @@ public function getTransactions(): ?string return $this->request['brq_transactions'] ?? null; } - /** - * @inheritdoc - */ - public function getAdditionalInformation(string $propertyName): ?string - { - $propertyName = 'add_' . strtolower($propertyName); - if (isset($this->request[$propertyName])) { - return $this->request[$propertyName]; - } - - return null; - } - /** * @inheritdoc */ diff --git a/Model/RequestPush/JsonPushRequest.php b/Model/RequestPush/JsonPushRequest.php index 4f0851f37..2982de7fc 100644 --- a/Model/RequestPush/JsonPushRequest.php +++ b/Model/RequestPush/JsonPushRequest.php @@ -40,16 +40,6 @@ */ class JsonPushRequest extends AbstractPushRequest implements PushRequestInterface { - /** - * @var array - */ - private array $request = []; - - /** - * @var array - */ - private array $originalRequest; - /** * @var Validator $validator */ diff --git a/Model/RequestPush/RequestPushFactory.php b/Model/RequestPush/RequestPushFactory.php index 29e7ad21e..c26e00c34 100644 --- a/Model/RequestPush/RequestPushFactory.php +++ b/Model/RequestPush/RequestPushFactory.php @@ -69,7 +69,8 @@ public function create(): PushRequestInterface if (strpos($this->request->getContentType(), 'application/json') !== false) { $this->logger->addDebug(sprintf( '[PUSH] | [Factory] | [%s:%s] - Create Json Request Object | request: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($this->request->getRequestData(), true) )); @@ -81,14 +82,16 @@ public function create(): PushRequestInterface } catch (\Exception $exception) { $this->logger->addError(sprintf( '[PUSH] | [Factory] | [%s:%s] - Create Json Request Object | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $exception->getMessage() )); } $this->logger->addDebug(sprintf( '[PUSH] | [Factory] | [%s:%s] - Create HTTP Post Request Object | request: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($this->request->getRequestData(), true) )); diff --git a/Model/ResourceModel/Giftcard.php b/Model/ResourceModel/Giftcard.php index cf83ba36b..289aba52c 100644 --- a/Model/ResourceModel/Giftcard.php +++ b/Model/ResourceModel/Giftcard.php @@ -26,17 +26,7 @@ class Giftcard extends AbstractDb { /** - * @var string - */ - protected $_eventPrefix = 'buckaroo_magento2_giftcard_resource'; - - /** - * @var string - */ - protected $_eventObject = 'resource'; - - /** - * Model Initialization + * Define resource model * * @return void */ diff --git a/Model/ResourceModel/Giftcard/Collection.php b/Model/ResourceModel/Giftcard/Collection.php index 6bfe679c7..c54fed752 100644 --- a/Model/ResourceModel/Giftcard/Collection.php +++ b/Model/ResourceModel/Giftcard/Collection.php @@ -20,7 +20,9 @@ namespace Buckaroo\Magento2\Model\ResourceModel\Giftcard; -class Collection extends \Magento\Sales\Model\ResourceModel\Collection\AbstractCollection +use Magento\Sales\Model\ResourceModel\Collection\AbstractCollection; + +class Collection extends AbstractCollection { /** * @var string diff --git a/Model/ResourceModel/GroupTransaction.php b/Model/ResourceModel/GroupTransaction.php index cd5c3e87e..913305d52 100644 --- a/Model/ResourceModel/GroupTransaction.php +++ b/Model/ResourceModel/GroupTransaction.php @@ -26,21 +26,7 @@ class GroupTransaction extends AbstractDb { /** - * Event prefix - * - * @var string - */ - protected $_eventPrefix = 'buckaroo_magento2_group_transaction_resource'; - - /** - * Event object - * - * @var string - */ - protected $_eventObject = 'resource'; - - /** - * Model Initialization + * Define resource model * * @return void */ diff --git a/Model/ResourceModel/Invoice.php b/Model/ResourceModel/Invoice.php index daccdb8a1..4282a3726 100644 --- a/Model/ResourceModel/Invoice.php +++ b/Model/ResourceModel/Invoice.php @@ -25,10 +25,13 @@ class Invoice extends AbstractDb { - // @codingStandardsIgnoreLine + /** + * Define resource model + * + * @return void + */ protected function _construct() { - // @codingStandardsIgnoreLine $this->_init( 'buckaroo_magento2_invoice', 'entity_id' diff --git a/Model/ResourceModel/Invoice/Collection.php b/Model/ResourceModel/Invoice/Collection.php index cd198c359..6b8cb587e 100644 --- a/Model/ResourceModel/Invoice/Collection.php +++ b/Model/ResourceModel/Invoice/Collection.php @@ -27,19 +27,29 @@ class Collection extends AbstractCollection /** * @var string */ - // @codingStandardsIgnoreLine protected $_idFieldName = 'entity_id'; /** + * Event prefix + * * @var string */ - // @codingStandardsIgnoreLine protected $_eventPrefix = 'buckaroo_magento2_invoice_collection'; - // @codingStandardsIgnoreLine + /** + * Event object + * + * @var string + */ + protected $_eventObject = 'buckaroo_invoice_collection'; + + /** + * Model initialization + * + * @return void + */ protected function _construct() { - // @codingStandardsIgnoreLine $this->_init( 'Buckaroo\Magento2\Model\Invoice', 'Buckaroo\Magento2\Model\ResourceModel\Invoice' diff --git a/Model/ResourceModel/Log/Collection.php b/Model/ResourceModel/Log/Collection.php index a20c337b6..da209a60f 100644 --- a/Model/ResourceModel/Log/Collection.php +++ b/Model/ResourceModel/Log/Collection.php @@ -21,7 +21,9 @@ namespace Buckaroo\Magento2\Model\ResourceModel\Log; -class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection +use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; + +class Collection extends AbstractCollection { /** * @var string diff --git a/Model/ResourceModel/Order/Handler/State.php b/Model/ResourceModel/Order/Handler/State.php index 51ef841ce..aeae5caeb 100644 --- a/Model/ResourceModel/Order/Handler/State.php +++ b/Model/ResourceModel/Order/Handler/State.php @@ -74,7 +74,8 @@ public function check(Order $order): State ) { $this->logger->addDebug(sprintf( '[ORDER_STATUS] | [Handler] | [%s:%s] - Skip update order status for PayPerEmail | order: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $order->getId() )); return $this; diff --git a/Model/Service/Order.php b/Model/Service/Order.php index c12f7b51e..ac367e626 100644 --- a/Model/Service/Order.php +++ b/Model/Service/Order.php @@ -176,7 +176,8 @@ protected function cancelExpiredTransferOrdersPerStore(StoreInterface $store) $this->logger->addDebug(sprintf( '[CANCEL_ORDER - Transfer] | [Service] | [%s:%s] - Cancel Expired Transfer Orders Per Store |' . 'storeId:%s | dueDays: %s | orderCollectionCount: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($store->getId(), true), var_export($dueDays, true), var_export($orderCollection->count(), true) @@ -256,7 +257,8 @@ protected function cancelExpiredPPEOrdersPerStore(StoreInterface $store) $this->logger->addDebug(sprintf( '[CANCEL_ORDER - PayPerEmail] | [Service] | [%s:%s] - Cancel Expired PayPerEmail Orders |' . 'storeId:%s | dueDays: %s | orderCollectionCount: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($store->getId(), true), var_export($dueDays, true), var_export($orderCollection->count(), true) @@ -286,12 +288,13 @@ protected function cancelExpiredPPEOrdersPerStore(StoreInterface $store) public function cancel(\Magento\Sales\Model\Order $order, ?int $statusCode) { $paymentMethodCode = $order->getPayment()->getMethod(); - $paymentMethodName = str_replace('buckaroo_magento2_', '',$paymentMethodCode); + $paymentMethodName = str_replace('buckaroo_magento2_', '', $paymentMethodCode); $this->logger->addDebug(sprintf( '[CANCEL_ORDER - %s] | [Service] | [%s:%s] - Cancel Order | orderIncrementId: %s', $paymentMethodName, - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($order->getIncrementId(), true) )); @@ -299,7 +302,8 @@ public function cancel(\Magento\Sales\Model\Order $order, ?int $statusCode) $this->logger->addDebug(sprintf( '[CANCEL_ORDER - %s] | [Service] | [%s:%s] - Cancel Order - already canceled', $paymentMethodName, - __METHOD__, __LINE__ + __METHOD__, + __LINE__ )); return true; } @@ -310,8 +314,7 @@ public function cancel(\Magento\Sales\Model\Order $order, ?int $statusCode) return true; } - if ($order->canCancel() || $paymentMethodName == 'payperemail') - { + if ($order->canCancel() || $paymentMethodName == 'payperemail') { if ($paymentMethodName == 'klarnakp') { $methodInstanceClass = get_class($order->getPayment()->getMethodInstance()); $methodInstanceClass::$requestOnVoid = false; @@ -324,7 +327,8 @@ public function cancel(\Magento\Sales\Model\Order $order, ?int $statusCode) $this->logger->addDebug(sprintf( '[CANCEL_ORDER - %s] | [Service] | [%s:%s] - Cancel Order - set status to: %s', $paymentMethodName, - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $failedStatus )); diff --git a/Model/Service/QuoteAddressService.php b/Model/Service/QuoteAddressService.php index 59feb18f6..e20d27a25 100644 --- a/Model/Service/QuoteAddressService.php +++ b/Model/Service/QuoteAddressService.php @@ -158,7 +158,8 @@ public function setShippingAddress(Quote &$quote, array $data): bool { $this->logger->addDebug(sprintf( '[SET_SHIPPING_ADDRESS] | [Service] | [%s:%s] - Set Shipping Address | data: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($data, true) )); @@ -218,7 +219,8 @@ protected function setCommonAddressProceed($errors, string $addressType): bool { $this->logger->addDebug(sprintf( '[SET_SHIPPING_ADDRESS] | [Service] | [%s:%s] - Set Shipping Address | errors: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($errors, true) )); @@ -294,7 +296,8 @@ public function assignAddressToQuote(AddressInterface $shippingAddress, Quote $c } catch (\Exception $e) { $this->logger->addError(sprintf( '[SET_SHIPPING_ADDRESS] | [Service] | [%s:%s] - Set Shipping Address | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); throw new ExpressMethodsException('Assign Shipping Address to Quote failed.'); diff --git a/Model/Service/QuoteService.php b/Model/Service/QuoteService.php index 8c520cdd3..9284c7461 100644 --- a/Model/Service/QuoteService.php +++ b/Model/Service/QuoteService.php @@ -172,7 +172,8 @@ public function createQuote(array $formData): Quote } catch (\Throwable $th) { $this->logger->addError(sprintf( '[CREATE_QUOTE] | [Service] | [%s:%s] - Create quote if in product page | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); throw new QuoteException(__("Failed to create quote"), 1, $th); diff --git a/Model/Service/ShippingMethodsService.php b/Model/Service/ShippingMethodsService.php index 4ce60012d..02d8f54c8 100644 --- a/Model/Service/ShippingMethodsService.php +++ b/Model/Service/ShippingMethodsService.php @@ -69,7 +69,6 @@ public function getAvailableShippingMethods(Quote $quote, AddressInterface $addr $shippingMethod = array_shift($shippingMethods); $address->setShippingMethod($shippingMethod->getCarrierCode() . '_' . $shippingMethod->getMethodCode()); - } $address->setCollectShippingRates(true); diff --git a/Model/Total/Creditmemo/BuckarooFee.php b/Model/Total/Creditmemo/BuckarooFee.php index 040849810..df196adda 100644 --- a/Model/Total/Creditmemo/BuckarooFee.php +++ b/Model/Total/Creditmemo/BuckarooFee.php @@ -63,8 +63,7 @@ public function collect(Creditmemo $creditmemo): BuckarooFee $refundItem = $this->request->getPost('creditmemo'); - if ( - $salesModel->getBaseBuckarooFee() + if ($salesModel->getBaseBuckarooFee() && $order->getBaseBuckarooFeeInvoiced() > $order->getBaseBuckarooFeeRefunded() ) { $baseBuckarooFee = $salesModel->getBaseBuckarooFee(); diff --git a/Model/Voucher/ApplyVoucher.php b/Model/Voucher/ApplyVoucher.php index e44a15fa7..2ab20dbca 100644 --- a/Model/Voucher/ApplyVoucher.php +++ b/Model/Voucher/ApplyVoucher.php @@ -125,6 +125,8 @@ public function apply(string $voucherCode): PayResponseInterface $this->logger->addDebug((string)$th); $this->renderException('Unknown buckaroo error has occurred'); } + + return $this->payResponseFactory->create(); } /** diff --git a/Model/Voucher/ApplyVoucherRequestInterface.php b/Model/Voucher/ApplyVoucherRequestInterface.php index 5f5a803d4..61aa78329 100644 --- a/Model/Voucher/ApplyVoucherRequestInterface.php +++ b/Model/Voucher/ApplyVoucherRequestInterface.php @@ -34,10 +34,10 @@ interface ApplyVoucherRequestInterface public function setVoucherCode(string $voucherCode): ApplyVoucherRequestInterface; /** - * Set quote - * - * @param CartInterface $quote - * @return ApplyVoucherRequestInterface - */ + * Set quote + * + * @param CartInterface $quote + * @return ApplyVoucherRequestInterface + */ public function setQuote(CartInterface $quote): ApplyVoucherRequestInterface; } diff --git a/Observer/GroupTransactionRegister.php b/Observer/GroupTransactionRegister.php index da9c237db..51f16e903 100644 --- a/Observer/GroupTransactionRegister.php +++ b/Observer/GroupTransactionRegister.php @@ -99,7 +99,8 @@ public function execute(Observer $observer) foreach ($items as $item) { $this->logger->addDebug(sprintf( '[GROUP_TRANSACTION] | [Observer] | [%s:%s] - Set Order Total Paid | orderTotalPaid: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export([$order->getTotalPaid(), $item['amount']], true) )); $totalPaid = $order->getTotalPaid() + $item['amount']; diff --git a/Observer/HandleFailedQuoteOrder.php b/Observer/HandleFailedQuoteOrder.php index 06ddda4be..d18b7e004 100644 --- a/Observer/HandleFailedQuoteOrder.php +++ b/Observer/HandleFailedQuoteOrder.php @@ -99,7 +99,8 @@ public function execute(Observer $observer) } catch (\Exception $e) { $this->logger->addError(sprintf( '[CANCEL_ORDER] | [Observer] | [%s:%s] - Error when adding order comment | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); } @@ -108,7 +109,8 @@ public function execute(Observer $observer) try { $this->logger->addDebug(sprintf( '[CANCEL_ORDER] | [Observer] | [%s:%s] - Cancel order for failed quote-to-order | order: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $order->getId() )); if ($this->moduleManager->isEnabled('Magento_Inventory')) { @@ -118,7 +120,8 @@ public function execute(Observer $observer) } catch (\Exception $e) { $this->logger->addError(sprintf( '[CANCEL_ORDER] | [Observer] | [%s:%s] - Error when canceling order | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); } diff --git a/Observer/OrderCancelAfter.php b/Observer/OrderCancelAfter.php index 9f55c97b4..31a55aa26 100644 --- a/Observer/OrderCancelAfter.php +++ b/Observer/OrderCancelAfter.php @@ -110,7 +110,8 @@ public function execute(Observer $observer) $this->logger->addDebug(sprintf( '[CANCEL_ORDER - PayPerEmail] | [Observer] | [%s:%s] - Send Cancel Order Request for PayPerEmail' . 'to payment engine | originalKey: %s | order: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export([$originalKey], true), $order->getId() )); @@ -118,7 +119,8 @@ public function execute(Observer $observer) } catch (\Exception $e) { $this->logger->addError(sprintf( '[CANCEL_ORDER - PayPerEmail] | [Observer] | [%s:%s] - Send Cancel Request for PPE | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); } diff --git a/Observer/RestoreQuote.php b/Observer/RestoreQuote.php index f4a2714e0..fff8f9c6d 100644 --- a/Observer/RestoreQuote.php +++ b/Observer/RestoreQuote.php @@ -132,8 +132,7 @@ public function execute(Observer $observer): void } } - if ( - ( + if (( $this->checkoutSession->getRestoreQuoteLastOrder() && $lastRealOrder->getData('state') === 'new' && $lastRealOrder->getData('status') === 'pending' && @@ -143,7 +142,8 @@ public function execute(Observer $observer): void $this->logger->addDebug(sprintf( '[RESTORE_QUOTE] | [Observer] | [%s:%s] - Restore Quote | ' . 'lastRealOrder: %s | previousOrderId: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $lastRealOrder->getIncrementId(), $previousOrderId )); @@ -157,7 +157,8 @@ public function execute(Observer $observer): void $this->logger->addDebug(sprintf( '[RESTORE_QUOTE] | [Observer] | [%s:%s] - Restore Skipped: ' . 'Quote restoration was not carried out. | lastRealOrder: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $lastRealOrder->getIncrementId(), )); @@ -204,7 +205,8 @@ public function rollbackPartialPayment(string $incrementId, $payment): void } catch (\Throwable $th) { $this->logger->addError(sprintf( '[RESTORE_QUOTE] | [Observer] | [%s:%s] - Rollback Partial Payment | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $th->getMessage() )); } diff --git a/Observer/SalesOrderShipmentAfter.php b/Observer/SalesOrderShipmentAfter.php index 1dd101f52..8d0b25bfe 100644 --- a/Observer/SalesOrderShipmentAfter.php +++ b/Observer/SalesOrderShipmentAfter.php @@ -156,7 +156,8 @@ private function createInvoice(Order $order, Shipment $shipment, bool $allowPart { $this->logger->addDebug(sprintf( '[CREATE_INVOICE] | [Observer] | [%s:%s] - Create invoice after shipment | orderDiscountAmount: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($order->getDiscountAmount(), true) )); @@ -186,7 +187,8 @@ private function createInvoice(Order $order, Shipment $shipment, bool $allowPart $this->logger->addDebug(sprintf( '[CREATE_INVOICE] | [Observer] | [%s:%s] - Create invoice after shipment | orderStatus: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($order->getStatus(), true) )); @@ -197,11 +199,11 @@ private function createInvoice(Order $order, Shipment $shipment, bool $allowPart $order->addStatusHistoryComment($description, false); $order->save(); } - } catch (\Exception $e) { $this->logger->addDebug(sprintf( '[CREATE_INVOICE] | [Observer] | [%s:%s] - Create invoice after shipment | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); $order->addStatusHistoryComment('Exception message: ' . $e->getMessage(), false); diff --git a/Observer/SendOrderConfirmation.php b/Observer/SendOrderConfirmation.php index 8980f8b39..23f1d3eed 100644 --- a/Observer/SendOrderConfirmation.php +++ b/Observer/SendOrderConfirmation.php @@ -98,7 +98,8 @@ public function execute(Observer $observer) ) { $this->logger->addDebug(sprintf( '[SEND_MAIL] | [Observer] | [%s:%s] - Send order confirmation on email | order: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $order->getId() )); $this->orderSender->send($order, true); diff --git a/Plugin/CommandInterface.php b/Plugin/CommandInterface.php index 7e1c2e2e5..501a5ec49 100644 --- a/Plugin/CommandInterface.php +++ b/Plugin/CommandInterface.php @@ -103,7 +103,8 @@ public function aroundExecute( $this->logger->addDebug(sprintf( '[UPDATE_STATUS] | [Plugin] | [%s:%s] - Update order state and status |' . ' paymentMethod: %s | paymentAction: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $paymentCode, $paymentAction )); @@ -116,7 +117,8 @@ public function aroundExecute( $this->logger->addDebug(sprintf( '[UPDATE_STATUS] | [Plugin] | [%s:%s] - Skip Update order state and status |' . ' paymentMethod: %s | paymentAction: %s, orderStatus: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $paymentCode, $paymentAction, $orderStatus diff --git a/Plugin/MyParcelNLBuckarooPlugin.php b/Plugin/MyParcelNLBuckarooPlugin.php index 27b852f9c..150262f78 100644 --- a/Plugin/MyParcelNLBuckarooPlugin.php +++ b/Plugin/MyParcelNLBuckarooPlugin.php @@ -78,7 +78,8 @@ public function beforeGetFromDeliveryOptions() if ($jsonDecoded = $this->json->unserialize($result)) { $this->logger->addDebug(sprintf( '[MyParcelNL] | [Plugin] | [%s:%s] - Set Pickup Location | deliveryOptions: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($jsonDecoded, true) )); if (!empty($jsonDecoded['deliveryOptions']) && diff --git a/Plugin/Onepage/Success.php b/Plugin/Onepage/Success.php index 3950789d3..547b1097e 100644 --- a/Plugin/Onepage/Success.php +++ b/Plugin/Onepage/Success.php @@ -80,7 +80,8 @@ public function aroundExecute(ControllerOnePageSuccess $checkoutSuccess, callabl $this->logger->addDebug(sprintf( '[SUCCESS_PAGE] | [Plugin] | [%s:%s] - Redirect to cart | details: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export([ 'orderStatus' => $order->getStatus(), 'isPaymentInTransit' => $this->checkPaymentType->isPaymentInTransit($payment) @@ -99,4 +100,4 @@ public function aroundExecute(ControllerOnePageSuccess $checkoutSuccess, callabl } return $proceed(); } -} \ No newline at end of file +} diff --git a/Plugin/ShippingMethodManagement.php b/Plugin/ShippingMethodManagement.php index 6b821f29e..2e57c9d58 100644 --- a/Plugin/ShippingMethodManagement.php +++ b/Plugin/ShippingMethodManagement.php @@ -104,7 +104,8 @@ public function beforeGet(\Magento\Quote\Model\ShippingMethodManagement $subject $this->logger->addDebug(sprintf( '[SET_SHIPPING] | [Plugin] | [%s:%s] - START - Ensures that the shipping address is loaded ' . ' and shipping rates are collected. | lastRealOrder: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $lastRealOrder->getIncrementId(), )); @@ -120,7 +121,8 @@ public function beforeGet(\Magento\Quote\Model\ShippingMethodManagement $subject $this->logger->addDebug(sprintf( '[SET_SHIPPING] | [Plugin] | [%s:%s] - SET SHIPPING ADDRESS - Ensures that ' . 'the shipping address is loaded. | lastRealOrder: %s | shippingAddressId: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $lastRealOrder->getIncrementId(), $shippingAddress->getAddressId() )); diff --git a/Service/Applepay/Add.php b/Service/Applepay/Add.php index 2472e06da..d5d4962b7 100644 --- a/Service/Applepay/Add.php +++ b/Service/Applepay/Add.php @@ -100,7 +100,8 @@ public function process(array $request) } catch (\Exception $exception) { $this->logger->addError(sprintf( '[ApplePay] | [Controller] | [%s:%s] - Add Product to Cart on Apple Pay | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $exception->getMessage() )); return false; diff --git a/Service/CreditManagement/ServiceParameters/CreateCombinedInvoice.php b/Service/CreditManagement/ServiceParameters/CreateCombinedInvoice.php index d494bbca7..8fe43e23a 100644 --- a/Service/CreditManagement/ServiceParameters/CreateCombinedInvoice.php +++ b/Service/CreditManagement/ServiceParameters/CreateCombinedInvoice.php @@ -23,6 +23,7 @@ use Buckaroo\Magento2\Exception; use Buckaroo\Magento2\Model\ConfigProvider\Method\AbstractConfigProvider; use Buckaroo\Magento2\Model\ConfigProvider\Method\Factory; +use Buckaroo\Magento2\Model\ConfigProvider\Method\PayPerEmail; use Magento\Payment\Model\InfoInterface; use Magento\Sales\Api\Data\OrderPaymentInterface; use Magento\Sales\Model\Order; @@ -183,7 +184,7 @@ private function getAllowedServices($payment): string $allowedServices = $this->appendGiftcards($allowedServices); - if ($payment->getMethod() === PayPerEmail::PAYMENT_METHOD_CODE) { + if ($payment->getMethod() === PayPerEmail::CODE) { return str_replace("p24,", "", $allowedServices); } @@ -221,7 +222,7 @@ private function appendGiftcards(string $allowedServices): string return $allowedServices; } - if(strlen($allowedServices) > 0) { + if (strlen($allowedServices) > 0) { return $allowedServices . "," . $activeGiftcardIssuers; } return $activeGiftcardIssuers; diff --git a/Service/CustomerAttributes.php b/Service/CustomerAttributes.php index a712bed4e..42fe4bdb5 100644 --- a/Service/CustomerAttributes.php +++ b/Service/CustomerAttributes.php @@ -26,4 +26,4 @@ public function setAttribute(int $customerId, string $attribute, string $value) $customer->setCustomAttribute($attribute, $value); $this->customerRepository->save($customer); } -} \ No newline at end of file +} diff --git a/Service/Formatter/Address/PhoneFormatter.php b/Service/Formatter/Address/PhoneFormatter.php index b7d6faf09..f289ef760 100644 --- a/Service/Formatter/Address/PhoneFormatter.php +++ b/Service/Formatter/Address/PhoneFormatter.php @@ -79,7 +79,8 @@ public function format(string $phoneNumber, string $country): array { $this->logger->addDebug(sprintf( '[PHONE_FORMATER] | [Service] | [%s:%s] - Format phone number by country | request: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export(['phoneNumber' => $phoneNumber, 'country' => $country], true) )); @@ -99,7 +100,8 @@ public function format(string $phoneNumber, string $country): array $this->logger->addDebug(sprintf( '[PHONE_FORMATER] | [Service] | [%s:%s] - Format phone number by country | response: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($return, true) )); diff --git a/Service/Ideal/IssuersService.php b/Service/Ideal/IssuersService.php index c27f48236..f2cde35ee 100644 --- a/Service/Ideal/IssuersService.php +++ b/Service/Ideal/IssuersService.php @@ -17,7 +17,7 @@ class IssuersService /** * @var int */ - protected CONST CACHE_LIFETIME_SECONDS = 86400; //24hours + protected const CACHE_LIFETIME_SECONDS = 86400; //24hours /** * @var CacheInterface @@ -86,7 +86,7 @@ public function __construct( public function get(): array { $issuers = $this->getCachedIssuers(); - if($issuers === null) { + if ($issuers === null) { return $this->updateCacheIssuers(); } return $issuers; @@ -103,7 +103,7 @@ private function updateCacheIssuers(): array $this->buckarooAdapter->getIdealIssuers() ); - if(count($retrievedIssuers)) { + if (count($retrievedIssuers)) { $this->cacheIssuers($retrievedIssuers); return $retrievedIssuers; } @@ -135,15 +135,14 @@ private function cacheIssuers(array $issuers): void private function getCachedIssuers(): ?array { $cacheData = $this->cache->load(self::CACHE_KEY); - if($cacheData === null || $cacheData === false) { + if ($cacheData === null || $cacheData === false) { return null; } $issuers = $this->serializer->unserialize($cacheData); - if(!is_array($issuers)) { + if (!is_array($issuers)) { return null; } return $issuers; - } /** @@ -155,10 +154,9 @@ private function getCachedIssuers(): ?array private function addLogos(array $issuers): array { return array_map( - function($issuer) { + function ($issuer) { $logo = null; - if( - isset($issuer['id']) && + if (isset($issuer['id']) && isset(self::ISSUERS_IMAGES[$issuer['id']]) ) { $name = self::ISSUERS_IMAGES[$issuer['id']]; diff --git a/Service/LogoService.php b/Service/LogoService.php index 9460f9b4a..88751b347 100644 --- a/Service/LogoService.php +++ b/Service/LogoService.php @@ -134,7 +134,8 @@ public function getCreditcard(string $code): string return $this->assetRepo->getUrl("Buckaroo_Magento2::images/creditcards/{$code}.svg"); } - public function getAssetUrl(string $path): string { + public function getAssetUrl(string $path): string + { return $this->assetRepo->getUrl($path); } } diff --git a/Service/Push/OrderRequestService.php b/Service/Push/OrderRequestService.php index e188658e5..86f95d33b 100644 --- a/Service/Push/OrderRequestService.php +++ b/Service/Push/OrderRequestService.php @@ -109,7 +109,8 @@ public function getOrderByRequest(?PushRequestInterface $pushRequest = null) if (!$this->order->getId()) { $this->logger->addDebug(sprintf( '[ORDER] | [Service] | [%s:%s] - Order could not be loaded by Invoice Number or Order Number', - __METHOD__, __LINE__ + __METHOD__, + __LINE__ )); // Try to get order by transaction id on payment. $this->order = $this->getOrderByTransactionKey($pushRequest); @@ -201,7 +202,8 @@ public function setOrderNotificationNote($message): void } catch (\Exception $e) { $this->logger->addError(sprintf( '[ORDER] | [Service] | [%s:%s] - Set Order Notification Note Failed | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getLogMessage() )); } @@ -227,7 +229,8 @@ public function updateOrderStatus( ): void { $this->logger->addDebug(sprintf( '[ORDER] | [Service] | [%s:%s] - Updates the order state and add a comment | data: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export([ 'orderState' => $orderState, 'newStatus' => $newStatus, @@ -282,7 +285,8 @@ public function sendInvoiceEmail(Invoice $invoice, bool $forceSyncMode = false): return $this->invoiceSender->send($invoice, $forceSyncMode); } - public function updateTotalOnOrder($order) { + public function updateTotalOnOrder($order) + { try { $connection = $this->resourceConnection->getConnection(); @@ -301,7 +305,6 @@ public function updateTotalOnOrder($order) { } catch (\Exception $exception) { return false; } - } /** @@ -327,4 +330,4 @@ public function loadOrder() $brqOrderId = $this->getOrderByRequest()->getIncrementId(); $this->order->loadByIncrementId((string)$brqOrderId); } -} \ No newline at end of file +} diff --git a/Service/Sales/Quote/Recreate.php b/Service/Sales/Quote/Recreate.php index a4b81160d..90a843a48 100644 --- a/Service/Sales/Quote/Recreate.php +++ b/Service/Sales/Quote/Recreate.php @@ -75,7 +75,8 @@ public function recreate(Quote $quote) } catch (NoSuchEntityException $e) { $this->logger->addError(sprintf( '[RECREATE_QUOTE] | [Service] | [%s:%s] - Reintialize the quote | [ERROR]: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $e->getMessage() )); } diff --git a/Service/SpamLimitService.php b/Service/SpamLimitService.php index 4e8b6f0f1..7514dfbaf 100644 --- a/Service/SpamLimitService.php +++ b/Service/SpamLimitService.php @@ -60,11 +60,8 @@ public function updateRateLimiterCount(MethodInterface $paymentMethodInstance) } $method = $paymentMethodInstance->getCode(); - try { - $quoteId = $this->getQuote()->getId(); - } catch (NoSuchEntityException $e) { - } catch (LocalizedException $e) { - } + $quoteId = $this->getQuote()->getId(); + $storage = $this->getPaymentAttemptsStorage(); if (!isset($storage[$quoteId])) { $storage[$quoteId] = [$method => 0]; @@ -193,4 +190,4 @@ public function setMaxAttemptsFlags($payment, string $message) $this->checkoutSession->setBuckarooFailedMaxAttempts(true); $payment->setAdditionalInformation(BuckarooAdapter::PAYMENT_ATTEMPTS_REACHED_MESSAGE, $message); } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Request/AbstractDataBuilderTest.php b/Test/Unit/Gateway/Request/AbstractDataBuilderTest.php index f7a0c7ea9..3202f7602 100644 --- a/Test/Unit/Gateway/Request/AbstractDataBuilderTest.php +++ b/Test/Unit/Gateway/Request/AbstractDataBuilderTest.php @@ -90,4 +90,4 @@ protected function getPaymentDOMock() return $paymentDOMock; } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Request/BasicParameter/AdditionalParametersDataBuilderTest.php b/Test/Unit/Gateway/Request/BasicParameter/AdditionalParametersDataBuilderTest.php index 654ef6d47..a53689d63 100644 --- a/Test/Unit/Gateway/Request/BasicParameter/AdditionalParametersDataBuilderTest.php +++ b/Test/Unit/Gateway/Request/BasicParameter/AdditionalParametersDataBuilderTest.php @@ -71,4 +71,4 @@ public function testGetSetAdditionalParameter(): void $this->assertEquals($value, $this->dataBuilder->getAdditionalParameter($key)); } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Request/BasicParameter/AmountCreditDataBuilderTest.php b/Test/Unit/Gateway/Request/BasicParameter/AmountCreditDataBuilderTest.php index 510a5266f..53882a8be 100644 --- a/Test/Unit/Gateway/Request/BasicParameter/AmountCreditDataBuilderTest.php +++ b/Test/Unit/Gateway/Request/BasicParameter/AmountCreditDataBuilderTest.php @@ -102,6 +102,4 @@ public function buildDataProvider(): array [0.01, 0.01, 0.01], ]; } - - } diff --git a/Test/Unit/Gateway/Request/BasicParameter/ClientIPDataBuilderTest.php b/Test/Unit/Gateway/Request/BasicParameter/ClientIPDataBuilderTest.php index b8a898644..2b4c8b804 100644 --- a/Test/Unit/Gateway/Request/BasicParameter/ClientIPDataBuilderTest.php +++ b/Test/Unit/Gateway/Request/BasicParameter/ClientIPDataBuilderTest.php @@ -175,4 +175,4 @@ private function invokeIsIpPrivateMethod(ClientIPDataBuilder $clientIPDataBuilde return $method->invokeArgs($clientIPDataBuilder, [$ip]); } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Request/BasicParameter/DescriptionDataBuilderTest.php b/Test/Unit/Gateway/Request/BasicParameter/DescriptionDataBuilderTest.php index 878d26f07..91240b74a 100644 --- a/Test/Unit/Gateway/Request/BasicParameter/DescriptionDataBuilderTest.php +++ b/Test/Unit/Gateway/Request/BasicParameter/DescriptionDataBuilderTest.php @@ -71,4 +71,4 @@ public function testBuild(): void $result = $this->descriptionDataBuilder->build(['payment' => $this->getPaymentDOMock()]); $this->assertEquals(['description' => 'Sample description'], $result); } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Request/BasicParameter/InvoiceDataBuilderTest.php b/Test/Unit/Gateway/Request/BasicParameter/InvoiceDataBuilderTest.php index e38e6e250..c237f8878 100644 --- a/Test/Unit/Gateway/Request/BasicParameter/InvoiceDataBuilderTest.php +++ b/Test/Unit/Gateway/Request/BasicParameter/InvoiceDataBuilderTest.php @@ -50,4 +50,4 @@ public function testBuild(): void 'order' => '100000001' ], $result); } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Request/BasicParameter/OrderNumberDataBuilderTest.php b/Test/Unit/Gateway/Request/BasicParameter/OrderNumberDataBuilderTest.php index 8577c0c97..4b7e768b0 100644 --- a/Test/Unit/Gateway/Request/BasicParameter/OrderNumberDataBuilderTest.php +++ b/Test/Unit/Gateway/Request/BasicParameter/OrderNumberDataBuilderTest.php @@ -68,4 +68,4 @@ public function testBuild(): void $result = $this->orderNumberDataBuilder->build(['payment' => $paymentDO]); $this->assertEquals(['order' => '100000001'], $result); } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Request/BasicParameter/PaymentMethodDataBuilderTest.php b/Test/Unit/Gateway/Request/BasicParameter/PaymentMethodDataBuilderTest.php index fcb864497..133b5b89a 100644 --- a/Test/Unit/Gateway/Request/BasicParameter/PaymentMethodDataBuilderTest.php +++ b/Test/Unit/Gateway/Request/BasicParameter/PaymentMethodDataBuilderTest.php @@ -72,6 +72,4 @@ public function buildDataProvider(): array ], ]; } - - -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Request/BasicParameter/PushUrlDataBuilderTest.php b/Test/Unit/Gateway/Request/BasicParameter/PushUrlDataBuilderTest.php index 546d672b1..10ff3e8a3 100644 --- a/Test/Unit/Gateway/Request/BasicParameter/PushUrlDataBuilderTest.php +++ b/Test/Unit/Gateway/Request/BasicParameter/PushUrlDataBuilderTest.php @@ -73,4 +73,4 @@ public function testBuild(): void $result ); } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Request/BasicParameter/SaveOrderBeforeDataBuilderTest.php b/Test/Unit/Gateway/Request/BasicParameter/SaveOrderBeforeDataBuilderTest.php index a7ce72765..d3bdd108f 100644 --- a/Test/Unit/Gateway/Request/BasicParameter/SaveOrderBeforeDataBuilderTest.php +++ b/Test/Unit/Gateway/Request/BasicParameter/SaveOrderBeforeDataBuilderTest.php @@ -27,6 +27,11 @@ class SaveOrderBeforeDataBuilderTest extends AbstractDataBuilderTest { + /** + * @var SaveOrderBeforeDataBuilder + */ + private SaveOrderBeforeDataBuilder $dataBuilder; + /** * @var Account|MockObject */ @@ -75,4 +80,4 @@ public function testBuild(): void $this->assertEquals([], $result); } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Response/AbstractResponseHandlerTest.php b/Test/Unit/Gateway/Response/AbstractResponseHandlerTest.php index 51abbd0c2..13ffdf8f2 100644 --- a/Test/Unit/Gateway/Response/AbstractResponseHandlerTest.php +++ b/Test/Unit/Gateway/Response/AbstractResponseHandlerTest.php @@ -114,4 +114,4 @@ protected function getTransactionResponse(): array { return ['object' => $this->transactionResponse]; } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Response/CreditManagementOrderHandlerTest.php b/Test/Unit/Gateway/Response/CreditManagementOrderHandlerTest.php index c8644e654..684d3b5c3 100644 --- a/Test/Unit/Gateway/Response/CreditManagementOrderHandlerTest.php +++ b/Test/Unit/Gateway/Response/CreditManagementOrderHandlerTest.php @@ -90,4 +90,3 @@ public function testGetInvoiceKey(): void $this->assertEquals($service['Parameters'][0]['Value'], $result); } } - diff --git a/Test/Unit/Gateway/Response/ReservationNumberHandlerTest.php b/Test/Unit/Gateway/Response/ReservationNumberHandlerTest.php index d2573c878..6a6465f92 100644 --- a/Test/Unit/Gateway/Response/ReservationNumberHandlerTest.php +++ b/Test/Unit/Gateway/Response/ReservationNumberHandlerTest.php @@ -118,4 +118,4 @@ public function reservationNumberDataProvider(): array ] ]; } -} \ No newline at end of file +} diff --git a/Test/Unit/Gateway/Validator/IssuerValidatorTest.php b/Test/Unit/Gateway/Validator/IssuerValidatorTest.php index 61739d5fe..c50453aaf 100644 --- a/Test/Unit/Gateway/Validator/IssuerValidatorTest.php +++ b/Test/Unit/Gateway/Validator/IssuerValidatorTest.php @@ -5,24 +5,26 @@ use Buckaroo\Magento2\Gateway\Validator\IssuerValidator; use Buckaroo\Magento2\Model\ConfigProvider\Method\AbstractConfigProvider; use Buckaroo\Magento2\Model\ConfigProvider\Method\Factory as ConfigProviderMethodFactory; +use Magento\Framework\App\Request\Http as HttpRequest; use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; use Magento\Payment\Gateway\Validator\ResultInterface; use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; use Magento\Payment\Model\InfoInterface; use Magento\Payment\Model\MethodInterface; use PHPUnit\Framework\TestCase; +use Magento\Framework\Serialize\Serializer\Json; class IssuerValidatorTest extends TestCase { /** - * @var ResultInterfaceFactory|MockObject + * @var IssuerValidator */ - private $resultFactoryMock; - + private IssuerValidator $validator; + /** - * @var IssuerValidator + * @var ResultInterfaceFactory|MockObject */ - private $validator; + private $resultFactoryMock; /** * @var ConfigProviderMethodFactory|MockObject @@ -39,9 +41,19 @@ protected function setUp(): void ->disableOriginalConstructor() ->getMock(); + $httpRequest = $this->getMockBuilder(HttpRequest::class) + ->disableOriginalConstructor() + ->getMock(); + + $jsonSerializer = $this->getMockBuilder(Json::class) + ->disableOriginalConstructor() + ->getMock(); + $this->validator = new IssuerValidator( $this->resultFactoryMock, - $this->configProviderFactory + $this->configProviderFactory, + $httpRequest, + $jsonSerializer ); } diff --git a/Test/Unit/Model/ConfigProvider/Method/CreditcardsTest.php b/Test/Unit/Model/ConfigProvider/Method/CreditcardsTest.php index 6d2a594d8..7b9afa4b9 100644 --- a/Test/Unit/Model/ConfigProvider/Method/CreditcardsTest.php +++ b/Test/Unit/Model/ConfigProvider/Method/CreditcardsTest.php @@ -71,8 +71,8 @@ public function testGetConfig($expected) $this->getPaymentMethodConfigPath(Creditcards::CODE, AbstractConfigProvider::XPATH_ALLOWED_CURRENCIES), ScopeInterface::SCOPE_STORE, null - ] - [Creditcards::XPATH_ALLOWED_CURRENCIES, ScopeInterface::SCOPE_STORE, null] + ], + [AbstractConfigProvider::XPATH_ALLOWED_CURRENCIES, ScopeInterface::SCOPE_STORE, null] ) ->willReturnOnConsecutiveCalls('', '1', 'EUR'); diff --git a/Test/Unit/Model/PushTest.php b/Test/Unit/Model/PushTest.php index 4eb36c801..2dd71fb26 100644 --- a/Test/Unit/Model/PushTest.php +++ b/Test/Unit/Model/PushTest.php @@ -20,7 +20,9 @@ */ namespace Buckaroo\Magento2\Test\Unit\Model; +use Buckaroo\Magento2\Logging\Log; use Buckaroo\Magento2\Model\ConfigProvider\Method\Giftcards; +use Buckaroo\Magento2\Model\Push\PushTransactionType; use Magento\Directory\Model\Currency; use Magento\Framework\Webapi\Rest\Request; use Magento\Payment\Model\MethodInterface; @@ -250,17 +252,17 @@ public function getTransactionTypeProvider() 'invoice type' => [ ['brq_invoicekey' => 'send key', 'brq_schemekey' => 'scheme key'], 'saved key', - Push::BUCK_PUSH_TYPE_INVOICE + PushTransactionType::BUCK_PUSH_TYPE_INVOICE ], 'datarequest type' => [ ['brq_datarequest' => 'request push'], null, - Push::BUCK_PUSH_TYPE_DATAREQUEST + PushTransactionType::BUCK_PUSH_TYPE_DATAREQUEST ], 'transaction type' => [ [], null, - Push::BUCK_PUSH_TYPE_TRANSACTION + PushTransactionType::BUCK_PUSH_TYPE_TRANSACTION ], ]; } diff --git a/ViewModel/PpeCustomerDetails.php b/ViewModel/PpeCustomerDetails.php index ecfc1f4c6..e8bec9a3a 100644 --- a/ViewModel/PpeCustomerDetails.php +++ b/ViewModel/PpeCustomerDetails.php @@ -60,7 +60,8 @@ public function getPPeCustomerDetails(): ?array { $this->logger->addDebug(sprintf( '[Helper - PayPerEmail] | [Helper] | [%s:%s] - Get PPE Customer details | originalRequest: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, var_export($this->request->getParams(), true) )); if (($customerId = $this->request->getParam('customer_id')) && ((int)$customerId > 0)) { @@ -78,7 +79,8 @@ public function getPPeCustomerDetails(): ?array } $this->logger->addDebug(sprintf( '[Helper - PayPerEmail] | [Helper] | [%s:%s] - Get PPE Customer details | customerEmail: %s', - __METHOD__, __LINE__, + __METHOD__, + __LINE__, $customer->getEmail() )); $this->staticCache['getPPeCustomerDetails'] = [ @@ -115,4 +117,4 @@ public function getPPeCustomerDetails(): ?array return $this->staticCache['getPPeCustomerDetails'] ?? null; } -} \ No newline at end of file +} diff --git a/etc/acl.xml b/etc/acl.xml index 60f9e31ff..33b9cde86 100644 --- a/etc/acl.xml +++ b/etc/acl.xml @@ -31,11 +31,11 @@ - - - - - + + + + + diff --git a/etc/adminhtml/routes.xml b/etc/adminhtml/routes.xml index 7201e3dec..9a34f12ea 100644 --- a/etc/adminhtml/routes.xml +++ b/etc/adminhtml/routes.xml @@ -26,7 +26,7 @@ - - + + diff --git a/etc/adminhtml/system/payment_methods/creditcard.xml b/etc/adminhtml/system/payment_methods/creditcard.xml index 3575df2e1..30b179e3a 100644 --- a/etc/adminhtml/system/payment_methods/creditcard.xml +++ b/etc/adminhtml/system/payment_methods/creditcard.xml @@ -277,4 +277,4 @@ - \ No newline at end of file + diff --git a/etc/adminhtml/system/payment_methods/klarna.xml b/etc/adminhtml/system/payment_methods/klarna.xml index c77c395e2..fde867e90 100644 --- a/etc/adminhtml/system/payment_methods/klarna.xml +++ b/etc/adminhtml/system/payment_methods/klarna.xml @@ -178,4 +178,4 @@ - \ No newline at end of file + diff --git a/etc/adminhtml/system/payment_methods/klarnain.xml b/etc/adminhtml/system/payment_methods/klarnain.xml index 58c834fb5..28a4bac1d 100644 --- a/etc/adminhtml/system/payment_methods/klarnain.xml +++ b/etc/adminhtml/system/payment_methods/klarnain.xml @@ -179,4 +179,4 @@ - \ No newline at end of file + diff --git a/etc/adminhtml/system/payment_methods/klarnakp.xml b/etc/adminhtml/system/payment_methods/klarnakp.xml index d0fa38451..50172b1d6 100644 --- a/etc/adminhtml/system/payment_methods/klarnakp.xml +++ b/etc/adminhtml/system/payment_methods/klarnakp.xml @@ -190,4 +190,4 @@ - \ No newline at end of file + diff --git a/etc/adminhtml/system/payment_methods/klarnas.xml b/etc/adminhtml/system/payment_methods/klarnas.xml index 1320c089e..624c43b56 100644 --- a/etc/adminhtml/system/payment_methods/klarnas.xml +++ b/etc/adminhtml/system/payment_methods/klarnas.xml @@ -31,4 +31,4 @@ - \ No newline at end of file + diff --git a/etc/di.xml b/etc/di.xml index 875e0ada5..a8f8bdf3a 100644 --- a/etc/di.xml +++ b/etc/di.xml @@ -213,11 +213,11 @@ afterpay Buckaroo\Magento2\Model\ConfigProvider\Method\Afterpay - + afterpay2 Buckaroo\Magento2\Model\ConfigProvider\Method\Afterpay2 - + afterpay20 Buckaroo\Magento2\Model\ConfigProvider\Method\Afterpay20 @@ -437,21 +437,21 @@ - - - - - buckaroo_magento2_log - Buckaroo\Magento2\Model\ResourceModel\Log\Collection - - - - - - Buckaroo\Magento2\Model\ResourceModel\Log\Grid\Collection - - - + + + + + buckaroo_magento2_log + Buckaroo\Magento2\Model\ResourceModel\Log\Collection + + + + + + Buckaroo\Magento2\Model\ResourceModel\Log\Grid\Collection + + + @@ -1923,6 +1923,7 @@ BuckarooOrderRequest Buckaroo\Magento2\Gateway\Request\Capayable\In3V3DataBuilder + Buckaroo\Magento2\Gateway\Request\Capayable\CustomerTypeDataBuilder CustomerCapayableDataBuilder Buckaroo\Magento2\Gateway\Request\Articles\ArticlesDataBuilder diff --git a/view/adminhtml/layout/buckaroo_magento2_log_index.xml b/view/adminhtml/layout/buckaroo_magento2_log_index.xml index ce58021c9..147dec1e1 100644 --- a/view/adminhtml/layout/buckaroo_magento2_log_index.xml +++ b/view/adminhtml/layout/buckaroo_magento2_log_index.xml @@ -1,9 +1,9 @@ - - - - - - + + + + + + diff --git a/view/adminhtml/templates/creditcard_sort_widget.phtml b/view/adminhtml/templates/creditcard_sort_widget.phtml index dbf793236..aea1775c0 100644 --- a/view/adminhtml/templates/creditcard_sort_widget.phtml +++ b/view/adminhtml/templates/creditcard_sort_widget.phtml @@ -116,4 +116,4 @@ \ No newline at end of file +?> diff --git a/view/adminhtml/ui_component/buckaroo_magento2_log_listing.xml b/view/adminhtml/ui_component/buckaroo_magento2_log_listing.xml index 8f7601960..8726cac75 100644 --- a/view/adminhtml/ui_component/buckaroo_magento2_log_listing.xml +++ b/view/adminhtml/ui_component/buckaroo_magento2_log_listing.xml @@ -1,123 +1,123 @@ - - - buckaroo_magento2_log_listing.buckaroo_magento2_log_listing_data_source - - - - buckaroo_magento2_log_columns - - buckaroo_magento2_log_listing.buckaroo_magento2_log_listing_data_source - - - - - - log_id - - - - Buckaroo_Magento2::Log - - - id - log_id - - - - - - true - - - - - - - - - - log_id - - - - - text - asc - - - - - - text - - - - - - text - - - - - - Buckaroo\Magento2\Model\Config\Source\LogLevel - - select - Magento_Ui/js/grid/columns/select - select - asc - 1 - Level - - - - - - - ui/grid/cells/html - Message - - - - text - - - - - - - dateRange - text - Time - 20 - - - - - - text - - - - - - text - - - - - - text - - - - - - text - - - - + + + buckaroo_magento2_log_listing.buckaroo_magento2_log_listing_data_source + + + + buckaroo_magento2_log_columns + + buckaroo_magento2_log_listing.buckaroo_magento2_log_listing_data_source + + + + + + log_id + + + + Buckaroo_Magento2::Log + + + id + log_id + + + + + + true + + + + + + + + + + log_id + + + + + text + asc + + + + + + text + + + + + + text + + + + + + Buckaroo\Magento2\Model\Config\Source\LogLevel + + select + Magento_Ui/js/grid/columns/select + select + asc + 1 + Level + + + + + + + ui/grid/cells/html + Message + + + + text + + + + + + + dateRange + text + Time + 20 + + + + + + text + + + + + + text + + + + + + text + + + + + + text + + + + diff --git a/view/frontend/layout/checkout_index_index.xml b/view/frontend/layout/checkout_index_index.xml index 2f581e14a..ada5a6b91 100644 --- a/view/frontend/layout/checkout_index_index.xml +++ b/view/frontend/layout/checkout_index_index.xml @@ -142,7 +142,7 @@ true - true + true true diff --git a/view/frontend/templates/checkout/cart/paypal-express.phtml b/view/frontend/templates/checkout/cart/paypal-express.phtml index a04185a00..0f68761a2 100644 --- a/view/frontend/templates/checkout/cart/paypal-express.phtml +++ b/view/frontend/templates/checkout/cart/paypal-express.phtml @@ -19,7 +19,7 @@ * @license https://tldrlegal.com/license/mit-license */ ?> -canShowCartButton()) : ?> +canShowCartButton()): ?>
@@ -37,4 +37,4 @@ }); } - \ No newline at end of file + diff --git a/view/frontend/templates/info/payment_method.phtml b/view/frontend/templates/info/payment_method.phtml index 50654028c..1cbbf2f3d 100644 --- a/view/frontend/templates/info/payment_method.phtml +++ b/view/frontend/templates/info/payment_method.phtml @@ -20,7 +20,7 @@ ?> getMethod() instanceof \Magento\Payment\Model\Method\Adapter) { +if ($block->getMethod() instanceof \Magento\Payment\Model\Method\Adapter) { $bpePaymentCode = $block->escapeHtml($block->getMethod()->getCode()); } else { $bpePaymentCode = $block->escapeHtml($block->getMethod()->buckarooPaymentMethodCode); diff --git a/view/frontend/web/js/action/amasty-place-order-mixin.js b/view/frontend/web/js/action/amasty-place-order-mixin.js index 49aa74b50..7f0c98b26 100644 --- a/view/frontend/web/js/action/amasty-place-order-mixin.js +++ b/view/frontend/web/js/action/amasty-place-order-mixin.js @@ -4,36 +4,36 @@ define([ ], function ($, wrapper) { 'use strict'; - let getAmastyPromise = function() { + let getAmastyPromise = function () { let requestDeferred = $.Deferred(); - if(window.checkoutConfig.amOrderAttribute !== undefined) { + if (window.checkoutConfig.amOrderAttribute !== undefined) { require([ 'Amasty_Orderattr/js/model/attribute-sets/payment-attributes', 'Amasty_Orderattr/js/model/validate-and-save' - ], function (attributesForm, validateAndSave) { - requestDeferred.resolve(validateAndSave(attributesForm)); - }) + ], function (attributesForm, validateAndSave) { + requestDeferred.resolve(validateAndSave(attributesForm)); + }) } else { - requestDeferred.resolve($.when()); + requestDeferred.resolve($.when()); } - return requestDeferred.promise().then(function(resp) { - return resp; + return requestDeferred.promise().then(function (resp) { + return resp; }); } return function (placeOrderAction) { return wrapper.wrap(placeOrderAction, function (originalAction, paymentData, redirectOnSuccess, messageContainer) { var result = $.Deferred(); - getAmastyPromise().done( - function() { + getAmastyPromise().done( + function () { $.when( originalAction(paymentData, redirectOnSuccess, messageContainer) ).fail( - function() { + function () { result.reject.apply(this, arguments); } ).done( - function() { + function () { result.resolve.apply(this, arguments); } ); diff --git a/view/frontend/web/js/action/paypal-express.js b/view/frontend/web/js/action/paypal-express.js index 151c1c8b0..312a6aa38 100644 --- a/view/frontend/web/js/action/paypal-express.js +++ b/view/frontend/web/js/action/paypal-express.js @@ -1,138 +1,144 @@ define([], function () { - "use strict"; - let checkoutUrl = "https://checkout.buckaroo.nl"; - let payPalClientId = + "use strict"; + let checkoutUrl = "https://checkout.buckaroo.nl"; + let payPalClientId = "ATv1oKfBmc76Zzl8rAMai_OwpXIp9CsDTMzEceayY7X2Sy8t6bQT2rm7DIC7LYbfkch9m9S3R3amkeyU"; - let buttonStyle = { - color: "gold", - shape: "rect", - }; - let amount = 0.01; - let currency = "EUR"; + let buttonStyle = { + color: "gold", + shape: "rect", + }; + let amount = 0.01; + let currency = "EUR"; /** * Load the paypal sdk */ - const requirePayPal = function (url, callback) { - const e = document.createElement("script"); - e.src = url; - e.setAttribute("data-partner-attribution-id", "NL_BUCKAROO_PPCP"); - e.type = "text/javascript"; - e.addEventListener("load", callback); - document.getElementsByTagName("head")[0].appendChild(e); - }; + const requirePayPal = function (url, callback) { + const e = document.createElement("script"); + e.src = url; + e.setAttribute("data-partner-attribution-id", "NL_BUCKAROO_PPCP"); + e.type = "text/javascript"; + e.addEventListener("load", callback); + document.getElementsByTagName("head")[0].appendChild(e); + }; /** * Set mode test */ - const setTestMode = function () { - checkoutUrl = "https://testcheckout.buckaroo.nl"; - payPalClientId = - "AfHztAEfaf3f76tNy8j_Z86w5y-fGbqbBt04PXppVFtJatje79gVSB27DwBENnyFgfhFvKzgJbegNpHv"; - }; + const setTestMode = function () { + checkoutUrl = "https://testcheckout.buckaroo.nl"; + payPalClientId = + "AfHztAEfaf3f76tNy8j_Z86w5y-fGbqbBt04PXppVFtJatje79gVSB27DwBENnyFgfhFvKzgJbegNpHv"; + }; - const setAmount = function (newAmount) { - amount = newAmount; - }; + const setAmount = function (newAmount) { + amount = newAmount; + }; - const setCurrency = function (newCurrency) { - currency = newCurrency; - }; + const setCurrency = function (newCurrency) { + currency = newCurrency; + }; /** * Initiate de button display */ - const initiate = function (options) { - const style = options.style || {}; - if (options.isTestMode) { - setTestMode(); - } + const initiate = function (options) { + const style = options.style || {}; + if (options.isTestMode) { + setTestMode(); + } - if (options.amount) { - amount = options.amount; - } + if (options.amount) { + amount = options.amount; + } - if (options.currency) { - currency = options.currency; - } + if (options.currency) { + currency = options.currency; + } - requirePayPal( - "https://www.paypal.com/sdk/js?client-id=" + - payPalClientId + - "&merchant-id=" + - options.paypalMerchantId + - "¤cy=" + - currency + - "&disable-funding=credit,card,bancontact,blik,eps,giropay,ideal,mercadopago,mybank,p24,sepa,sofort,venmo&enable-funding=paylater", - function () { - paypal - .Buttons({ - style: Object.assign(buttonStyle, style), - createOrder: function () { - var createOrderUrl = - checkoutUrl + - "/api/paypal/createOrder?buckarooWebsiteKey=" + - options.buckarooWebsiteKey + - "¤cy=" + - currency + - "&initialAmount=" + - amount; - // Optional - Add InvoiceId when available. - if ( - options.invoiceId !== undefined && - options.invoiceId !== null - ) { - createOrderUrl += "&invoiceId=" + options.invoiceId; - } - return fetch(createOrderUrl, { - method: "post", - }) - .then(function (res) { - return res.json(); + requirePayPal( + "https://www.paypal.com/sdk/js?client-id=" + + payPalClientId + + "&merchant-id=" + + options.paypalMerchantId + + "¤cy=" + + currency + + "&disable-funding=credit,card,bancontact,blik,eps,giropay,ideal,mercadopago,mybank,p24,sepa,sofort,venmo&enable-funding=paylater", + function () { + paypal + .Buttons({ + style: Object.assign(buttonStyle, style), + createOrder: function () { + var createOrderUrl = + checkoutUrl + + "/api/paypal/createOrder?buckarooWebsiteKey=" + + options.buckarooWebsiteKey + + "¤cy=" + + currency + + "&initialAmount=" + + amount; + // Optional - Add InvoiceId when available. + if ( + options.invoiceId !== undefined && + options.invoiceId !== null + ) { + createOrderUrl += "&invoiceId=" + options.invoiceId; + } + return fetch(createOrderUrl, { + method: "post", + }) + .then(function (res) { + return res.json(); + }) + .then(function (orderData) { + console.log(orderData); + return orderData.PaypalOrderId; + }); + }, + onApprove: function (data) { + return options.createPaymentHandler(data).then( + function () { + options.onSuccessCallback(); + }, + function (reason) { + if (options.onErrorCallback !== undefined) { + options.onErrorCallback(reason); + } + } + ); + }, + onShippingChange: function (data, actions) { + if (options.onShippingChangeHandler !== undefined) { + return options.onShippingChangeHandler(data, actions); + } + }, + onCancel: function () { + if (options.onCancelCallback !== undefined) { + options.onCancelCallback(); + } + }, + onError: function (reason) { + if (options.onErrorCallback !== undefined) { + options.onErrorCallback(reason); + } + }, + onInit: function () { + if (options.onInitCallback !== undefined) { + options.onInitCallback(); + } + }, + onClick: function () { + if (options.onClickCallback !== undefined) { + options.onClickCallback(); + } + }, }) - .then(function (orderData) { - console.log(orderData); - return orderData.PaypalOrderId; - }); - }, - onApprove: function (data) { - return options.createPaymentHandler(data).then( - function () { - options.onSuccessCallback(); - }, - function (reason) { - if (options.onErrorCallback !== undefined) - options.onErrorCallback(reason); - } - ); - }, - onShippingChange: function (data, actions) { - if (options.onShippingChangeHandler !== undefined) - return options.onShippingChangeHandler(data, actions); - }, - onCancel: function () { - if (options.onCancelCallback !== undefined) - options.onCancelCallback(); - }, - onError: function (reason) { - if (options.onErrorCallback !== undefined) - options.onErrorCallback(reason); - }, - onInit: function () { - if (options.onInitCallback !== undefined) - options.onInitCallback(); - }, - onClick: function () { - if (options.onClickCallback !== undefined) - options.onClickCallback(); - }, - }) - .render(options.containerSelector); - } - ); - }; - return { - initiate, - setAmount, - setCurrency, - }; + .render(options.containerSelector); + } + ); + }; + return { + initiate, + setAmount, + setCurrency, + }; }); diff --git a/view/frontend/web/js/action/place-order.js b/view/frontend/web/js/action/place-order.js index d8e31fe45..f8763b9b4 100644 --- a/view/frontend/web/js/action/place-order.js +++ b/view/frontend/web/js/action/place-order.js @@ -111,8 +111,8 @@ define( title: $t('Error'), content: $t(jsonResponse.limitReachedMessage), buttons: [{ - text: $t('Close'), - class: 'action primary accept', + text: $t('Close'), + class: 'action primary accept', click: function () { this.closeModal(true); } diff --git a/view/frontend/web/js/view/checkout/common.js b/view/frontend/web/js/view/checkout/common.js index d0c0bb9f3..1136a9297 100644 --- a/view/frontend/web/js/view/checkout/common.js +++ b/view/frontend/web/js/view/checkout/common.js @@ -37,24 +37,24 @@ define( window.location.replace(response.RequiredAction.RedirectURL); } }, - getSubtextStyle: function(paymentCode) { + getSubtextStyle: function (paymentCode) { let config = window.checkoutConfig.payment.buckaroo[paymentCode]; - if(config === undefined) { + if (config === undefined) { return; } let subtextColor = config.subtext_color || '#757575'; let subtextStyle = config.subtext_style || 'regular'; let style = { color: subtextColor } - if(subtextStyle == 'bold') { - style.fontWeight = 'bold'; + if (subtextStyle == 'bold') { + style.fontWeight = 'bold'; } - if(subtextStyle == 'italic') { - style.fontStyle = 'italic'; + if (subtextStyle == 'italic') { + style.fontStyle = 'italic'; } return style; - } + } }; } diff --git a/view/frontend/web/js/view/checkout/paypal-express/button.js b/view/frontend/web/js/view/checkout/paypal-express/button.js index 272068af1..23d76f51d 100644 --- a/view/frontend/web/js/view/checkout/paypal-express/button.js +++ b/view/frontend/web/js/view/checkout/paypal-express/button.js @@ -16,7 +16,7 @@ * @copyright Copyright (c) Buckaroo B.V. * @license https://tldrlegal.com/license/mit-license */ - define( +define( [ 'uiComponent', 'buckaroo/paypal-express/pay', diff --git a/view/frontend/web/js/view/checkout/paypal-express/pay.js b/view/frontend/web/js/view/checkout/paypal-express/pay.js index 9441b7756..2ffa3d384 100644 --- a/view/frontend/web/js/view/checkout/paypal-express/pay.js +++ b/view/frontend/web/js/view/checkout/paypal-express/pay.js @@ -17,192 +17,194 @@ * @license https://tldrlegal.com/license/mit-license */ define([ - "jquery", - "ko", - "mage/url", - "Magento_Customer/js/customer-data", - "Buckaroo_Magento2/js/action/paypal-express", - "mage/translate", - , + "jquery", + "ko", + "mage/url", + "Magento_Customer/js/customer-data", + "Buckaroo_Magento2/js/action/paypal-express", + "mage/translate", + , ], function ($, ko, urlBuilder, customerData, sdk, __) { - // 'use strict'; - return { - setConfig(config, page) { - this.page = page; - if (this.page === "cart") { - require(["Magento_Checkout/js/model/quote"], function (quote) { - quote.totals.subscribe((totalData) => { - sdk.setAmount( ( - totalData.grand_total + totalData.tax_amount - ).toFixed(2)); - sdk.setCurrency(totalData.quote_currency_code); - }); - }); - } - this.options = Object.assign( - { - containerSelector: ".buckaroo-paypal-express", - buckarooWebsiteKey: "", - paypalMerchantId: "", - currency: "EUR", - amount: 0.1, - createPaymentHandler: this.createPaymentHandler.bind(this), - onShippingChangeHandler: this.onShippingChangeHandler.bind(this), - onSuccessCallback: this.onSuccessCallback.bind(this), - onErrorCallback: this.onErrorCallback.bind(this), - onCancelCallback: this.onCancelCallback.bind(this), - onInitCallback: this.onInitCallback.bind(this), - onClickCallback: this.onClickCallback.bind(this), + // 'use strict'; + return { + setConfig(config, page) { + this.page = page; + if (this.page === "cart") { + require(["Magento_Checkout/js/model/quote"], function (quote) { + quote.totals.subscribe((totalData) => { + sdk.setAmount(( + totalData.grand_total + totalData.tax_amount + ).toFixed(2)); + sdk.setCurrency(totalData.quote_currency_code); + }); + }); + } + this.options = Object.assign( + { + containerSelector: ".buckaroo-paypal-express", + buckarooWebsiteKey: "", + paypalMerchantId: "", + currency: "EUR", + amount: 0.1, + createPaymentHandler: this.createPaymentHandler.bind(this), + onShippingChangeHandler: this.onShippingChangeHandler.bind(this), + onSuccessCallback: this.onSuccessCallback.bind(this), + onErrorCallback: this.onErrorCallback.bind(this), + onCancelCallback: this.onCancelCallback.bind(this), + onInitCallback: this.onInitCallback.bind(this), + onClickCallback: this.onClickCallback.bind(this), + }, + config + ); }, - config - ); - }, - result: null, + result: null, - cart_id: null, - /** - * Api events - */ - onShippingChangeHandler(data, actions) { - let shipping = this.setShipping(data); - return new Promise((resolve, reject) => { - shipping.then( - (response) => { - if (!response.message) { - this.options.amount = response.value; - this.cart_id = response.cart_id; - actions.order - .patch([ - { - op: "replace", - path: "/purchase_units/@reference_id=='default'/amount", - value: response, - }, - ]) - .then( - (resp) => resolve(resp), - (err) => reject(err) + cart_id: null, + /** + * Api events + */ + onShippingChangeHandler(data, actions) { + let shipping = this.setShipping(data); + return new Promise((resolve, reject) => { + shipping.then( + (response) => { + if (!response.message) { + this.options.amount = response.value; + this.cart_id = response.cart_id; + actions.order + .patch([ + { + op: "replace", + path: "/purchase_units/@reference_id=='default'/amount", + value: response, + }, + ]) + .then( + (resp) => resolve(resp), + (err) => reject(err) + ); + } else { + reject(response.message); + } + }, + () => { + reject(__("Cannot create payment")); + } ); + }); + }, + createPaymentHandler(data) { + return this.createTransaction(data.orderID); + }, + onSuccessCallback() { + if (this.result.message) { + this.displayErrorMessage(message); } else { - reject(response.message); + if (this.result.cart_id && this.result.cart_id.length) { + window.location.replace( + urlBuilder.build("checkout/onepage/success/") + ); + } else { + this.displayErrorMessage(__("Cannot create payment")); + } } - }, - () => { - reject(__("Cannot create payment")); - } - ); - }); - }, - createPaymentHandler(data) { - return this.createTransaction(data.orderID); - }, - onSuccessCallback() { - if (this.result.message) { - this.displayErrorMessage(message); - } else { - if (this.result.cart_id && this.result.cart_id.length) { - window.location.replace( - urlBuilder.build("checkout/onepage/success/") - ); - } else { - this.displayErrorMessage(__("Cannot create payment")); - } - } - }, + }, - onErrorCallback(reason) { - // custom error behavior - this.displayErrorMessage(reason); - }, - onInitCallback() {}, - onCancelCallback() { - this.displayErrorMessage(__("You have canceled the payment request")); - }, - onClickCallback() { - //reset any previous payment response; - this.result = null; - }, - /** - * Init class - */ - init() { - sdk.initiate(this.options); - }, + onErrorCallback(reason) { + // custom error behavior + this.displayErrorMessage(reason); + }, + onInitCallback() { + }, + onCancelCallback() { + this.displayErrorMessage(__("You have canceled the payment request")); + }, + onClickCallback() { + //reset any previous payment response; + this.result = null; + }, + /** + * Init class + */ + init() { + sdk.initiate(this.options); + }, - /** - * Create order and do payment - * @param {string} orderId - * @returns Promise - */ - createTransaction(orderId) { - const cart_id = this.cart_id; - return new Promise((resolve, reject) => { - $.post( - urlBuilder.build( - "rest/default/V1/buckaroo/paypal-express/order/create" - ), - { - paypal_order_id: orderId, - cart_id, - } - ).then( - (response) => { - this.result = response; - resolve(response); - }, - (reason) => reject(reason) - ); - }); - }, + /** + * Create order and do payment + * @param {string} orderId + * @returns Promise + */ + createTransaction(orderId) { + const cart_id = this.cart_id; + return new Promise((resolve, reject) => { + $.post( + urlBuilder.build( + "rest/default/V1/buckaroo/paypal-express/order/create" + ), + { + paypal_order_id: orderId, + cart_id, + } + ).then( + (response) => { + this.result = response; + resolve(response); + }, + (reason) => reject(reason) + ); + }); + }, - /** - * Set shipping on cart and return new total - * @param {Object} data - * @returns - */ - setShipping(data) { - return $.post( - urlBuilder.build( - "rest/default/V1/buckaroo/paypal-express/quote/create" - ), - { - shippingAddress: data.shipping_address, - orderData: this.getOrderData(), - page: this.page, - } - ); - }, - /** - * Get form data for product page to create cart - * @returns - */ - getOrderData() { - let form = $("#product_addtocart_form"); - if (this.page === "product") { - return form.serializeArray(); - } - }, - /** - * Display any validation errors we receive - * @param {string} message - */ - displayErrorMessage(message) { - if (typeof message === "object") { - if (message.responseJSON && message.responseJSON.message) { - message = __(message.responseJSON.message); - } else { - message = __("Cannot create payment"); - } - } - customerData.set("messages", { - messages: [ - { - type: "error", - text: message, - }, - ], - }); - }, - }; + /** + * Set shipping on cart and return new total + * @param {Object} data + * @returns + */ + setShipping(data) { + return $.post( + urlBuilder.build( + "rest/default/V1/buckaroo/paypal-express/quote/create" + ), + { + shippingAddress: data.shipping_address, + orderData: this.getOrderData(), + page: this.page, + } + ); + }, + /** + * Get form data for product page to create cart + * @returns + */ + getOrderData() { + let form = $("#product_addtocart_form"); + if (this.page === "product") { + return form.serializeArray(); + } + }, + /** + * Display any validation errors we receive + * @param {string} message + */ + displayErrorMessage(message) { + if (typeof message === "object") { + if (message.responseJSON && message.responseJSON.message) { + message = __(message.responseJSON.message); + } else { + message = __("Cannot create payment"); + } + } + customerData.set("messages", { + messages: [ + { + type: "error", + text: message, + }, + ], + }); + }, + }; }); + 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 773d956ea..0cd3e167d 100644 --- a/view/frontend/web/js/view/payment/method-renderer/afterpay.js +++ b/view/frontend/web/js/view/payment/method-renderer/afterpay.js @@ -103,15 +103,16 @@ define( value.substr(6, 4), value.substr(3, 2) - 1, value.substr(0, 2), - 0, 0, 0 + 0, + 0, + 0 ); return ~~((Date.now() - birthday) / (31557600000)) >= 18; } } return false; }, - $.mage.__('You should be at least 18 years old.') - ); + $.mage.__('You should be at least 18 years old.')); return Component.extend( { @@ -173,7 +174,7 @@ define( this.billingName = ko.computed( function () { - if(quote.billingAddress() !== null) { + if (quote.billingAddress() !== null) { return quote.billingAddress().firstname + " " + quote.billingAddress().lastname; } }, @@ -182,7 +183,7 @@ define( this.termsUrl = ko.computed( function () { - if(quote.billingAddress() !== null) { + if (quote.billingAddress() !== null) { let newUrl = 'https://www.afterpay.nl/nl/algemeen/betalen-met-afterpay/betalingsvoorwaarden'; if (this.paymentMethod == PAYMENT_METHOD_DIGIACCEPT) { newUrl = this.getDigiacceptUrl(quote.billingAddress().countryId); @@ -208,24 +209,24 @@ define( */ this.bankAccountNumber.extend({ uppercase: true }); - this.dateValidate.subscribe(function() { + this.dateValidate.subscribe(function () { const dobId = 'buckaroo_magento2_afterpay_DoB'; const isValid = $(`#${dobId}`).valid(); let state = this.validationState(); state[dobId] = isValid; this.validationState(state); - }, this); + }, this); this.buttoncheck = ko.computed( function () { const state = this.validationState(); const valid = this.getActiveValidationFields().map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true @@ -248,7 +249,7 @@ define( let fields = [ 'buckaroo_magento2_afterpay_TermsCondition', ]; - if(!this.hasTelephoneNumber()) { + if (!this.hasTelephoneNumber()) { fields.push('buckaroo_magento2_afterpay_Telephone') } @@ -259,9 +260,9 @@ define( ) ) { fields.push('buckaroo_magento2_afterpay_DoB') - if(this.paymentMethod == PAYMENT_METHOD_ACCEPTGIRO) { - fields.push('buckaroo_magento2_afterpay_IBAN') - } + if (this.paymentMethod == PAYMENT_METHOD_ACCEPTGIRO) { + fields.push('buckaroo_magento2_afterpay_IBAN') + } } else { fields = fields.concat( [ @@ -350,7 +351,7 @@ define( } }; }, - getDigiacceptUrl :function(country) { + getDigiacceptUrl :function (country) { var businessMethod = this.getBusinessMethod(); var url = 'https://www.afterpay.nl/nl/algemeen/betalen-met-afterpay/betalingsvoorwaarden'; @@ -369,7 +370,7 @@ define( return url; }, - getBusinessMethod : function() { + getBusinessMethod : function () { var businessMethod = BUSINESS_METHOD_B2C; if (this.businessMethod == BUSINESS_METHOD_B2B diff --git a/view/frontend/web/js/view/payment/method-renderer/afterpay2.js b/view/frontend/web/js/view/payment/method-renderer/afterpay2.js index 44457ae99..27b6583d3 100644 --- a/view/frontend/web/js/view/payment/method-renderer/afterpay2.js +++ b/view/frontend/web/js/view/payment/method-renderer/afterpay2.js @@ -103,15 +103,16 @@ define( value.substr(6, 4), value.substr(3, 2) - 1, value.substr(0, 2), - 0, 0, 0 + 0, + 0, + 0 ); return ~~((Date.now() - birthday) / (31557600000)) >= 18; } } return false; }, - $.mage.__('You should be at least 18 years old.') - ); + $.mage.__('You should be at least 18 years old.')); return Component.extend( { @@ -172,7 +173,7 @@ define( this.billingName = ko.computed( function () { - if(quote.billingAddress() !== null) { + if (quote.billingAddress() !== null) { return quote.billingAddress().firstname + " " + quote.billingAddress().lastname; } }, @@ -181,7 +182,7 @@ define( this.termsUrl = ko.computed( function () { - if(quote.billingAddress() !== null) { + if (quote.billingAddress() !== null) { let newUrl = 'https://www.afterpay.nl/nl/algemeen/betalen-met-afterpay/betalingsvoorwaarden'; if (this.paymentMethod == PAYMENT_METHOD_DIGIACCEPT) { newUrl = this.getDigiacceptUrl(quote.billingAddress().countryId); @@ -207,24 +208,24 @@ define( */ this.bankAccountNumber.extend({ uppercase: true }); - this.dateValidate.subscribe(function() { + this.dateValidate.subscribe(function () { const dobId = 'buckaroo_magento2_afterpay2_DoB'; const isValid = $(`#${dobId}`).valid(); let state = this.validationState(); state[dobId] = isValid; this.validationState(state); - }, this); + }, this); this.buttoncheck = ko.computed( function () { const state = this.validationState(); const valid = this.getActiveValidationFields().map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true @@ -247,7 +248,7 @@ define( let fields = [ 'buckaroo_magento2_afterpay2_TermsCondition', ]; - if(!this.hasTelephoneNumber()) { + if (!this.hasTelephoneNumber()) { fields.push('buckaroo_magento2_afterpay2_Telephone') } @@ -258,9 +259,9 @@ define( ) ) { fields.push('buckaroo_magento2_afterpay2_DoB') - if(this.paymentMethod == PAYMENT_METHOD_ACCEPTGIRO) { - fields.push('buckaroo_magento2_afterpay2_IBAN') - } + if (this.paymentMethod == PAYMENT_METHOD_ACCEPTGIRO) { + fields.push('buckaroo_magento2_afterpay2_IBAN') + } } else { fields = fields.concat( [ @@ -349,7 +350,7 @@ define( } }; }, - getDigiacceptUrl :function(country) { + getDigiacceptUrl :function (country) { var businessMethod = this.getBusinessMethod(); var url = 'https://www.afterpay.nl/nl/algemeen/betalen-met-afterpay/betalingsvoorwaarden'; @@ -368,7 +369,7 @@ define( return url; }, - getBusinessMethod : function() { + getBusinessMethod : function () { var businessMethod = BUSINESS_METHOD_B2C; if (this.businessMethod == BUSINESS_METHOD_B2B diff --git a/view/frontend/web/js/view/payment/method-renderer/afterpay20.js b/view/frontend/web/js/view/payment/method-renderer/afterpay20.js index 1cbe63f96..e0d285686 100644 --- a/view/frontend/web/js/view/payment/method-renderer/afterpay20.js +++ b/view/frontend/web/js/view/payment/method-renderer/afterpay20.js @@ -64,8 +64,7 @@ define( return value.length <= 8; }, - $.mage.__('Invalid COC number') - ); + $.mage.__('Invalid COC number')); $.validator.addMethod('phoneValidation', function (value) { var countryId = quote.billingAddress().countryId; @@ -82,35 +81,34 @@ define( min: 11, max: 14 } - }; - if (!value) { - return false; - } + }; + if (!value) { + return false; + } value = value.replace(/^\+|(00)/, ''); value = value.replace(/\(0\)|\s|-/g, ''); - if (value.match(/\+/)) { - return false; - } + if (value.match(/\+/)) { + return false; + } + + if (value.match(/[^0-9]/)) { + return false; + } - if (value.match(/[^0-9]/)) { + if (lengths.hasOwnProperty(countryId)) { + if (lengths[countryId].min && (value.length < lengths[countryId].min)) { return false; } - - if (lengths.hasOwnProperty(countryId)) { - if (lengths[countryId].min && (value.length < lengths[countryId].min)) { - return false; - } - if (lengths[countryId].max && (value.length > lengths[countryId].max)) { - return false; - } + if (lengths[countryId].max && (value.length > lengths[countryId].max)) { + return false; } + } return true; - }, - $.mage.__('Phone number should be correct.') - ); + }, + $.mage.__('Phone number should be correct.')); $.validator.addMethod('validateAge', function (value) { if (value && (value.length > 0)) { @@ -120,15 +118,16 @@ define( value.substr(6, 4), value.substr(3, 2) - 1, value.substr(0, 2), - 0, 0, 0 + 0, + 0, + 0 ); return ~~((Date.now() - birthday) / (31557600000)) >= 18; } } return false; }, - $.mage.__('You should be at least 18 years old.') - ); + $.mage.__('You should be at least 18 years old.')); return Component.extend( { @@ -184,8 +183,8 @@ define( ); this.activeAddress = ko.computed( - function() { - if(quote.billingAddress()) { + function () { + if (quote.billingAddress()) { return quote.billingAddress(); } return quote.shippingAddress(); @@ -193,14 +192,14 @@ define( ); this.country = ko.computed( - function() { + function () { return this.activeAddress().countryId; }, this ); this.showCOC = ko.computed( - function() { + function () { let shipping = quote.shippingAddress(); let billing = quote.billingAddress(); @@ -218,9 +217,8 @@ define( return (!this.isCustomerLoggedIn() && this.isOsc()) || (this.country() === 'NL' || this.country() === 'BE') || this.phoneValidate() - }, - this - ); + }, + this); this.showNLBEFields = ko.computed( function () { @@ -262,15 +260,15 @@ define( ); this.buttoncheck = ko.computed( - function() { + function () { const state = this.validationState(); const valid = this.getActiveValidationFields().map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true @@ -280,26 +278,26 @@ define( this ) - this.activeAddress.subscribe(function(address) { - if(address.phone) { + this.activeAddress.subscribe(function (address) { + if (address.phone) { this.phoneValidate(address.phone) } }, this) - this.dateValidate.subscribe(function() { - this.validateField('DoB'); + this.dateValidate.subscribe(function () { + this.validateField('DoB'); }, this); - this.customerCoc.subscribe(function() { + this.customerCoc.subscribe(function () { this.validateField('coc'); - }, this); - this.termsValidate.subscribe(function() { - this.validateField('TermsCondition'); }, this); - this.identificationValidate.subscribe(function() { - this.validateField('Identificationnumber'); + this.termsValidate.subscribe(function () { + this.validateField('TermsCondition'); + }, this); + this.identificationValidate.subscribe(function () { + this.validateField('Identificationnumber'); }, this); - this.phoneValidate.subscribe(function() { - this.validateField('Telephone'); + this.phoneValidate.subscribe(function () { + this.validateField('Telephone'); }, this); return this; @@ -307,26 +305,26 @@ define( getActiveValidationFields() { let fields = ['TermsCondition']; - if(this.showPhone()) { + if (this.showPhone()) { fields.push('Telephone') } - if(this.showIdentification()) { + if (this.showIdentification()) { fields.push('Identificationnumber') } - if(this.showCOC()) { + if (this.showCOC()) { fields.push('coc') } - if(this.showNLBEFields()) { + if (this.showNLBEFields()) { fields.push('DoB') } return fields; }, - validateField: function(id) { + validateField: function (id) { this.messageContainer.clear(); const isValid = $(`#buckaroo_magento2_afterpay20_${id}`).valid(); let state = this.validationState(); @@ -366,7 +364,7 @@ define( 'dpd-selected-parcelshop-city', 'dpd-selected-parcelshop-country' ]; - dpdCookies.forEach(function(item) { + dpdCookies.forEach(function (item) { var value = $.mage.cookies.get(item); if (value) { $.mage.cookies.clear(item); diff --git a/view/frontend/web/js/view/payment/method-renderer/billink.js b/view/frontend/web/js/view/payment/method-renderer/billink.js index b139a441f..c1e2903c8 100644 --- a/view/frontend/web/js/view/payment/method-renderer/billink.js +++ b/view/frontend/web/js/view/payment/method-renderer/billink.js @@ -56,15 +56,16 @@ define( value.substr(6, 4), value.substr(3, 2) - 1, value.substr(0, 2), - 0, 0, 0 + 0, + 0, + 0 ); return ~~((Date.now() - birthday) / (31557600000)) >= 18; } } return false; }, - $.mage.__('You should be at least 18 years old.') - ); + $.mage.__('You should be at least 18 years old.')); const validPhone = function (value) { if (quote.billingAddress() === null) { @@ -111,7 +112,9 @@ define( return true; }; - $.validator.addMethod('phoneValidation', validPhone , + $.validator.addMethod( + 'phoneValidation', + validPhone , $.mage.__('Phone number should be correct.') ); @@ -173,10 +176,10 @@ define( ); this.billingName = ko.computed( function () { - if(this.isB2B && quote.billingAddress() !== null) { + if (this.isB2B && quote.billingAddress() !== null) { return quote.billingAddress().company; } - if(quote.billingAddress() !== null) { + if (quote.billingAddress() !== null) { return quote.billingAddress().firstname + " " + quote.billingAddress().lastname; } }, @@ -201,7 +204,7 @@ define( ); this.showB2B = ko.computed( - function() { + function () { let shipping = quote.shippingAddress(); let billing = quote.billingAddress(); @@ -214,24 +217,24 @@ define( this ); - this.dob.subscribe(function() { + this.dob.subscribe(function () { const dobId = 'buckaroo_magento2_billink_DoB'; const isValid = $(`#${dobId}`).valid(); let state = this.validationState(); state[dobId] = isValid; this.validationState(state); - }, this); + }, this); this.buttoncheck = ko.computed( function () { const state = this.validationState(); const valid = this.getActiveValidationFields().map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true @@ -254,7 +257,7 @@ define( let fields = [ 'buckaroo_magento2_billink_TermsCondition', ]; - if(this.showPhone()) { + if (this.showPhone()) { fields.push('buckaroo_magento2_billink_Telephone') } @@ -323,7 +326,7 @@ define( getData: function () { let phone = this.phone(); - if(!this.showPhone() && quote.billingAddress() !== null) { + if (!this.showPhone() && quote.billingAddress() !== null) { phone = quote.billingAddress().telephone; } diff --git a/view/frontend/web/js/view/payment/method-renderer/capayablein3.js b/view/frontend/web/js/view/payment/method-renderer/capayablein3.js index c5b5513aa..e6f127098 100644 --- a/view/frontend/web/js/view/payment/method-renderer/capayablein3.js +++ b/view/frontend/web/js/view/payment/method-renderer/capayablein3.js @@ -90,9 +90,11 @@ define( return true; }; - $.validator.addMethod('in3phoneValidation', validPhone , - $.mage.__('Phone number should be correct.') - ); + $.validator.addMethod( + 'in3phoneValidation', + validPhone , + $.mage.__('Phone number should be correct.') + ); return Component.extend( { @@ -144,7 +146,7 @@ define( this.billingName = ko.computed( function () { - if(quote.billingAddress() !== null) { + if (quote.billingAddress() !== null) { return quote.billingAddress().firstname + " " + quote.billingAddress().lastname } return ''; @@ -158,12 +160,12 @@ define( function () { const state = this.validationState(); const valid =this.getActiveFields().map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true @@ -173,13 +175,13 @@ define( this ); - this.dateValidate.subscribe(function() { + this.dateValidate.subscribe(function () { const id = 'buckaroo_magento2_capayablein3_DoB'; const isValid = $(`#${id}`).valid(); let state = this.validationState(); state[id] = isValid; this.validationState(state); - }, this); + }, this); return this; }, @@ -187,7 +189,7 @@ define( let fields = [ 'buckaroo_magento2_capayablein3_DoB', ]; - if(this.showPhone()) { + if (this.showPhone()) { fields.push('buckaroo_magento2_capayablein3_Telephone'); } return fields; @@ -257,7 +259,7 @@ define( return $('.' + this.getCode() + ' .payment-method-second-col form').valid(); }, - getData : function() { + getData : function () { let telephone = quote.billingAddress().telephone; if (validPhone(this.phone())) { telephone = this.phone(); diff --git a/view/frontend/web/js/view/payment/method-renderer/creditcards.js b/view/frontend/web/js/view/payment/method-renderer/creditcards.js index 614e9093b..3c68ac0ff 100644 --- a/view/frontend/web/js/view/payment/method-renderer/creditcards.js +++ b/view/frontend/web/js/view/payment/method-renderer/creditcards.js @@ -48,44 +48,39 @@ define( */ $.validator.addMethod('validateCardNumber', function (value) { return BuckarooClientSideEncryption.V001.validateCardNumber(value.replace(/\s+/g, '')); - }, - $.mage.__('Please enter a valid creditcard number.') - ); + }, + $.mage.__('Please enter a valid creditcard number.')); $.validator.addMethod('validateCvc', function (value) { return BuckarooClientSideEncryption.V001.validateCvc( value, $('#buckaroo_magento2_creditcards_issuer').val() ); - }, - $.mage.__('Please enter a valid Cvc number.') - ); + }, + $.mage.__('Please enter a valid Cvc number.')); $.validator.addMethod('validateCardHolderName', function (value) { return BuckarooClientSideEncryption.V001.validateCardholderName(value); - }, - $.mage.__('Please enter a valid card holder name.') - ); + }, + $.mage.__('Please enter a valid card holder name.')); $.validator.addMethod('bkValidateYear', function (value) { - if(value.length === 0) { - return false; - } + if (value.length === 0) { + return false; + } const parts = value.split("/"); return BuckarooClientSideEncryption.V001.validateYear(parts[1]); - }, - $.mage.__('Enter a valid year number.') - ); + }, + $.mage.__('Enter a valid year number.')); $.validator.addMethod('bkValidateMonth', function (value) { - if(value.length === 0) { - return false; - } + if (value.length === 0) { + return false; + } const parts = value.split("/"); return BuckarooClientSideEncryption.V001.validateMonth(parts[0]); - }, - $.mage.__('Enter a valid month number.') - ); + }, + $.mage.__('Enter a valid month number.')); return Component.extend( { @@ -136,7 +131,7 @@ define( this.formatedCardNumber = ko.computed({ read: function () { let cardNumber = this.cardNumber(); - if(cardNumber.length) { + if (cardNumber.length) { return this.cardNumber().match(new RegExp('.{1,4}', 'g')).join(" "); } return ''; @@ -150,22 +145,29 @@ define( this.formatedExpirationDate = ko.computed({ read: function () { let expireDate = this.expireDate(); - if(expireDate.length) { + if (expireDate.length) { return expireDate.replace( - /^([1-9]\/|[2-9])$/g, '0$1/' // 3 > 03/ - ).replace( - /^(0[1-9]|1[0-2])$/g, '$1/' // 11 > 11/ - ).replace( - /^([0-1])([3-9])$/g, '0$1/$2' // 13 > 01/3 - ).replace( - /^(0?[1-9]|1[0-2])([0-9]{2})$/g, '$1/$2' // 141 > 01/41 - ).replace( - /^([0]+)\/|[0]+$/g, '0' // 0/ > 0 and 00 > 0 - ).replace( - /[^\d\/]|^[\/]*$/g, '' // To allow only digits and `/` - ).replace( - /\/\//g, '/' // Prevent entering more than 1 `/` - ); + /^([1-9]\/|[2-9])$/g, + '0$1/' // 3 > 03/ + ).replace( + /^(0[1-9]|1[0-2])$/g, + '$1/' // 11 > 11/ + ).replace( + /^([0-1])([3-9])$/g, + '0$1/$2' // 13 > 01/3 + ).replace( + /^(0?[1-9]|1[0-2])([0-9]{2})$/g, + '$1/$2' // 141 > 01/41 + ).replace( + /^([0]+)\/|[0]+$/g, + '0' // 0/ > 0 and 00 > 0 + ).replace( + /[^\d\/]|^[\/]*$/g, + '' // To allow only digits and `/` + ).replace( + /\/\//g, + '/' // Prevent entering more than 1 `/` + ); } return ''; }, @@ -185,7 +187,7 @@ define( cardLogo = issuer.img; } - return cardLogo; + return cardLogo; }, this ); @@ -203,9 +205,9 @@ define( ) //validate the cvc if exists - if(this.cvc().length) { - $('#buckaroo_magento2_creditcards_cvc').valid(); - } + if (this.cvc().length) { + $('#buckaroo_magento2_creditcards_cvc').valid(); + } }, validateField(data, event) { @@ -260,7 +262,7 @@ define( selectPaymentMethod: function () { window.checkoutConfig.buckarooFee.title(this.paymentFeeLabel); - this.getData().then(function(data) { + this.getData().then(function (data) { selectPaymentMethodAction(data); }) checkoutData.setSelectedPaymentMethod(this.item.method); @@ -296,7 +298,7 @@ define( if (this.validate() && additionalValidators.validate()) { this.isPlaceOrderActionAllowed(false); - this.getData().then(function(data) { + this.getData().then(function (data) { placeOrder = placeOrderAction(data, self.redirectAfterPlaceOrder, self.messageContainer); $.when(placeOrder).fail( @@ -317,14 +319,14 @@ define( }, getData: function () { - return new Promise(function(resolve) { + return new Promise(function (resolve) { const parts = this.expireDate().split("/"); const month = parts[0]; const year = parts[1]; const method = this.item.method; let cardIssuer = this.cardIssuer(); - if(cardIssuer == null) { + if (cardIssuer == null) { cardIssuer = this.determineIssuer(this.cardNumber()); } @@ -335,7 +337,7 @@ define( month, this.cvc(), this.cardHolderName(), - function(encryptedCardData) { + function (encryptedCardData) { resolve({ "method": method, "po_number": null, @@ -344,7 +346,8 @@ define( "card_type" : cardIssuer } }) - }); + } + ); }.bind(this)) } } diff --git a/view/frontend/web/js/view/payment/method-renderer/giropay.js b/view/frontend/web/js/view/payment/method-renderer/giropay.js index 63d4f59c6..d8ec27314 100644 --- a/view/frontend/web/js/view/payment/method-renderer/giropay.js +++ b/view/frontend/web/js/view/payment/method-renderer/giropay.js @@ -61,16 +61,16 @@ define( bicNumber: '', validationState: {} }, - paymentFeeLabel : window.checkoutConfig.payment.buckaroo.giropay.paymentFeeLabel, - subtext : window.checkoutConfig.payment.buckaroo.giropay.subtext, - subTextStyle : checkoutCommon.getSubtextStyle('giropay'), - currencyCode : window.checkoutConfig.quoteData.quote_currency_code, - baseCurrencyCode : window.checkoutConfig.quoteData.base_currency_code, + paymentFeeLabel: window.checkoutConfig.payment.buckaroo.giropay.paymentFeeLabel, + subtext: window.checkoutConfig.payment.buckaroo.giropay.subtext, + subTextStyle: checkoutCommon.getSubtextStyle('giropay'), + currencyCode: window.checkoutConfig.quoteData.quote_currency_code, + baseCurrencyCode: window.checkoutConfig.quoteData.base_currency_code, /** - * @override - */ - initialize : function (options) { + * @override + */ + initialize: function (options) { if (checkoutData.getSelectedPaymentMethod() == options.index) { window.checkoutConfig.buckarooFee.title(this.paymentFeeLabel); } @@ -81,19 +81,19 @@ define( initObservable: function () { this._super().observe(['bicNumber', 'validationState']); - /** Check used to see form is valid **/ - this.buttoncheck = ko.computed( + /** Check used to see form is valid **/ + this.buttoncheck = ko.computed( function () { const state = this.validationState(); const valid = [ 'bicnumber', ].map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true @@ -129,7 +129,7 @@ define( */ placeOrder: function (data, event) { var self = this, - placeOrder; + placeOrder; if (event) { event.preventDefault(); @@ -188,3 +188,4 @@ define( ); } ); + diff --git a/view/frontend/web/js/view/payment/method-renderer/ideal.js b/view/frontend/web/js/view/payment/method-renderer/ideal.js index 10618b4e9..235a624a1 100644 --- a/view/frontend/web/js/view/payment/method-renderer/ideal.js +++ b/view/frontend/web/js/view/payment/method-renderer/ideal.js @@ -80,12 +80,12 @@ define( const valid = [ 'issuer', ].map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true diff --git a/view/frontend/web/js/view/payment/method-renderer/idealprocessing.js b/view/frontend/web/js/view/payment/method-renderer/idealprocessing.js index fb3d8cfb5..cb9f4ebfc 100644 --- a/view/frontend/web/js/view/payment/method-renderer/idealprocessing.js +++ b/view/frontend/web/js/view/payment/method-renderer/idealprocessing.js @@ -80,12 +80,12 @@ define( const valid = [ 'issuer', ].map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true diff --git a/view/frontend/web/js/view/payment/method-renderer/klarna.js b/view/frontend/web/js/view/payment/method-renderer/klarna.js index 1983b3437..78e8f1978 100644 --- a/view/frontend/web/js/view/payment/method-renderer/klarna.js +++ b/view/frontend/web/js/view/payment/method-renderer/klarna.js @@ -79,8 +79,8 @@ define( * Check if the required fields are filled. If so: enable place order button (true) | if not: disable place order button (false) */ this.buttoncheck = ko.computed( - function () { - return this.selectedGender() != null; + function () { + return this.selectedGender() != null; }, this ); @@ -143,7 +143,7 @@ define( var text = $.mage.__('The transaction will be processed using %s.'); return text.replace('%s', this.baseCurrencyCode); - }, + }, getData: function () { return { diff --git a/view/frontend/web/js/view/payment/method-renderer/klarnain.js b/view/frontend/web/js/view/payment/method-renderer/klarnain.js index f8ef6ac4b..22c5684b2 100644 --- a/view/frontend/web/js/view/payment/method-renderer/klarnain.js +++ b/view/frontend/web/js/view/payment/method-renderer/klarnain.js @@ -77,8 +77,8 @@ define( * Check if the required fields are filled. If so: enable place order button (true) | if not: disable place order button (false) */ this.buttoncheck = ko.computed( - function () { - return this.selectedGender() != null; + function () { + return this.selectedGender() != null; }, this ); diff --git a/view/frontend/web/js/view/payment/method-renderer/mrcash.js b/view/frontend/web/js/view/payment/method-renderer/mrcash.js index 2d578eb78..6a3348c41 100644 --- a/view/frontend/web/js/view/payment/method-renderer/mrcash.js +++ b/view/frontend/web/js/view/payment/method-renderer/mrcash.js @@ -49,33 +49,29 @@ define( */ $.validator.addMethod('validateCardNumber', function (value) { return BuckarooClientSideEncryption.V001.validateCardNumber(value.replace(/\s+/g, '')); - }, - $.mage.__('Please enter a valid creditcard number.') - ); + }, + $.mage.__('Please enter a valid creditcard number.')); $.validator.addMethod('validateCardHolderName', function (value) { return BuckarooClientSideEncryption.V001.validateCardholderName(value); - }, - $.mage.__('Please enter a valid card holder name.') - ); + }, + $.mage.__('Please enter a valid card holder name.')); $.validator.addMethod('bkValidateYear', function (value) { - if(value.length === 0) { - return false; - } + if (value.length === 0) { + return false; + } const parts = value.split("/"); return BuckarooClientSideEncryption.V001.validateYear(parts[1]); - }, - $.mage.__('Enter a valid year number.') - ); + }, + $.mage.__('Enter a valid year number.')); $.validator.addMethod('bkValidateMonth', function (value) { - if(value.length === 0) { - return false; - } + if (value.length === 0) { + return false; + } const parts = value.split("/"); return BuckarooClientSideEncryption.V001.validateMonth(parts[0]); - }, - $.mage.__('Enter a valid month number.') - ); + }, + $.mage.__('Enter a valid month number.')); return Component.extend( { @@ -133,7 +129,7 @@ define( this.formatedCardNumber = ko.computed({ read: function () { let cardNumber = this.cardNumber(); - if(cardNumber.length) { + if (cardNumber.length) { return this.cardNumber().match(new RegExp('.{1,4}', 'g')).join(" "); } return ''; @@ -147,22 +143,29 @@ define( this.formatedExpirationDate = ko.computed({ read: function () { let expireDate = this.expireDate(); - if(expireDate.length) { + if (expireDate.length) { return expireDate.replace( - /^([1-9]\/|[2-9])$/g, '0$1/' // 3 > 03/ - ).replace( - /^(0[1-9]|1[0-2])$/g, '$1/' // 11 > 11/ - ).replace( - /^([0-1])([3-9])$/g, '0$1/$2' // 13 > 01/3 - ).replace( - /^(0?[1-9]|1[0-2])([0-9]{2})$/g, '$1/$2' // 141 > 01/41 - ).replace( - /^([0]+)\/|[0]+$/g, '0' // 0/ > 0 and 00 > 0 - ).replace( - /[^\d\/]|^[\/]*$/g, '' // To allow only digits and `/` - ).replace( - /\/\//g, '/' // Prevent entering more than 1 `/` - ); + /^([1-9]\/|[2-9])$/g, + '0$1/' // 3 > 03/ + ).replace( + /^(0[1-9]|1[0-2])$/g, + '$1/' // 11 > 11/ + ).replace( + /^([0-1])([3-9])$/g, + '0$1/$2' // 13 > 01/3 + ).replace( + /^(0?[1-9]|1[0-2])([0-9]{2})$/g, + '$1/$2' // 141 > 01/41 + ).replace( + /^([0]+)\/|[0]+$/g, + '0' // 0/ > 0 and 00 > 0 + ).replace( + /[^\d\/]|^[\/]*$/g, + '' // To allow only digits and `/` + ).replace( + /\/\//g, + '/' // Prevent entering more than 1 `/` + ); } return ''; }, @@ -174,7 +177,7 @@ define( this.buttoncheck = ko.computed( function () { - if(this.isMobileMode() || this.useClientSide == false) { + if (this.isMobileMode() || this.useClientSide == false) { return true; } const state = this.validationState(); @@ -183,12 +186,12 @@ define( 'buckaroo_magento2_mrcash_cardnumber', 'buckaroo_magento2_mrcash_expireDate', ].map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true @@ -210,7 +213,7 @@ define( }, getData: function () { - return new Promise(function(resolve) { + return new Promise(function (resolve) { const parts = this.expireDate().split("/"); const month = parts[0]; const year = parts[1]; @@ -224,7 +227,7 @@ define( month, '', this.cardHolderName(), - function(encryptedCardData) { + function (encryptedCardData) { resolve({ "method": method, "po_number": null, @@ -233,7 +236,8 @@ define( "client_side_mode" :clientSideMode } }) - }); + } + ); }.bind(this)) }, @@ -246,7 +250,7 @@ define( * placeOrderAction has been changed from Magento_Checkout/js/action/place-order to our own version * (Buckaroo_Magento2/js/action/place-order) to prevent redirect and handle the response. */ - placeOrder: function (data, event) { + placeOrder: function (data, event) { var self = this, placeOrder; @@ -256,7 +260,7 @@ define( if (additionalValidators.validate()) { this.isPlaceOrderActionAllowed(false); - this.getData().then(function(data) { + this.getData().then(function (data) { placeOrder = placeOrderAction(data, self.redirectAfterPlaceOrder, self.messageContainer); $.when(placeOrder).fail( diff --git a/view/frontend/web/js/view/payment/method-renderer/paybybank.js b/view/frontend/web/js/view/payment/method-renderer/paybybank.js index e566f09de..548bc7858 100644 --- a/view/frontend/web/js/view/payment/method-renderer/paybybank.js +++ b/view/frontend/web/js/view/payment/method-renderer/paybybank.js @@ -29,190 +29,190 @@ define([ "Magento_Checkout/js/action/select-payment-method", "buckaroo/checkout/common", ], function ( - $, - Component, - additionalValidators, - placeOrderAction, - ko, - $t, - checkoutData, - selectPaymentMethodAction, - checkoutCommon + $, + Component, + additionalValidators, + placeOrderAction, + ko, + $t, + checkoutData, + selectPaymentMethodAction, + checkoutCommon ) { - "use strict"; - - return Component.extend({ - defaults: { - template: "Buckaroo_Magento2/payment/buckaroo_magento2_paybybank", - selectedBank: "", - validationState: {}, - showAll: false, - bankTypes: window.checkoutConfig.payment.buckaroo.paybybank.banks, - isMobile: $(window).width() < 768, - logo: require.toUrl('Buckaroo_Magento2/images/paybybank.gif') - }, - redirectAfterPlaceOrder: false, - selectionType: - window.checkoutConfig.payment.buckaroo.paybybank.selectionType, - subtext: window.checkoutConfig.payment.buckaroo.paybybank.subtext, - subTextStyle: checkoutCommon.getSubtextStyle("paybybank"), - currencyCode: window.checkoutConfig.quoteData.quote_currency_code, - baseCurrencyCode: window.checkoutConfig.quoteData.base_currency_code, - internalBanks: window.checkoutConfig.payment.buckaroo.paybybank.banks, - /** - * @override - */ - initialize: function (options) { - return this._super(options); - }, - - initObservable: function () { - this._super().observe(["selectedBank", "validationState", "showAll", "isMobile"]); - this.initialSelected(); - const self = this; - $(window).resize(function () { - const width = $(window).width(); - if(width < 768 && self.isMobile() === false) { - self.isMobile(true); - } else if (width >= 768) { - self.isMobile(false); - } - }); - - this.bankTypes = ko.computed(function () { - const issuers = window.checkoutConfig.payment.buckaroo.paybybank.banks; - if (this.showAll() === false && !this.isMobile()) { - if (this.selectedBank() !== "") { - return issuers.filter(function (bank) { - return bank.code === this.selectedBank(); + "use strict"; + + return Component.extend({ + defaults: { + template: "Buckaroo_Magento2/payment/buckaroo_magento2_paybybank", + selectedBank: "", + validationState: {}, + showAll: false, + bankTypes: window.checkoutConfig.payment.buckaroo.paybybank.banks, + isMobile: $(window).width() < 768, + logo: require.toUrl('Buckaroo_Magento2/images/paybybank.gif') + }, + redirectAfterPlaceOrder: false, + selectionType: + window.checkoutConfig.payment.buckaroo.paybybank.selectionType, + subtext: window.checkoutConfig.payment.buckaroo.paybybank.subtext, + subTextStyle: checkoutCommon.getSubtextStyle("paybybank"), + currencyCode: window.checkoutConfig.quoteData.quote_currency_code, + baseCurrencyCode: window.checkoutConfig.quoteData.base_currency_code, + internalBanks: window.checkoutConfig.payment.buckaroo.paybybank.banks, + /** + * @override + */ + initialize: function (options) { + return this._super(options); + }, + + initObservable: function () { + this._super().observe(["selectedBank", "validationState", "showAll", "isMobile"]); + this.initialSelected(); + const self = this; + $(window).resize(function () { + const width = $(window).width(); + if (width < 768 && self.isMobile() === false) { + self.isMobile(true); + } else if (width >= 768) { + self.isMobile(false); + } + }); + + this.bankTypes = ko.computed(function () { + const issuers = window.checkoutConfig.payment.buckaroo.paybybank.banks; + if (this.showAll() === false && !this.isMobile()) { + if (this.selectedBank() !== "") { + return issuers.filter(function (bank) { + return bank.code === this.selectedBank(); + }, this); + } + return issuers.slice(0, 4); + } + return issuers; }, this); - } - return issuers.slice(0, 4); - } - return issuers; - }, this); - - /** Check used to see form is valid **/ - this.buttoncheck = ko.computed(function () { - const state = this.validationState(); - const valid = ["issuer"] - .map((field) => { - if (state[field] !== undefined) { - return state[field]; - } - return false; - }) - .reduce(function (prev, cur) { - return prev && cur; - }, true); - return valid; - }, this); - - this.logo = ko.computed(function () { - let found = this.internalBanks.find(function (bank) { - return bank.code === this.selectedBank(); - }, this); + + /** Check used to see form is valid **/ + this.buttoncheck = ko.computed(function () { + const state = this.validationState(); + const valid = ["issuer"] + .map((field) => { + if (state[field] !== undefined) { + return state[field]; + } + return false; + }) + .reduce(function (prev, cur) { + return prev && cur; + }, true); + return valid; + }, this); + + this.logo = ko.computed(function () { + let found = this.internalBanks.find(function (bank) { + return bank.code === this.selectedBank(); + }, this); + if (found !== undefined) { + return found.img; + } + return require.toUrl('Buckaroo_Magento2/images/paybybank.gif') + }, this); + return this; + }, + + + initialSelected() { + let found = this.internalBanks.find(function (bank) { + return bank.selected === true; + }); + if (found !== undefined) { - return found.img; + this.selectedBank(found.code); + this.updateFormState(true); } - return require.toUrl('Buckaroo_Magento2/images/paybybank.gif') - }, this); - return this; - }, - - - initialSelected() { - let found = this.internalBanks.find(function (bank) { - return bank.selected === true; - }); - - if (found !== undefined) { - this.selectedBank(found.code); - this.updateFormState(true); - } - }, - - validateField(data, event) { - this.updateFormState( - $(event.target).valid() - ); - }, - - updateFormState(isValid) { - let state = this.validationState(); - state["issuer"] = isValid; - this.validationState(state); - }, - - toggleShow: function () { - this.showAll(!this.showAll()); - }, - /** - * Place order. - * - * placeOrderAction has been changed from Magento_Checkout/js/action/place-order to our own version - * (Buckaroo_Magento2/js/action/place-order) to prevent redirect and handle the response. - */ - placeOrder: function (data, event) { - var self = this, - placeOrder; - - if (event) { - event.preventDefault(); - } - - if (this.validate() && additionalValidators.validate()) { - this.isPlaceOrderActionAllowed(false); - placeOrder = placeOrderAction( - this.getData(), - this.redirectAfterPlaceOrder, - this.messageContainer - ); - - $.when(placeOrder) - .fail(function () { - self.isPlaceOrderActionAllowed(true); - }) - .done(this.afterPlaceOrder.bind(this)); - return true; - } - return false; - }, - - afterPlaceOrder: function () { - var response = window.checkoutConfig.payment.buckaroo.response; - response = $.parseJSON(response); - checkoutCommon.redirectHandle(response); - }, - - selectPaymentMethod: function () { - selectPaymentMethodAction(this.getData()); - checkoutData.setSelectedPaymentMethod(this.item.method); - return true; - }, - - getData: function () { - return { - method: this.item.method, - po_number: null, - additional_data: { - issuer: this.selectedBank(), }, - }; - }, - payWithBaseCurrency: function () { - var allowedCurrencies = - window.checkoutConfig.payment.buckaroo.paybybank.allowedCurrencies; + validateField(data, event) { + this.updateFormState( + $(event.target).valid() + ); + }, + + updateFormState(isValid) { + let state = this.validationState(); + state["issuer"] = isValid; + this.validationState(state); + }, - return allowedCurrencies.indexOf(this.currencyCode) < 0; - }, + toggleShow: function () { + this.showAll(!this.showAll()); + }, + /** + * Place order. + * + * placeOrderAction has been changed from Magento_Checkout/js/action/place-order to our own version + * (Buckaroo_Magento2/js/action/place-order) to prevent redirect and handle the response. + */ + placeOrder: function (data, event) { + var self = this, + placeOrder; + + if (event) { + event.preventDefault(); + } - getPayWithBaseCurrencyText: function () { - var text = $.mage.__("The transaction will be processed using %s."); + if (this.validate() && additionalValidators.validate()) { + this.isPlaceOrderActionAllowed(false); + placeOrder = placeOrderAction( + this.getData(), + this.redirectAfterPlaceOrder, + this.messageContainer + ); + + $.when(placeOrder) + .fail(function () { + self.isPlaceOrderActionAllowed(true); + }) + .done(this.afterPlaceOrder.bind(this)); + return true; + } + return false; + }, + + afterPlaceOrder: function () { + var response = window.checkoutConfig.payment.buckaroo.response; + response = $.parseJSON(response); + checkoutCommon.redirectHandle(response); + }, - return text.replace("%s", this.baseCurrencyCode); - }, - }); + selectPaymentMethod: function () { + selectPaymentMethodAction(this.getData()); + checkoutData.setSelectedPaymentMethod(this.item.method); + return true; + }, + + getData: function () { + return { + method: this.item.method, + po_number: null, + additional_data: { + issuer: this.selectedBank(), + }, + }; + }, + + payWithBaseCurrency: function () { + var allowedCurrencies = + window.checkoutConfig.payment.buckaroo.paybybank.allowedCurrencies; + + return allowedCurrencies.indexOf(this.currencyCode) < 0; + }, + + getPayWithBaseCurrencyText: function () { + var text = $.mage.__("The transaction will be processed using %s."); + + return text.replace("%s", this.baseCurrencyCode); + }, + }); }); diff --git a/view/frontend/web/js/view/payment/method-renderer/payperemail.js b/view/frontend/web/js/view/payment/method-renderer/payperemail.js index 88b4cee98..14d9e2e40 100644 --- a/view/frontend/web/js/view/payment/method-renderer/payperemail.js +++ b/view/frontend/web/js/view/payment/method-renderer/payperemail.js @@ -84,7 +84,7 @@ define( ] ); quote.billingAddress.subscribe(function (address) { - if(address !== null) { + if (address !== null) { this.firstName(address.firstname || ''); this.lastName(address.lastname || ''); this.middleName(address.middlename || ''); @@ -108,7 +108,7 @@ define( ); } - if(quote.guestEmail) { + if (quote.guestEmail) { this.email(quote.guestEmail); this.updateState( 'buckaroo_magento2_payperemail_Email', @@ -126,12 +126,12 @@ define( "buckaroo_magento2_payperemail_BillingLastName", "buckaroo_magento2_payperemail_Email" ].map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true diff --git a/view/frontend/web/js/view/payment/method-renderer/sepadirectdebit.js b/view/frontend/web/js/view/payment/method-renderer/sepadirectdebit.js index 427f65918..0bf48dda0 100644 --- a/view/frontend/web/js/view/payment/method-renderer/sepadirectdebit.js +++ b/view/frontend/web/js/view/payment/method-renderer/sepadirectdebit.js @@ -148,12 +148,12 @@ define( function () { const state = this.validationState(); const valid =this.getActiveFields().map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true @@ -171,7 +171,7 @@ define( 'bankaccountholder', 'bankaccountnumber', ]; - if(!this.isnl()) { + if (!this.isnl()) { fields.push('bicnumber'); } return fields; diff --git a/view/frontend/web/js/view/payment/method-renderer/tinka.js b/view/frontend/web/js/view/payment/method-renderer/tinka.js index 5c35c4b67..3e658f3de 100644 --- a/view/frontend/web/js/view/payment/method-renderer/tinka.js +++ b/view/frontend/web/js/view/payment/method-renderer/tinka.js @@ -56,15 +56,16 @@ define( value.substr(6, 4), value.substr(3, 2) - 1, value.substr(0, 2), - 0, 0, 0 + 0, + 0, + 0 ); return ~~((Date.now() - birthday) / (31557600000)) >= 18; } } return false; }, - $.mage.__('You should be at least 18 years old.') - ); + $.mage.__('You should be at least 18 years old.')); return Component.extend( { @@ -110,8 +111,8 @@ define( ); this.activeAddress = ko.computed( - function() { - if(quote.billingAddress()) { + function () { + if (quote.billingAddress()) { return quote.billingAddress(); } return quote.shippingAddress(); @@ -119,7 +120,7 @@ define( ); this.country = ko.computed( - function() { + function () { return this.activeAddress().countryId; }, this @@ -152,12 +153,12 @@ define( function () { const state = this.validationState(); const valid = this.getActiveValidationFields().map((field) => { - if(state[field] !== undefined) { + if (state[field] !== undefined) { return state[field]; } return false; }).reduce( - function(prev, cur) { + function (prev, cur) { return prev && cur }, true @@ -167,13 +168,13 @@ define( this ); - this.dateValidate.subscribe(function() { + this.dateValidate.subscribe(function () { const dobId = 'buckaroo_magento2_tinka_DoB'; const isValid = $(`#${dobId}`).valid(); let state = this.validationState(); state[dobId] = isValid; this.validationState(state); - }, this); + }, this); return this; }, @@ -188,11 +189,11 @@ define( getActiveValidationFields() { let fields = []; - if(this.showPhone()) { + if (this.showPhone()) { fields.push('buckaroo_magento2_tinka_Telephone') } - if(this.showNLBEFields()) { + if (this.showNLBEFields()) { fields.push('buckaroo_magento2_tinka_DoB') } return fields; diff --git a/view/frontend/web/js/view/payment/method-renderer/voucher.js b/view/frontend/web/js/view/payment/method-renderer/voucher.js index 33c295855..88458f552 100644 --- a/view/frontend/web/js/view/payment/method-renderer/voucher.js +++ b/view/frontend/web/js/view/payment/method-renderer/voucher.js @@ -161,7 +161,7 @@ define( } } - ); + ); } ); diff --git a/view/frontend/web/js/view/payment/save-payment.js b/view/frontend/web/js/view/payment/save-payment.js index 46cd7f31e..910643b83 100644 --- a/view/frontend/web/js/view/payment/save-payment.js +++ b/view/frontend/web/js/view/payment/save-payment.js @@ -39,7 +39,7 @@ define( if (messagesComponent && messagesComponent.cookieMessages) { messagesComponent.cookieMessages.forEach(function (message) { if (message.type == 'error') { - messageList.addErrorMessage({message: $.mage.__($("").html(message.text).text())}); } }); }