diff --git a/composer.json b/composer.json index da409c32..c6b104ff 100644 --- a/composer.json +++ b/composer.json @@ -6,13 +6,13 @@ } ], "description": "Official Shopware 6 Plugin to connect to Payment Service Provider Adyen", - "version": "3.14.4", + "version": "3.15.0", "type": "shopware-platform-plugin", "license": "MIT", "require": { "shopware/core": "~6.4.0 || ~6.5.0", "shopware/storefront": "~6.4.0 || ~6.5.0", - "adyen/php-api-library": "^15.0.0", + "adyen/php-api-library": "^17.5.0", "adyen/php-webhook-module": "0.8.0", "ext-json": "*" }, diff --git a/src/AdyenPaymentShopware6.php b/src/AdyenPaymentShopware6.php index 0d0a2cdf..0dae2971 100644 --- a/src/AdyenPaymentShopware6.php +++ b/src/AdyenPaymentShopware6.php @@ -28,8 +28,6 @@ use Adyen\Shopware\Entity\Notification\NotificationEntityDefinition; use Adyen\Shopware\Entity\PaymentResponse\PaymentResponseEntityDefinition; use Adyen\Shopware\Entity\PaymentStateData\PaymentStateDataEntityDefinition; -use Adyen\Shopware\Handlers\GenericGiftCardPaymentMethodHandler; -use Adyen\Shopware\PaymentMethods; use Adyen\Shopware\Service\ConfigurationService; use Shopware\Core\Checkout\Payment\PaymentMethodEntity; use Shopware\Core\Framework\Plugin; @@ -46,7 +44,6 @@ use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; use Doctrine\DBAL\Connection; use Shopware\Core\System\SalesChannel\SalesChannelEntity; -use Symfony\Component\DependencyInjection\ContainerBuilder; class AdyenPaymentShopware6 extends Plugin { @@ -154,10 +151,6 @@ public function update(UpdateContext $updateContext): void $this->updateTo300($updateContext); } - if (\version_compare($currentVersion, '3.1.0', '<')) { - $this->updateTo310($updateContext); - } - if (\version_compare($currentVersion, '3.2.0', '<')) { $this->updateTo320($updateContext); } @@ -173,6 +166,10 @@ public function update(UpdateContext $updateContext): void if (\version_compare($currentVersion, '3.10.0', '<')) { $this->updateTo3100($updateContext); } + + if (\version_compare($currentVersion, '3.15.0', '<')) { + $this->updateTo3150($updateContext); + } } private function addPaymentMethod(PaymentMethods\PaymentMethodInterface $paymentMethod, Context $context): void @@ -388,37 +385,7 @@ private function updateTo300(UpdateContext $updateContext): void } } - private function updateTo310(UpdateContext $updateContext): void - { - //Version 3.1.0 introduces gift cards - foreach ([ - new PaymentMethods\GivexGiftCardPaymentMethod, - new PaymentMethods\WebshopGiftCardPaymentMethod, - new PaymentMethods\KadowereldGiftCardPaymentMethod, - new PaymentMethods\TCSTestGiftCardPaymentMethod, - new PaymentMethods\AlbelliGiftCardPaymentMethod, - new PaymentMethods\BijenkorfGiftCardPaymentMethod, - new PaymentMethods\VVVGiftCardPaymentMethod, - new PaymentMethods\GallGallGiftCardPaymentMethod, - new PaymentMethods\HunkemollerLingerieGiftCardPaymentMethod, - new PaymentMethods\BeautyGiftCardPaymentMethod, - new PaymentMethods\SVSGiftCardPaymentMethod, - ] as $method) { - $this->addPaymentMethod( - $method, - $updateContext->getContext() - ); - $this->setPaymentMethodIsActive( - true, - $updateContext->getContext(), - $method - ); - } - } - /** - * This update will add FashionCheque and DeCadeaukaart - * It will also set Savvy to inactive, add it as GenericGiftCard. * It will also remove all links of Savvy payment_method in sales_channel_payment_method and recreate these links * for the new payment method * @@ -426,75 +393,8 @@ private function updateTo310(UpdateContext $updateContext): void */ private function updateTo320(UpdateContext $updateContext): void { - foreach ([ - new PaymentMethods\FashionChequeGiftCardPaymentMethod(), - new PaymentMethods\DeCadeaukaartGiftCardPaymentMethod(), - new PaymentMethods\GenericGiftCardPaymentMethod() - ] as $method) { - $this->addPaymentMethod( - $method, - $updateContext->getContext() - ); - $this->setPaymentMethodIsActive( - true, - $updateContext->getContext(), - $method - ); - } - - // Set the Savvy payment method to inactive - /** @var EntityRepository $paymentRepository */ - $paymentRepository = $this->container->get('payment_method.repository'); - $salesChannelPaymentRepository = $this->container->get('sales_channel_payment_method.repository'); - $savvyPaymentMethodId = $this->getPaymentMethodId( - 'Adyen\Shopware\Handlers\SavvyGiftCardPaymentMethodHandler' - ); - // If savvy payment method is not found, return - if (!$savvyPaymentMethodId) { - return; - } - $paymentMethodData = [ - 'id' => $savvyPaymentMethodId, - 'active' => false - ]; - - // Set the savvy payment method to inactive - $paymentRepository->update([$paymentMethodData], $updateContext->getContext()); - - $criteria = new Criteria(); - $criteria->addFilter(new EqualsFilter('id', $savvyPaymentMethodId)); - $criteria->addAssociation('salesChannels'); - - /** @var PaymentMethodEntity $savvyPaymentMethod */ - $savvyPaymentMethod = $paymentRepository->search($criteria, $updateContext->getContext())->first(); - - $genericPaymentMethodId = $this->getPaymentMethodId( - GenericGiftCardPaymentMethodHandler::class - ); - - $salesChannelIds = []; - $salesChannels = $savvyPaymentMethod->getSalesChannels(); - - if (count($salesChannels) > 0) { - /** @var SalesChannelEntity $savvySalesChannel */ - foreach ($savvyPaymentMethod->getSalesChannels() as $savvySalesChannel) { - $salesChannelIds[] = ['id' => $savvySalesChannel->getId()]; - $salesChannelPaymentRepository->delete([ - [ - 'salesChannelId' => $savvySalesChannel->getId(), - 'paymentMethodId' => $savvyPaymentMethodId - ] - ], $updateContext->getContext()); - } - - // Add new Generic giftcard links to the sales channel - $paymentRepository->update([ - [ - 'id' => $genericPaymentMethodId, - 'salesChannels' => $salesChannelIds - ] - ], $updateContext->getContext()); - } + $paymentMethodHandler = 'Adyen\Shopware\Handlers\SavvyGiftCardPaymentMethodHandler'; + $this->deactivateAndRemovePaymentMethod($updateContext, $paymentMethodHandler); } private function updateTo350(UpdateContext $updateContext): void @@ -564,6 +464,43 @@ private function updateTo3100(UpdateContext $updateContext): void } } + private function updateTo3150(UpdateContext $updateContext): void + { + //Version 3.15.0 introduces MultiGiftcards + $this->addPaymentMethod( + new PaymentMethods\GiftCardPaymentMethod(), + $updateContext->getContext() + ); + $this->setPaymentMethodIsActive( + true, + $updateContext->getContext(), + new PaymentMethods\GiftcardPaymentMethod() + ); + + $deprecatedGiftcardMethods = [ + 'Adyen\Shopware\Handlers\AlbelliGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\BeautyGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\BijenkorfGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\DeCadeaukaartGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\FashionChequeGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\GallGallGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\GenericGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\GivexGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\HunkemollerLingerieGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\KadowereldGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\SVSGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\TCSTestGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\VVVGiftCardPaymentMethodHandler', + 'Adyen\Shopware\Handlers\WebshopGiftCardPaymentMethodHandler' + ]; + + // Disable deprecated gift card payment methods + foreach ($deprecatedGiftcardMethods as $deprecatedGiftcardMethod) { + $description = '@deprecated DO NOT ACTIVATE, use GiftCard instead'; + $this->deactivateAndRemovePaymentMethod($updateContext, $deprecatedGiftcardMethod, $description); + } + } + private function safeCopyAsset($source, $destination): bool { try { @@ -572,6 +509,61 @@ private function safeCopyAsset($source, $destination): bool return false; } } + + /** + * @param UpdateContext $updateContext + * @param string $paymentMethodHandler + * @param string|null $description + * @return void + */ + private function deactivateAndRemovePaymentMethod( + UpdateContext $updateContext, + string $paymentMethodHandler, + string $description = null + ): void { + /** @var EntityRepository $paymentRepository */ + $paymentRepository = $this->container->get('payment_method.repository'); + /** @var EntityRepository $salesChannelPaymentRepository */ + $salesChannelPaymentRepository = $this->container->get('sales_channel_payment_method.repository'); + + $paymentMethodId = $this->getPaymentMethodId($paymentMethodHandler); + // If payment method is not found, return + if (!$paymentMethodId) { + return; + } + $paymentMethodData = [ + 'id' => $paymentMethodId, + 'active' => false + ]; + + // Update description as deprecation message + if (isset($description)) { + $paymentMethodData['description'] = $description; + } + + // Set the payment method to inactive + $paymentRepository->update([$paymentMethodData], $updateContext->getContext()); + + $criteria = new Criteria(); + $criteria->addFilter(new EqualsFilter('id', $paymentMethodId)); + $criteria->addAssociation('salesChannels'); + + /** @var PaymentMethodEntity $paymentMethod */ + $paymentMethod = $paymentRepository->search($criteria, $updateContext->getContext())->first(); + $salesChannels = $paymentMethod->getSalesChannels(); + + if (count($salesChannels) > 0) { + /** @var SalesChannelEntity $savvySalesChannel */ + foreach ($paymentMethod->getSalesChannels() as $savvySalesChannel) { + $salesChannelPaymentRepository->delete([ + [ + 'salesChannelId' => $savvySalesChannel->getId(), + 'paymentMethodId' => $paymentMethodId + ] + ], $updateContext->getContext()); + } + } + } } if (file_exists(__DIR__ . '/../vendor/autoload.php')) { diff --git a/src/Command/DisablePaymentMethodCommand.php b/src/Command/DisablePaymentMethodCommand.php index 2bc3a674..7410752c 100644 --- a/src/Command/DisablePaymentMethodCommand.php +++ b/src/Command/DisablePaymentMethodCommand.php @@ -24,7 +24,7 @@ namespace Adyen\Shopware\Command; -use Adyen\Shopware\Handlers\Command\DisablePaymentMethodHandler; +use Adyen\Shopware\Handlers\Command\PaymentMethodStatusHandler; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -35,17 +35,17 @@ class DisablePaymentMethodCommand extends Command protected static $defaultName = 'adyen:payment-method:disable'; /** - * @var DisablePaymentMethodHandler + * @var PaymentMethodStatusHandler */ - protected $handler; + protected PaymentMethodStatusHandler $handler; - public function __construct(DisablePaymentMethodHandler $handler) + public function __construct(PaymentMethodStatusHandler $handler) { parent::__construct(); $this->handler = $handler; } - protected function configure() + protected function configure(): void { $this->setDescription('Finds the payment method according to given PM handler and disables it'); @@ -64,14 +64,14 @@ protected function configure() ); } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { try { $isAllSelected = $input->getOption('all'); $paymentMethodHandlerIdentifier = $input->getOption('payment-method'); if ($isAllSelected xor isset($paymentMethodHandlerIdentifier)) { - $this->handler->run($isAllSelected, $paymentMethodHandlerIdentifier); + $this->handler->run($isAllSelected, false, $paymentMethodHandlerIdentifier); $message = 'Payment method is disabled successfully.'; } else { throw new \Exception('Invalid parameter! For usage please check manual --help.'); @@ -81,6 +81,6 @@ protected function execute(InputInterface $input, OutputInterface $output) } $output->writeln($message); - return 0; + return Command::SUCCESS; } } diff --git a/src/Command/EnablePaymentMethodCommand.php b/src/Command/EnablePaymentMethodCommand.php index 9b8199d8..8fd1e458 100644 --- a/src/Command/EnablePaymentMethodCommand.php +++ b/src/Command/EnablePaymentMethodCommand.php @@ -24,7 +24,7 @@ namespace Adyen\Shopware\Command; -use Adyen\Shopware\Handlers\Command\EnablePaymentMethodHandler; +use Adyen\Shopware\Handlers\Command\PaymentMethodStatusHandler; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; @@ -35,17 +35,17 @@ class EnablePaymentMethodCommand extends Command protected static $defaultName = 'adyen:payment-method:enable'; /** - * @var EnablePaymentMethodHandler + * @var PaymentMethodStatusHandler */ - protected $handler; + protected PaymentMethodStatusHandler $handler; - public function __construct(EnablePaymentMethodHandler $handler) + public function __construct(PaymentMethodStatusHandler $handler) { parent::__construct(); $this->handler = $handler; } - protected function configure() + protected function configure(): void { $this->setDescription('Finds the payment method according to given PM handler and enables it'); @@ -64,14 +64,14 @@ protected function configure() ); } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { try { $isAllSelected = $input->getOption('all'); $paymentMethodHandlerIdentifier = $input->getOption('payment-method'); if ($isAllSelected xor isset($paymentMethodHandlerIdentifier)) { - $this->handler->run($isAllSelected, $paymentMethodHandlerIdentifier); + $this->handler->run($isAllSelected, true, $paymentMethodHandlerIdentifier); $message = 'Payment method is enabled successfully.'; } else { throw new \Exception('Invalid parameter! For usage please check manual --help.'); @@ -81,6 +81,6 @@ protected function execute(InputInterface $input, OutputInterface $output) } $output->writeln($message); - return 0; + return Command::SUCCESS; } } diff --git a/src/Command/FetchPaymentMethodLogosCommand.php b/src/Command/FetchPaymentMethodLogosCommand.php index c76452c3..e31825aa 100644 --- a/src/Command/FetchPaymentMethodLogosCommand.php +++ b/src/Command/FetchPaymentMethodLogosCommand.php @@ -44,15 +44,15 @@ public function __construct(FetchPaymentMethodLogosHandler $handler) $this->handler = $handler; } - protected function configure() + protected function configure(): void { $this->setDescription('Fetch and update logos for Adyen payment methods.'); } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $this->handler->run(); $output->writeln('All available logos have been updated.'); - return 0; + return Command::SUCCESS; } } diff --git a/src/Command/ProcessWebhooksCommand.php b/src/Command/ProcessWebhooksCommand.php index 67ce9e8b..f959699b 100644 --- a/src/Command/ProcessWebhooksCommand.php +++ b/src/Command/ProcessWebhooksCommand.php @@ -44,15 +44,15 @@ public function __construct(ProcessNotificationsHandler $handler) $this->handler = $handler; } - protected function configure() + protected function configure(): void { - $this->setDescription('Process webhook notifications.'); + $this->setDescription('Process webhook notifications'); } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $this->handler->run(); - $output->writeln('Webhook notifications have been processed.'); - return 0; + $output->writeln('Webhook notifications have been processed'); + return Command::SUCCESS; } } diff --git a/src/Command/ScheduleWebhooksCommand.php b/src/Command/ScheduleWebhooksCommand.php new file mode 100644 index 00000000..4323409a --- /dev/null +++ b/src/Command/ScheduleWebhooksCommand.php @@ -0,0 +1,58 @@ + + */ + +namespace Adyen\Shopware\Command; + +use Adyen\Shopware\ScheduledTask\ScheduleNotificationsHandler; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; + +class ScheduleWebhooksCommand extends Command +{ + protected static $defaultName = 'adyen:schedule-webhooks'; + + /** + * @var ScheduleNotificationsHandler + */ + protected $handler; + + public function __construct(ScheduleNotificationsHandler $handler) + { + parent::__construct(); + $this->handler = $handler; + } + + protected function configure(): void + { + $this->setDescription('Schedule webhook notifications'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $this->handler->run(); + $output->writeln('Webhook notifications have been scheduled'); + return Command::SUCCESS; + } +} diff --git a/src/Controller/AdminController.php b/src/Controller/AdminController.php index d2809a87..8effab36 100644 --- a/src/Controller/AdminController.php +++ b/src/Controller/AdminController.php @@ -23,12 +23,10 @@ namespace Adyen\Shopware\Controller; -use Adyen\AdyenException; use Adyen\Client; use Adyen\Service\Checkout; use Adyen\Shopware\Entity\AdyenPayment\AdyenPaymentEntity; use Adyen\Shopware\Entity\Notification\NotificationEntity; -use Adyen\Shopware\Entity\Refund\RefundEntity; use Adyen\Shopware\Exception\CaptureException; use Adyen\Shopware\Service\AdyenPaymentService; use Adyen\Shopware\Service\CaptureService; @@ -39,7 +37,7 @@ use Adyen\Shopware\Service\Repository\AdyenRefundRepository; use Adyen\Shopware\Service\Repository\OrderRepository; use Adyen\Shopware\Service\Repository\OrderTransactionRepository; -use Adyen\Util\Currency; +use Adyen\Shopware\Util\Currency; use Exception; use Psr\Log\LoggerInterface; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStates; @@ -51,6 +49,7 @@ use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; +use Throwable; /** * Class AdminController @@ -302,12 +301,16 @@ public function isManualCaptureEnabled(string $orderId) { try { $orderTransaction = $this->orderTransactionRepository->getFirstAdyenOrderTransaction($orderId); + if (is_null($orderTransaction)) { + return new JsonResponse(false); + } + $paymentMethodHandlerIdentifier = $orderTransaction->getPaymentMethod()->getHandlerIdentifier(); return new JsonResponse( $this->captureService->isManualCapture($paymentMethodHandlerIdentifier) ); - } catch (Exception $e) { + } catch (Throwable $t) { return new JsonResponse(false); } } @@ -364,27 +367,7 @@ public function postRefund(Request $request): JsonResponse } try { - $result = $this->refundService->refund($order, $amountInMinorUnit); - // If response does not contain pspReference - if (!array_key_exists('pspReference', $result)) { - $message = sprintf('Invalid response for refund on order %s', $order->getOrderNumber()); - throw new AdyenException($message); - } - - $statesToSearch = RefundService::REFUNDABLE_STATES; - $orderTransaction = $this->refundService->getAdyenOrderTransactionForRefund($order, $statesToSearch); - $adyenRefund = $this->adyenRefundRepository - ->getRefundForOrderByPspReference($orderTransaction->getId(), $result['pspReference']); - - if (is_null($adyenRefund)) { - $this->refundService->insertAdyenRefund( - $order, - $result['pspReference'], - RefundEntity::SOURCE_SHOPWARE, - RefundEntity::STATUS_PENDING_WEBHOOK, - $amountInMinorUnit - ); - } + $this->refundService->refund($order, (float) $refundAmount); } catch (Exception $e) { $this->logger->error($e->getMessage()); diff --git a/src/Controller/StoreApi/Donate/DonateController.php b/src/Controller/StoreApi/Donate/DonateController.php index 028d26ca..5f014ec3 100644 --- a/src/Controller/StoreApi/Donate/DonateController.php +++ b/src/Controller/StoreApi/Donate/DonateController.php @@ -30,7 +30,7 @@ use Adyen\Shopware\Service\ConfigurationService; use Adyen\Shopware\Service\DonationService; use Adyen\Shopware\Service\Repository\OrderTransactionRepository; -use Adyen\Util\Currency; +use Adyen\Shopware\Util\Currency; use Psr\Log\LoggerInterface; use Shopware\Core\Framework\Context; use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; diff --git a/src/Controller/StoreApi/OrderApi/OrderApiController.php b/src/Controller/StoreApi/OrderApi/OrderApiController.php index 3f4da9e7..801a23b2 100644 --- a/src/Controller/StoreApi/OrderApi/OrderApiController.php +++ b/src/Controller/StoreApi/OrderApi/OrderApiController.php @@ -28,13 +28,17 @@ use Adyen\Shopware\Service\PaymentMethodsBalanceService; use Adyen\Shopware\Service\OrdersService; use Adyen\Shopware\Service\OrdersCancelService; +use Adyen\Shopware\Service\PaymentMethodsFilterService; use Adyen\Shopware\Service\PaymentStateDataService; +use Shopware\Core\Framework\Validation\DataBag\RequestDataBag; +use Shopware\Core\System\SalesChannel\Context\SalesChannelContextService; +use Shopware\Core\System\SalesChannel\SalesChannel\AbstractContextSwitchRoute; use Shopware\Core\System\SalesChannel\SalesChannelContext; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; -use Shopware\Core\Framework\Uuid\Uuid; use Psr\Log\LoggerInterface; use Symfony\Component\Routing\Annotation\Route; +use Shopware\Core\Checkout\Cart\SalesChannel\CartService; /** * Class OrderApiController @@ -47,22 +51,24 @@ class OrderApiController * @var PaymentMethodsBalanceService */ private $paymentMethodsBalanceService; - /** - * @var OrdersService - */ - private $ordersService; + /** * @var OrdersService */ private $ordersCancelService; + /** * @var PaymentStateDataService */ private $paymentStateDataService; + /** - * @var LoggerInterface + * @var CartService */ + private $cartService; private $logger; + private $contextSwitchRoute; + private $paymentMethodsFilterService; /** * StoreApiController constructor. @@ -71,6 +77,9 @@ class OrderApiController * @param OrdersService $ordersService * @param OrdersCancelService $ordersCancelService * @param PaymentStateDataService $paymentStateDataService + * @param CartService $cartService + * @param PaymentMethodsFilterService $paymentMethodsFilterService + * @param AbstractContextSwitchRoute $contextSwitchRoute * @param LoggerInterface $logger */ public function __construct( @@ -78,12 +87,18 @@ public function __construct( OrdersService $ordersService, OrdersCancelService $ordersCancelService, PaymentStateDataService $paymentStateDataService, + CartService $cartService, + PaymentMethodsFilterService $paymentMethodsFilterService, + AbstractContextSwitchRoute $contextSwitchRoute, LoggerInterface $logger ) { $this->paymentMethodsBalanceService = $paymentMethodsBalanceService; $this->ordersService = $ordersService; $this->ordersCancelService = $ordersCancelService; $this->paymentStateDataService = $paymentStateDataService; + $this->cartService = $cartService; + $this->paymentMethodsFilterService = $paymentMethodsFilterService; + $this->contextSwitchRoute = $contextSwitchRoute; $this->logger = $logger; } @@ -107,25 +122,6 @@ public function getPaymentMethodsBalance(SalesChannelContext $context, Request $ ); } - /** - * @Route( - * "/store-api/adyen/orders", - * name="store-api.action.adyen.orders", - * methods={"POST"} - * ) - * - * @param SalesChannelContext $context - * @return JsonResponse - */ - public function createOrder(SalesChannelContext $context, Request $request): JsonResponse - { - $uuid = Uuid::randomHex(); - $orderAmount = $request->request->get('orderAmount'); - $currency = $request->request->get('currency'); - - return new JsonResponse($this->ordersService->createOrder($context, $uuid, $orderAmount, $currency)); - } - /** * @Route( * "/store-api/adyen/orders/cancel", @@ -134,6 +130,7 @@ public function createOrder(SalesChannelContext $context, Request $request): Jso * ) * * @param SalesChannelContext $context + * @param Request $request * @return JsonResponse */ public function cancelOrder(SalesChannelContext $context, Request $request): JsonResponse @@ -163,17 +160,13 @@ public function giftcardStateData(SalesChannelContext $context, Request $request if ('giftcard' !== $stateData['paymentMethod']['type']) { throw new ValidationException('Only giftcard state data is allowed to be stored.'); } + $this->paymentStateDataService->insertPaymentStateData( $context->getToken(), - json_encode($stateData), - [ - 'amount' => (int) $request->request->get('amount'), - 'paymentMethodId' => $request->request->get('paymentMethodId'), - 'balance' => (int) $request->request->get('balance'), - ] + json_encode($stateData) ); - return new JsonResponse(['paymentMethodId' => $request->request->get('paymentMethodId')]); + return new JsonResponse(['token' => $context->getToken()]); } /** @@ -188,8 +181,83 @@ public function giftcardStateData(SalesChannelContext $context, Request $request */ public function deleteGiftCardStateData(SalesChannelContext $context, Request $request): JsonResponse { - $this->paymentStateDataService->deletePaymentStateDataFromContextToken($context->getToken()); + $stateDateId = $request->request->get('stateDataId'); + $this->paymentStateDataService->deletePaymentStateDataFromId($stateDateId); return new JsonResponse(['token' => $context->getToken()]); } + + /** + * @Route( + * "/store-api/adyen/giftcard", + * name="store-api.action.adyen.giftcard.fetch", + * methods={"POST"} + * ) + * @param SalesChannelContext $context + * @param Request $request + * @return JsonResponse + * @throws ValidationException + * @throws \Adyen\AdyenException + */ + public function fetchRedeemedGiftcards(SalesChannelContext $context): JsonResponse + { + $fetchedRedeemedGiftcards = $this->paymentStateDataService + ->fetchRedeemedGiftCardsFromContextToken($context->getToken()); + $remainingOrderAmount = $this->cartService + ->getCart($context->getToken(), $context) + ->getPrice()->getTotalPrice(); + $giftcardDetails = $this->paymentStateDataService->getGiftcardTotalDiscountAndBalance( + $context, + $remainingOrderAmount + ); + $paymentMethodId = $this->paymentMethodsFilterService->getGiftCardPaymentMethodId($context); + + if ($giftcardDetails['giftcardDiscount'] >= $remainingOrderAmount) { //if full amount is covered + $this->contextSwitchRoute->switchContext( + new RequestDataBag( + [ + SalesChannelContextService::PAYMENT_METHOD_ID => $paymentMethodId + ] + ), + $context + ); + } + + $responseArray = [ + 'giftcards' => $this->filterGiftcardStateData($fetchedRedeemedGiftcards, $context), + 'remainingAmount' => $remainingOrderAmount - $giftcardDetails['giftcardDiscount'], + 'totalDiscount' => $giftcardDetails['giftcardDiscount'] + ]; + + return new JsonResponse(['redeemedGiftcards' => $responseArray]); + } + + private function filterGiftcardStateData($fetchedRedeemedGiftcards, $salesChannelContext): array + { + $responseArray = array(); + $remainingOrderAmount = $this->cartService + ->getCart($salesChannelContext->getToken(), $salesChannelContext) + ->getPrice()->getTotalPrice(); + + foreach ($fetchedRedeemedGiftcards->getElements() as $fetchedRedeemedGiftcard) { + $stateData = json_decode($fetchedRedeemedGiftcard->getStateData(), true); + if (!isset($stateData['paymentMethod']['type']) || + !isset($stateData['paymentMethod']['brand']) || + $stateData['paymentMethod']['type'] !== 'giftcard') { + unset($fetchedRedeemedGiftcards); + continue; + } + $deductedAmount = min($remainingOrderAmount, $stateData['giftcard']['value']); + $responseArray[] = [ + 'stateDataId' => $fetchedRedeemedGiftcard->getId(), + 'brand' => $stateData['paymentMethod']['brand'], + 'title' => $stateData['giftcard']['title'], + 'balance' => $stateData['giftcard']['value'], + 'deductedAmount' => $deductedAmount + ]; + + $remainingOrderAmount -= $deductedAmount; + } + return $responseArray; + } } diff --git a/src/Controller/StoreApi/Payment/PaymentController.php b/src/Controller/StoreApi/Payment/PaymentController.php index a066298f..5b2b00f1 100644 --- a/src/Controller/StoreApi/Payment/PaymentController.php +++ b/src/Controller/StoreApi/Payment/PaymentController.php @@ -24,7 +24,8 @@ namespace Adyen\Shopware\Controller\StoreApi\Payment; -use Adyen\Service\Validator\CheckoutStateDataValidator; +use Adyen\Model\Checkout\PaymentDetailsRequest; +use Adyen\Shopware\Util\CheckoutStateDataValidator; use Adyen\Shopware\Exception\PaymentFailedException; use Adyen\Shopware\Handlers\PaymentResponseHandler; use Adyen\Shopware\Service\ConfigurationService; @@ -95,7 +96,7 @@ class PaymentController /** * @var EntityRepository */ - private $orderTransactionRepository; + private EntityRepository $orderTransactionRepository; /** * @var StateMachineRegistry */ @@ -130,10 +131,10 @@ class PaymentController * @param OrderService $orderService * @param StateMachineRegistry $stateMachineRegistry * @param InitialStateIdLoader $initialStateIdLoader - * @param LoggerInterface $logger * @param EntityRepository $orderTransactionRepository * @param ConfigurationService $configurationService * @param OrderTransactionStateHandler $orderTransactionStateHandler + * @param LoggerInterface $logger */ public function __construct( PaymentMethodsService $paymentMethodsService, @@ -146,10 +147,10 @@ public function __construct( OrderService $orderService, StateMachineRegistry $stateMachineRegistry, InitialStateIdLoader $initialStateIdLoader, - LoggerInterface $logger, EntityRepository $orderTransactionRepository, ConfigurationService $configurationService, - OrderTransactionStateHandler $orderTransactionStateHandler + OrderTransactionStateHandler $orderTransactionStateHandler, + LoggerInterface $logger ) { $this->paymentMethodsService = $paymentMethodsService; $this->paymentDetailsService = $paymentDetailsService; @@ -160,11 +161,11 @@ public function __construct( $this->orderRepository = $orderRepository; $this->orderService = $orderService; $this->stateMachineRegistry = $stateMachineRegistry; - $this->logger = $logger; $this->orderTransactionRepository = $orderTransactionRepository; $this->configurationService = $configurationService; $this->orderTransactionStateHandler = $orderTransactionStateHandler; $this->initialStateIdLoader = $initialStateIdLoader; + $this->logger = $logger; } /** @@ -179,7 +180,8 @@ public function __construct( */ public function getPaymentMethods(SalesChannelContext $context): JsonResponse { - return new JsonResponse($this->paymentMethodsService->getPaymentMethods($context)); + $paymentMethodsResponse = $this->paymentMethodsService->getPaymentMethods($context); + return new JsonResponse($this->paymentMethodsService->getPaymentMethodsArray($paymentMethodsResponse)); } /** @@ -225,7 +227,7 @@ public function postPaymentDetails( try { $result = $this->paymentDetailsService->getPaymentDetails( - $stateData, + new PaymentDetailsRequest($stateData), $paymentResponse->getOrderTransaction() ); } catch (PaymentFailedException $exception) { diff --git a/src/Entity/AdyenPayment/AdyenPaymentEntity.php b/src/Entity/AdyenPayment/AdyenPaymentEntity.php index c8203bd0..d9407f80 100644 --- a/src/Entity/AdyenPayment/AdyenPaymentEntity.php +++ b/src/Entity/AdyenPayment/AdyenPaymentEntity.php @@ -71,6 +71,11 @@ class AdyenPaymentEntity extends Entity */ protected $amountCurrency; + /** + * @var int + */ + protected $totalRefunded; + /** * @var string */ @@ -203,6 +208,22 @@ public function setAmountValue(int $amountValue): void $this->amountValue = $amountValue; } + /** + * @return int + */ + public function getTotalRefunded(): int + { + return $this->totalRefunded; + } + + /** + * @param int $totalRefunded + */ + public function setTotalRefunded(int $totalRefunded): void + { + $this->totalRefunded = $totalRefunded; + } + /** * @return string */ diff --git a/src/Entity/AdyenPayment/AdyenPaymentEntityDefinition.php b/src/Entity/AdyenPayment/AdyenPaymentEntityDefinition.php index 87b9b97a..cb90cc56 100644 --- a/src/Entity/AdyenPayment/AdyenPaymentEntityDefinition.php +++ b/src/Entity/AdyenPayment/AdyenPaymentEntityDefinition.php @@ -76,6 +76,7 @@ protected function defineFields(): FieldCollection new StringField('merchant_order_reference', 'merchantOrderReference'), new StringField('payment_method', 'paymentMethod'), new IntField('amount_value', 'amountValue'), + new IntField('total_refunded', 'totalRefunded'), new StringField('amount_currency', 'amountCurrency'), new LongTextField('additional_data', 'additionalData'), new StringField('capture_mode', 'captureMode'), diff --git a/src/Handlers/AbstractPaymentMethodHandler.php b/src/Handlers/AbstractPaymentMethodHandler.php index 684f7f7b..56389ac4 100644 --- a/src/Handlers/AbstractPaymentMethodHandler.php +++ b/src/Handlers/AbstractPaymentMethodHandler.php @@ -27,20 +27,25 @@ use Adyen\AdyenException; use Adyen\Client; -use Adyen\Service\Builder\Address; -use Adyen\Service\Builder\Browser; -use Adyen\Service\Builder\Customer; -use Adyen\Service\Builder\Payment; -use Adyen\Service\Builder\OpenInvoice; -use Adyen\Service\Validator\CheckoutStateDataValidator; +use Adyen\Model\Checkout\CheckoutPaymentMethod; +use Adyen\Model\Checkout\EncryptedOrderData; +use Adyen\Model\Checkout\LineItem; +use Adyen\Model\Checkout\PaymentRequest; +use Adyen\Model\Checkout\Address; +use Adyen\Model\Checkout\Amount; +use Adyen\Model\Checkout\BrowserInfo; +use Adyen\Model\Checkout\Name; +use Adyen\Model\Checkout\PaymentResponse; +use Adyen\Service\Checkout\PaymentsApi; +use Adyen\Shopware\Util\CheckoutStateDataValidator; use Adyen\Shopware\Exception\PaymentCancelledException; use Adyen\Shopware\Exception\PaymentFailedException; -use Adyen\Shopware\Service\CheckoutService; use Adyen\Shopware\Service\ClientService; use Adyen\Shopware\Service\ConfigurationService; +use Adyen\Shopware\Service\OrdersService; use Adyen\Shopware\Service\PaymentStateDataService; use Adyen\Shopware\Service\Repository\SalesChannelRepository; -use Adyen\Util\Currency; +use Adyen\Shopware\Util\Currency; use Psr\Log\LoggerInterface; use Shopware\Core\Checkout\Order\Aggregate\OrderTransaction\OrderTransactionStateHandler; use Shopware\Core\Checkout\Payment\Cart\AsyncPaymentTransactionStruct; @@ -55,10 +60,8 @@ use Shopware\Core\Framework\Context; use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; +use Shopware\Core\Framework\Uuid\Uuid; use Shopware\Core\Framework\Validation\DataBag\RequestDataBag; -use Shopware\Core\System\Currency\CurrencyCollection; -use Shopware\Core\System\Currency\CurrencyEntity; -use Adyen\Shopware\Exception\CurrencyNotFoundException; use Shopware\Core\System\SalesChannel\Context\SalesChannelContextService; use Shopware\Core\System\SalesChannel\SalesChannel\AbstractContextSwitchRoute; use Shopware\Core\System\SalesChannel\SalesChannelContext; @@ -84,36 +87,15 @@ abstract class AbstractPaymentMethodHandler implements AsynchronousPaymentHandle */ const SAFE_ERROR_CODES = ['124']; - public static $isOpenInvoice = false; - public static $isGiftCard = false; - public static $supportsManualCapture = false; - public static $supportsPartialCapture = false; + public static bool $isOpenInvoice = false; + public static bool $supportsManualCapture = false; + public static bool $supportsPartialCapture = false; /** * @var ClientService */ protected $clientService; - /** - * @var Browser - */ - protected $browserBuilder; - - /** - * @var Address - */ - protected $addressBuilder; - - /** - * @var Payment - */ - protected $paymentBuilder; - - /** - * @var OpenInvoice - */ - protected $openInvoiceBuilder; - /** * @var Currency */ @@ -124,11 +106,6 @@ abstract class AbstractPaymentMethodHandler implements AsynchronousPaymentHandle */ protected $configurationService; - /** - * @var Customer - */ - protected $customerBuilder; - /** * @var CheckoutStateDataValidator */ @@ -189,7 +166,7 @@ abstract class AbstractPaymentMethodHandler implements AsynchronousPaymentHandle */ private $contextSwitchRoute; - private $checkoutService; + private $paymentsApiService; private $paymentResults = []; @@ -197,17 +174,15 @@ abstract class AbstractPaymentMethodHandler implements AsynchronousPaymentHandle private $remainingAmount = null; + private OrdersService $ordersService; + /** * AbstractPaymentMethodHandler constructor. * - * @param ConfigurationService $configurationService + * @param OrdersService $ordersService * @param ClientService $clientService - * @param Browser $browserBuilder - * @param Address $addressBuilder - * @param Payment $paymentBuilder - * @param OpenInvoice $openInvoiceBuilder + * @param ConfigurationService $configurationService * @param Currency $currency - * @param Customer $customerBuilder * @param CheckoutStateDataValidator $checkoutStateDataValidator * @param PaymentStateDataService $paymentStateDataService * @param SalesChannelRepository $salesChannelRepository @@ -218,18 +193,14 @@ abstract class AbstractPaymentMethodHandler implements AsynchronousPaymentHandle * @param RequestStack $requestStack * @param EntityRepository $currencyRepository * @param EntityRepository $productRepository - * @param LoggerInterface $logger * @param AbstractContextSwitchRoute $contextSwitchRoute + * @param LoggerInterface $logger */ public function __construct( + OrdersService $ordersService, ConfigurationService $configurationService, ClientService $clientService, - Browser $browserBuilder, - Address $addressBuilder, - Payment $paymentBuilder, - OpenInvoice $openInvoiceBuilder, Currency $currency, - Customer $customerBuilder, CheckoutStateDataValidator $checkoutStateDataValidator, PaymentStateDataService $paymentStateDataService, SalesChannelRepository $salesChannelRepository, @@ -243,14 +214,10 @@ public function __construct( AbstractContextSwitchRoute $contextSwitchRoute, LoggerInterface $logger ) { + $this->ordersService = $ordersService; $this->clientService = $clientService; - $this->browserBuilder = $browserBuilder; - $this->addressBuilder = $addressBuilder; - $this->openInvoiceBuilder = $openInvoiceBuilder; $this->currency = $currency; $this->configurationService = $configurationService; - $this->customerBuilder = $customerBuilder; - $this->paymentBuilder = $paymentBuilder; $this->checkoutStateDataValidator = $checkoutStateDataValidator; $this->paymentStateDataService = $paymentStateDataService; $this->salesChannelRepository = $salesChannelRepository; @@ -284,69 +251,54 @@ public function pay( RequestDataBag $dataBag, SalesChannelContext $salesChannelContext ): RedirectResponse { - $this->checkoutService = new CheckoutService( + + $this->paymentsApiService = new PaymentsApi( $this->clientService->getClient($salesChannelContext->getSalesChannel()->getId()) ); + + $countStateData= 0; $requestStateData = $dataBag->get('stateData'); if ($requestStateData) { $requestStateData = json_decode($requestStateData, true); + $countStateData++; + } + $countStoredStateData = $this->paymentStateDataService->countStoredStateData($salesChannelContext); + $countStateData += $countStoredStateData; + //If condition to check more than 1 PM + if ($countStateData > 1) { + $adyenOrderResponse = $this->createAdyenOrder($salesChannelContext, $transaction); + $this->handleAdyenOrderPayment($transaction, $adyenOrderResponse, $salesChannelContext); } - - $this->handleAdyenOrderPayment($transaction, $dataBag, $salesChannelContext); $transactionId = $transaction->getOrderTransaction()->getId(); - $storedStateData = $this->getStoredStateData($salesChannelContext, $transactionId); + $storedStateData = $this->paymentStateDataService->getStoredStateData($salesChannelContext, $transactionId); + + /* + * For single gift card payments, $storedStateData will be used. + * For all other cases, $requestStateData can be used or $stateData can be null. + */ $stateData = $requestStateData ?? $storedStateData ?? []; - try { - $request = $this->preparePaymentsRequest( + /* + * If there are more than one stateData and /payments calls have been completed, + * check the remaining order amount for final /payments call. + * + * remainingAmount is only set if there are multiple payments. + */ + if (is_null($this->remainingAmount) || $this->remainingAmount > 0) { + $request = $this->getPaymentRequest( $salesChannelContext, $transaction, $stateData, $this->remainingAmount, $this->orderRequestData ); - } catch (AsyncPaymentProcessException $exception) { - $this->logger->error($exception->getMessage()); - throw $exception; - } catch (\Exception $exception) { - $message = sprintf( - "There was an error with the payment method. Order number: %s Missing data: %s", - $transaction->getOrder()->getOrderNumber(), - $exception->getMessage() - ); - $this->logger->error($message); - throw new AsyncPaymentProcessException($transactionId, $message); - } - - if ($storedStateData) { - // Remove the used state.data - $this->paymentStateDataService->deletePaymentStateDataFromContextToken($salesChannelContext->getToken()); - } - - try { - $this->clientService->logRequest( - $request, - Client::API_CHECKOUT_VERSION, - '/payments', - $salesChannelContext->getSalesChannelId() - ); - - $response = $this->checkoutService->payments($request); - - $this->clientService->logResponse( - $response, - $salesChannelContext->getSalesChannelId() - ); - } catch (AdyenException $exception) { - $message = sprintf( - "There was an error with the /payments request. Order number %s: %s", - $transaction->getOrder()->getOrderNumber(), - $exception->getMessage() - ); - $this->displaySafeErrorMessages($exception); - $this->logger->error($message); - throw new AsyncPaymentProcessException($transactionId, $message); + //make /payments call + $this->paymentsCall($salesChannelContext, $request, $transaction); + //Remove all state data if stored or from giftcard + if ($storedStateData) { + $this->paymentStateDataService->deletePaymentStateDataFromId($storedStateData['id']); + } } $orderNumber = $transaction->getOrder()->getOrderNumber(); @@ -356,9 +308,6 @@ public function pay( throw new AsyncPaymentProcessException($transactionId, $message); } - $this->paymentResults[] = $this->paymentResponseHandler - ->handlePaymentResponse($response, $transaction->getOrderTransaction(), false); - try { $this->paymentResponseHandler ->handleShopwareApis($transaction, $salesChannelContext, $this->paymentResults); @@ -385,6 +334,17 @@ public function pay( return new RedirectResponse($transaction->getReturnUrl()); } + private function createAdyenOrder(SalesChannelContext $salesChannelContext, $transaction) + { + $uuid = Uuid::randomHex(); + $currency = $salesChannelContext->getCurrency()->getIsoCode(); + $amount = $this->currency->sanitize( + $transaction->getOrder()->getPrice()->getTotalPrice(), + $salesChannelContext->getCurrency()->getIsoCode() + ); + return $this->ordersService->createOrder($salesChannelContext, $uuid, $amount, $currency); + } + /** * @param AsyncPaymentTransactionStruct $transaction * @param Request $request @@ -413,7 +373,7 @@ public function finalize( * @param array $request * @param int|null $partialAmount * @param array|null $adyenOrderData - * @return array + * @return PaymentRequest */ protected function preparePaymentsRequest( SalesChannelContext $salesChannelContext, @@ -421,7 +381,10 @@ protected function preparePaymentsRequest( array $request = [], ?int $partialAmount = null, ?array $adyenOrderData = [] - ): array { + ): PaymentRequest { + + $paymentRequest = new PaymentRequest($request); + if (!empty($request['additionalData'])) { $stateDataAdditionalData = $request['additionalData']; } @@ -429,26 +392,33 @@ protected function preparePaymentsRequest( //Validate state.data for payment and build request object $request = $this->checkoutStateDataValidator->getValidatedAdditionalData($request); + //set payment method + if (!empty($request)) { + $paymentMethod = new CheckoutPaymentMethod($request['paymentMethod']); + } else { + $paymentMethod = new CheckoutPaymentMethod(); + } + //Setting payment method type if not present in statedata if (empty($request['paymentMethod']['type'])) { $paymentMethodType = static::getPaymentMethodCode(); } else { $paymentMethodType = $request['paymentMethod']['type']; } - - if (static::$isGiftCard) { - $request['paymentMethod']['brand'] = static::getBrand(); - } + + $paymentMethod->setType($paymentMethodType ?? 'zip'); + $paymentRequest->setPaymentMethod($paymentMethod); if (!empty($request['storePaymentMethod']) && $request['storePaymentMethod'] === true) { - $request['recurringProcessingModel'] = 'CardOnFile'; + $paymentRequest->setStorePaymentMethod($request['storePaymentMethod']); + $paymentRequest->setRecurringProcessingModel('CardOnFile'); } if (static::class === OneClickPaymentMethodHandler::class) { - $request['shopperInteraction'] = self::SHOPPER_INTERACTION_CONTAUTH; - $request['recurringProcessingModel'] = 'CardOnFile'; + $paymentRequest->setShopperInteraction(self::SHOPPER_INTERACTION_CONTAUTH); + $paymentRequest->setRecurringProcessingModel('CardOnFile'); } else { - $request['shopperInteraction'] = self::SHOPPER_INTERACTION_ECOMMERCE; + $paymentRequest->setShopperInteraction(self::SHOPPER_INTERACTION_ECOMMERCE); } //Setting browser info if not present in statedata @@ -463,6 +433,20 @@ protected function preparePaymentsRequest( $userAgent = $request['browserInfo']['userAgent']; } + if (!empty($request['browserInfo'])) { + $browserInfo = new BrowserInfo(); + $browserInfo->setUserAgent($userAgent); + $browserInfo->setAcceptHeader($acceptHeader); + $browserInfo->setScreenWidth($request['browserInfo']['screenWidth']); + $browserInfo->setScreenHeight($request['browserInfo']['screenHeight']); + $browserInfo->setColorDepth($request['browserInfo']['colorDepth']); + $browserInfo->setTimeZoneOffset($request['browserInfo']['timeZoneOffset']); + $browserInfo->setLanguage($request['browserInfo']['language']); + $browserInfo->setJavaEnabled($request['browserInfo']['javaEnabled']); + + $paymentRequest->setBrowserInfo($browserInfo); + } + //Setting delivery address info if not present in statedata if (empty($request['deliveryAddress'])) { if ($salesChannelContext->getShippingLocation()->getAddress()->getCountryState()) { @@ -475,15 +459,16 @@ protected function preparePaymentsRequest( $shippingStreetAddress = $this->getSplitStreetAddressHouseNumber( $salesChannelContext->getShippingLocation()->getAddress()->getStreet() ); - $request = $this->addressBuilder->buildDeliveryAddress( - $shippingStreetAddress['street'], - $shippingStreetAddress['houseNumber'], - $salesChannelContext->getShippingLocation()->getAddress()->getZipcode(), - $salesChannelContext->getShippingLocation()->getAddress()->getCity(), - $shippingState, - $salesChannelContext->getShippingLocation()->getAddress()->getCountry()->getIso(), - $request - ); + + $addressInfo = new Address(); + $addressInfo->setStreet($shippingStreetAddress['street']); + $addressInfo->setHouseNumberOrName($shippingStreetAddress['houseNumber']); + $addressInfo->setPostalCode($salesChannelContext->getShippingLocation()->getAddress()->getZipcode()); + $addressInfo->setCity($salesChannelContext->getShippingLocation()->getAddress()->getCity()); + $addressInfo->setStateOrProvince($shippingState); + $addressInfo->setCountry($salesChannelContext->getShippingLocation()->getAddress()->getCountry()->getIso()); + + $paymentRequest->setDeliveryAddress($addressInfo); } //Setting billing address info if not present in statedata @@ -498,15 +483,17 @@ protected function preparePaymentsRequest( $billingStreetAddress = $this->getSplitStreetAddressHouseNumber( $salesChannelContext->getCustomer()->getActiveBillingAddress()->getStreet() ); - $request = $this->addressBuilder->buildBillingAddress( - $billingStreetAddress['street'], - $billingStreetAddress['houseNumber'], - $salesChannelContext->getCustomer()->getActiveBillingAddress()->getZipcode(), - $salesChannelContext->getCustomer()->getActiveBillingAddress()->getCity(), - $billingState, - $salesChannelContext->getCustomer()->getActiveBillingAddress()->getCountry()->getIso(), - $request + + $addressInfo = new Address(); + $addressInfo->setStreet($billingStreetAddress['street']); + $addressInfo->setHouseNumberOrName($billingStreetAddress['houseNumber']); + $addressInfo->setPostalCode($salesChannelContext->getCustomer()->getActiveBillingAddress()->getZipcode()); + $addressInfo->setCity($salesChannelContext->getCustomer()->getActiveBillingAddress()->getCity()); + $addressInfo->setStateOrProvince($billingState); + $addressInfo->setCountry( + $salesChannelContext->getCustomer()->getActiveBillingAddress()->getCountry()->getIso() ); + $paymentRequest->setBillingAddress($addressInfo); } //Setting customer data if not present in statedata @@ -524,26 +511,25 @@ protected function preparePaymentsRequest( $shopperEmail = $request['shopperEmail']; } - if (empty($request['paymentMethod']['personalDetails']['telephoneNumber'])) { + if (empty($request['telephoneNumber'])) { $shopperPhone = $salesChannelContext->getShippingLocation()->getAddress()->getPhoneNumber(); } else { - $shopperPhone = $request['paymentMethod']['personalDetails']['telephoneNumber']; + $shopperPhone = $request['telephoneNumber']; } - if (empty($request['paymentMethod']['personalDetails']['dateOfBirth'])) { + if (empty($request['dateOfBirth'])) { if ($salesChannelContext->getCustomer()->getBirthday()) { $shopperDob = $salesChannelContext->getCustomer()->getBirthday()->format('Y-m-d'); } else { $shopperDob = ''; } } else { - $shopperDob = $request['paymentMethod']['personalDetails']['dateOfBirth']; + $shopperDob = $request['dateOfBirth']; } if (empty($request['shopperLocale'])) { $shopperLocale = $this->salesChannelRepository - ->getSalesChannelAssoc($salesChannelContext, ['language.locale']) - ->getLanguage()->getLocale()->getCode(); + ->getSalesChannelLocale($salesChannelContext); } else { $shopperLocale = $request['shopperLocale']; } @@ -566,52 +552,37 @@ protected function preparePaymentsRequest( $countryCode = $request['countryCode']; } - $request = $this->browserBuilder->buildBrowserData( - $userAgent, - $acceptHeader, - isset($request['browserInfo']['screenWidth']) ? $request['browserInfo']['screenWidth'] : null, - isset($request['browserInfo']['screenHeight']) ? $request['browserInfo']['screenHeight'] : null, - isset($request['browserInfo']['colorDepth']) ? $request['browserInfo']['colorDepth'] : null, - isset($request['browserInfo']['timeZoneOffset']) ? $request['browserInfo']['timeZoneOffset'] : null, - isset($request['browserInfo']['language']) ? $request['browserInfo']['language'] : null, - isset($request['browserInfo']['javaEnabled']) ? $request['browserInfo']['javaEnabled'] : null, - $request - ); + $shopperName = new Name(); + $shopperName->setFirstName($shopperFirstName); + $shopperName->setLastName($shopperLastName); - $request = $this->customerBuilder->buildCustomerData( - false, - $shopperEmail, - $shopperPhone, - '', - $shopperDob, - $shopperFirstName, - $shopperLastName, - $countryCode, - $shopperLocale, - $shopperIp, - $shopperReference, - $request - ); + $paymentRequest->setShopperName($shopperName); + $paymentRequest->setShopperEmail($shopperEmail); + if (!empty($shopperPhone)) { + $paymentRequest->setTelephoneNumber($shopperPhone); + } + $paymentRequest->setDateOfBirth($shopperDob); + $paymentRequest->setCountryCode($countryCode); + $paymentRequest->setShopperLocale($shopperLocale); + $paymentRequest->setShopperIP($shopperIp); + $paymentRequest->setShopperReference($shopperReference); //Building payment data $amount = $partialAmount ?: $this->currency->sanitize( $transaction->getOrder()->getPrice()->getTotalPrice(), $salesChannelContext->getCurrency()->getIsoCode() ); - $request = $this->paymentBuilder->buildPaymentData( - $salesChannelContext->getCurrency()->getIsoCode(), - $amount, - $transaction->getOrder()->getOrderNumber(), - $this->configurationService->getMerchantAccount($salesChannelContext->getSalesChannel()->getId()), - $transaction->getReturnUrl(), - $request - ); - $request = $this->paymentBuilder->buildAlternativePaymentMethodData( - $paymentMethodType, - '', - $request + $amountInfo = new Amount(); + $amountInfo->setCurrency($salesChannelContext->getCurrency()->getIsoCode()); + $amountInfo->setValue($amount); + + $paymentRequest->setAmount($amountInfo); + $paymentRequest->setReference($transaction->getOrder()->getOrderNumber()); + $paymentRequest->setMerchantAccount( + $this->configurationService->getMerchantAccount($salesChannelContext->getSalesChannel()->getId()) ); + $paymentRequest->setReturnUrl($transaction->getReturnUrl()); if (static::$isOpenInvoice) { $orderLines = $transaction->getOrder()->getLineItems(); @@ -633,15 +604,11 @@ protected function preparePaymentsRequest( } else { $taxRate = 0; } - $currency = $this->getCurrency( - $transaction->getOrder()->getCurrencyId(), - $salesChannelContext->getContext() - ); $product = !is_null($orderLine->getProductId()) ? - $this->getProduct($orderLine->getProductId(), $salesChannelContext->getContext()) : - null; + $this->getProduct($orderLine->getProductId(), $salesChannelContext->getContext()) : + null; // Add url for only real product and not for the custom cart items. if (!is_null($product->getId())) { @@ -666,72 +633,124 @@ protected function preparePaymentsRequest( $productCategory = null; } + $currency = $salesChannelContext->getCurrency(); + //Building open invoice line - $lineItems[] = $this->openInvoiceBuilder->buildOpenInvoiceLineItem( - $productName, - $this->currency->sanitize( - $price->getUnitPrice() - - ($transaction->getOrder()->getTaxStatus() == 'gross' ? $lineTax : 0), - $currency - ), - $this->currency->sanitize( - $lineTax, - $currency - ), - $taxRate * 100, - $orderLine->getQuantity(), - '', - $productNumber, - $productUrl, - $imageUrl, - $this->currency->sanitize( - $price->getUnitPrice(), - $currency - ), - $productCategory - ); + + $lineItem = new LineItem(); + + $lineItem->setDescription($productName); + $lineItem->setAmountExcludingTax($this->currency->sanitize( + $price->getUnitPrice() - + ($transaction->getOrder()->getTaxStatus() == 'gross' ? $lineTax : 0), + $currency->getIsoCode() + )); + $lineItem->setTaxAmount($this->currency->sanitize( + $lineTax, + $currency->getIsoCode() + )); + $lineItem->setTaxPercentage($taxRate * 100); + $lineItem->setQuantity($orderLine->getQuantity()); + $lineItem->setId($productNumber); + $lineItem->setProductUrl($productUrl); + $lineItem->setImageUrl($imageUrl); + $lineItem->setAmountIncludingTax($this->currency->sanitize( + $price->getUnitPrice(), + $currency->getIsoCode() + )); + $lineItem->setItemCategory($productCategory); + + $lineItems[] = $lineItem; } - $request['lineItems'] = $lineItems; + $paymentRequest->setLineItems($lineItems); } //Setting info from statedata additionalData if present if (!empty($stateDataAdditionalData['origin'])) { - $request['origin'] = $stateDataAdditionalData['origin']; + $origin = $stateDataAdditionalData['origin']; } else { $origin = $this->salesChannelRepository->getCurrentDomainUrl($salesChannelContext); - $request['origin'] = $origin; } - $request['additionalData']['allow3DS2'] = true; - - $request['channel'] = 'web'; + $paymentRequest->setOrigin($origin); + $paymentRequest->setAdditionaldata(['allow3DS2' => true]); + $paymentRequest->setChannel('Web'); if (!empty($adyenOrderData)) { - $request['order'] = $adyenOrderData; + $encryptedOrderData = new EncryptedOrderData(); + $encryptedOrderData->setOrderData($adyenOrderData['orderData']); + $encryptedOrderData->setPspReference($adyenOrderData['pspReference']); + $paymentRequest->setOrder($encryptedOrderData); } - return $request; + return $paymentRequest; } - /** - * @param string $currencyId - * @param Context $context - * @return CurrencyEntity - */ - private function getCurrency(string $currencyId, Context $context): CurrencyEntity - { - $criteria = new Criteria([$currencyId]); + private function getPaymentRequest( + $salesChannelContext, + $transaction, + $stateData, + $partialAmount, + $orderRequestData + ) { + $transactionId = $transaction->getOrderTransaction()->getId(); + try { + $request = $this->preparePaymentsRequest( + $salesChannelContext, + $transaction, + $stateData, + $partialAmount, + $orderRequestData + ); + return $request; + } catch (AsyncPaymentProcessException $exception) { + $this->logger->error($exception->getMessage()); + throw $exception; + } catch (\Exception $exception) { + $message = sprintf( + "There was an error with the payment method. Order number: %s Missing data: %s", + $transaction->getOrder()->getOrderNumber(), + $exception->getMessage() + ); + $this->logger->error($message); + throw new AsyncPaymentProcessException($transactionId, $message); + } + } - /** @var CurrencyCollection $currencyCollection */ - $currencyCollection = $this->currencyRepository->search($criteria, $context); + private function paymentsCall( + SalesChannelContext $salesChannelContext, + PaymentRequest $request, + AsyncPaymentTransactionStruct $transaction + ): void { + $transactionId = $transaction->getOrderTransaction()->getId(); + try { + $this->clientService->logRequest( + $request->toArray(), + Client::API_CHECKOUT_VERSION, + '/payments', + $salesChannelContext->getSalesChannelId() + ); - $currency = $currencyCollection->get($currencyId); - if ($currency === null) { - throw new CurrencyNotFoundException($currencyId); - } + /** @var PaymentResponse $response */ + $response = $this->paymentsApiService->payments($request); - return $currency; + $this->clientService->logResponse( + $response->toArray(), + $salesChannelContext->getSalesChannelId() + ); + } catch (AdyenException $exception) { + $message = sprintf( + "There was an error with the /payments request. Order number %s: %s", + $transaction->getOrder()->getOrderNumber(), + $exception->getMessage() + ); + $this->displaySafeErrorMessages($exception); + $this->logger->error($message); + throw new AsyncPaymentProcessException($transactionId, $message); + } + $this->paymentResults[] = $this->paymentResponseHandler + ->handlePaymentResponse($response, $transaction->getOrderTransaction(), false); } /** @@ -803,98 +822,60 @@ private function getSplitStreetAddressHouseNumber(string $address): array */ public function handleAdyenOrderPayment( AsyncPaymentTransactionStruct $transaction, - RequestDataBag $dataBag, + $adyenOrderResponse, SalesChannelContext $salesChannelContext ): void { - $adyenOrder = $dataBag->get('order'); - if (!$adyenOrder) { + if (empty($adyenOrderResponse)) { return; } - // order has been created, use state data from db as the first payment $transactionId = $transaction->getOrderTransaction()->getId(); - $storedStateData = $this->getStoredStateData($salesChannelContext, $transactionId); - if (!$storedStateData) { - $message = sprintf( - "There was an error with the giftcard payment. Order number: %s; Missing: giftcard data", - $transaction->getOrder()->getOrderNumber() - ); - $this->logger->error($message); - throw new AsyncPaymentProcessException($transactionId, $message); - } + + //New Multi-Gift-card implementation + $remainingOrderAmount = $this->currency->sanitize( + $transaction->getOrder()->getPrice()->getTotalPrice(), + $salesChannelContext->getCurrency()->getIsoCode() + ); $this->orderRequestData = [ - 'orderData' => $adyenOrder->get('orderData'), - 'pspReference' => $adyenOrder->get('pspReference') + 'orderData' => $adyenOrderResponse['orderData'], + 'pspReference' => $adyenOrderResponse['pspReference'] ]; - $partialAmount = (int) $storedStateData['additionalData']['amount']; - try { - $giftcardPaymentRequest = $this->preparePaymentsRequest( + + $stateData = $this->paymentStateDataService->fetchRedeemedGiftCardsFromContextToken( + $salesChannelContext->getToken() + ); + + foreach ($stateData->getElements() as $statedataArray) { + $storedStateData = json_decode($statedataArray->getStateData(), true); + $giftcardValue = $this->currency->sanitize( + $storedStateData['giftcard']['value'], + $salesChannelContext->getCurrency()->getIsoCode() + ); + $partialAmount = min($remainingOrderAmount, $giftcardValue); //convert to integer from float + + $giftcardPaymentRequest = $this->getPaymentRequest( $salesChannelContext, $transaction, $storedStateData, $partialAmount, $this->orderRequestData ); - } catch (AsyncPaymentProcessException $exception) { - $this->logger->error($exception->getMessage()); - throw $exception; - } catch (\Exception $exception) { - $message = sprintf( - "There was an error with the giftcard payment. Order number: %s Missing data: %s", - $transaction->getOrder()->getOrderNumber(), - $exception->getMessage() - ); - $this->logger->error($message); - throw new AsyncPaymentProcessException($transactionId, $message); - } - - try { - $giftcardPaymentResponse = $this->checkoutService->payments($giftcardPaymentRequest); - } catch (AdyenException $exception) { - $message = sprintf( - "There was an error with the giftcard payment request. Order number %s: %s", - $transaction->getOrder()->getOrderNumber(), - $exception->getMessage() - ); - $this->displaySafeErrorMessages($exception); - $this->logger->error($message); - throw new AsyncPaymentProcessException($transactionId, $message); - } - $this->paymentResults[] = $this->paymentResponseHandler - ->handlePaymentResponse($giftcardPaymentResponse, $transaction->getOrderTransaction(), false); + //make /payments call + $this->paymentsCall($salesChannelContext, $giftcardPaymentRequest, $transaction); - $this->remainingAmount = $this->currency->sanitize( - $transaction->getOrder()->getPrice()->getTotalPrice(), - $salesChannelContext->getCurrency()->getIsoCode() - ) - $partialAmount; - - // Remove the used state.data - $this->paymentStateDataService->deletePaymentStateDataFromContextToken($salesChannelContext->getToken()); - } + $remainingOrderAmount -= $partialAmount; - /** - * @param SalesChannelContext $salesChannelContext - * @param string $transactionId - * @return array|null - */ - public function getStoredStateData(SalesChannelContext $salesChannelContext, string $transactionId): ?array - { - // Check for state.data in db using the context token - $storedStateData = null; - $stateDataEntity = $this->paymentStateDataService->getPaymentStateDataFromContextToken( - $salesChannelContext->getToken() - ); - if ($stateDataEntity) { - $storedStateData = json_decode($stateDataEntity->getStateData(), true); + // Remove the used state.data + $this->paymentStateDataService->deletePaymentStateDataFromId($statedataArray->getId()); } - if (json_last_error() !== JSON_ERROR_NONE) { throw new AsyncPaymentProcessException( $transactionId, 'Invalid payment state data.' ); } - return $storedStateData; + + $this->remainingAmount = $remainingOrderAmount; } } diff --git a/src/Handlers/AffirmPaymentMethodHandler.php b/src/Handlers/AffirmPaymentMethodHandler.php index 400c0d48..99c26454 100644 --- a/src/Handlers/AffirmPaymentMethodHandler.php +++ b/src/Handlers/AffirmPaymentMethodHandler.php @@ -27,8 +27,8 @@ class AffirmPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $isOpenInvoice = true; - public static $supportsManualCapture = true; + public static bool $isOpenInvoice = true; + public static bool $supportsManualCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/AfterpayDefaultPaymentMethodHandler.php b/src/Handlers/AfterpayDefaultPaymentMethodHandler.php index c476b355..2ada178c 100644 --- a/src/Handlers/AfterpayDefaultPaymentMethodHandler.php +++ b/src/Handlers/AfterpayDefaultPaymentMethodHandler.php @@ -28,8 +28,8 @@ class AfterpayDefaultPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $isOpenInvoice = true; - public static $supportsManualCapture = true; + public static bool $isOpenInvoice = true; + public static bool $supportsManualCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/AlbelliGiftCardPaymentMethodHandler.php b/src/Handlers/AlbelliGiftCardPaymentMethodHandler.php index 04801af7..447d7f92 100644 --- a/src/Handlers/AlbelliGiftCardPaymentMethodHandler.php +++ b/src/Handlers/AlbelliGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class AlbelliGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Handlers/AmazonPayPaymentMethodHandler.php b/src/Handlers/AmazonPayPaymentMethodHandler.php index 32576454..e5968cb6 100644 --- a/src/Handlers/AmazonPayPaymentMethodHandler.php +++ b/src/Handlers/AmazonPayPaymentMethodHandler.php @@ -27,7 +27,7 @@ class AmazonPayPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $supportsManualCapture = true; + public static bool $supportsManualCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/ApplePayPaymentMethodHandler.php b/src/Handlers/ApplePayPaymentMethodHandler.php index 5c1cee50..6f37e4d9 100644 --- a/src/Handlers/ApplePayPaymentMethodHandler.php +++ b/src/Handlers/ApplePayPaymentMethodHandler.php @@ -27,8 +27,8 @@ class ApplePayPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $supportsManualCapture = true; - public static $supportsPartialCapture = true; + public static bool $supportsManualCapture = true; + public static bool $supportsPartialCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/BeautyGiftCardPaymentMethodHandler.php b/src/Handlers/BeautyGiftCardPaymentMethodHandler.php index 70321bcb..b07eb526 100644 --- a/src/Handlers/BeautyGiftCardPaymentMethodHandler.php +++ b/src/Handlers/BeautyGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class BeautyGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Handlers/BijenkorfGiftCardPaymentMethodHandler.php b/src/Handlers/BijenkorfGiftCardPaymentMethodHandler.php index 56c2e578..13c673d0 100644 --- a/src/Handlers/BijenkorfGiftCardPaymentMethodHandler.php +++ b/src/Handlers/BijenkorfGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class BijenkorfGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Handlers/CardsPaymentMethodHandler.php b/src/Handlers/CardsPaymentMethodHandler.php index 56903dc6..09aaf953 100644 --- a/src/Handlers/CardsPaymentMethodHandler.php +++ b/src/Handlers/CardsPaymentMethodHandler.php @@ -27,8 +27,8 @@ class CardsPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $supportsManualCapture = true; - public static $supportsPartialCapture = true; + public static bool $supportsManualCapture = true; + public static bool $supportsPartialCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/ClearpayPaymentMethodHandler.php b/src/Handlers/ClearpayPaymentMethodHandler.php index 11366b46..6d8f3055 100644 --- a/src/Handlers/ClearpayPaymentMethodHandler.php +++ b/src/Handlers/ClearpayPaymentMethodHandler.php @@ -27,8 +27,8 @@ class ClearpayPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $isOpenInvoice = true; - public static $supportsManualCapture = true; + public static bool $isOpenInvoice = true; + public static bool $supportsManualCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/Command/DisablePaymentMethodHandler.php b/src/Handlers/Command/DisablePaymentMethodHandler.php deleted file mode 100644 index 55a8356a..00000000 --- a/src/Handlers/Command/DisablePaymentMethodHandler.php +++ /dev/null @@ -1,112 +0,0 @@ - - */ - -namespace Adyen\Shopware\Handlers\Command; - -use Adyen\Shopware\Provider\AdyenPluginProvider; -use Shopware\Core\Framework\Context; -use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter; -use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter; - -class DisablePaymentMethodHandler -{ - /** - * @var AdyenPluginProvider - */ - private $adyenPluginProvider; - - /** - * @var EntityRepository - */ - private $paymentMethodRepository; - - /** - * @var EntityRepository - */ - private $salesChannelRepository; - - /** - * @var EntityRepository - */ - private $salesChannelPaymentMethodRepository; - - public function __construct( - AdyenPluginProvider $adyenPluginProvider, - EntityRepository $paymentMethodRepository, - EntityRepository $salesChannelRepository, - EntityRepository $salesChannelPaymentMethodRepository - ) { - $this->adyenPluginProvider = $adyenPluginProvider; - $this->paymentMethodRepository = $paymentMethodRepository; - $this->salesChannelRepository = $salesChannelRepository; - $this->salesChannelPaymentMethodRepository = $salesChannelPaymentMethodRepository; - } - - public function run(bool $isAll, ?string $paymentMethodHandlerIdentifier): void - { - $criteria = new Criteria(); - $criteria->addFilter( - new EqualsFilter('pluginId', $this->adyenPluginProvider->getAdyenPluginId()) - ); - if (!$isAll) { - $criteria->addFilter( - new ContainsFilter('handlerIdentifier', $paymentMethodHandlerIdentifier) - ); - } - - $paymentMethods = $this->paymentMethodRepository - ->search($criteria, Context::createDefaultContext()) - ->getEntities(); - - if (!count($paymentMethods->getElements())) { - throw new \Exception('No payment methods found!'); - } - - $criteria = new Criteria(); - $salesChannels = $this->salesChannelRepository - ->searchIds($criteria, Context::createDefaultContext()) - ->getData(); - - echo "Following payment methods will be disabled: \n"; - foreach ($paymentMethods->getElements() as $paymentMethod) { - $paymentMethodName = $paymentMethod->getName(); - echo "* $paymentMethodName \n"; - - foreach ($salesChannels as $salesChannel) { - $this->disablePaymentMethod($paymentMethod->getId(), $salesChannel['id']); - } - } - } - - private function disablePaymentMethod(string $paymentMethodId, string $salesChannelId) - { - $this->salesChannelPaymentMethodRepository - ->delete( - [['paymentMethodId' => $paymentMethodId, 'salesChannelId' => $salesChannelId]], - Context::createDefaultContext() - ); - } -} diff --git a/src/Handlers/Command/EnablePaymentMethodHandler.php b/src/Handlers/Command/PaymentMethodStatusHandler.php similarity index 80% rename from src/Handlers/Command/EnablePaymentMethodHandler.php rename to src/Handlers/Command/PaymentMethodStatusHandler.php index c35c4f9b..c68fad9b 100644 --- a/src/Handlers/Command/EnablePaymentMethodHandler.php +++ b/src/Handlers/Command/PaymentMethodStatusHandler.php @@ -31,16 +31,13 @@ use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter; use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter; -class EnablePaymentMethodHandler +class PaymentMethodStatusHandler { /** * @var AdyenPluginProvider */ private $adyenPluginProvider; - /** - * @var EntityRepository - */ private $paymentMethodRepository; /** @@ -55,7 +52,7 @@ class EnablePaymentMethodHandler public function __construct( AdyenPluginProvider $adyenPluginProvider, - EntityRepository $paymentMethodRepository, + $paymentMethodRepository, EntityRepository $salesChannelRepository, EntityRepository $salesChannelPaymentMethodRepository ) { @@ -65,12 +62,16 @@ public function __construct( $this->salesChannelPaymentMethodRepository = $salesChannelPaymentMethodRepository; } - public function run(bool $isAll, ?string $paymentMethodHandlerIdentifier): void + public function run(bool $isAll, bool $isActive, ?string $paymentMethodHandlerIdentifier): void { $criteria = new Criteria(); $criteria->addFilter( new EqualsFilter('pluginId', $this->adyenPluginProvider->getAdyenPluginId()) ); + $criteria->addFilter( + new EqualsFilter('active', true) + ); + if (!$isAll) { $criteria->addFilter( new ContainsFilter('handlerIdentifier', $paymentMethodHandlerIdentifier) @@ -96,12 +97,16 @@ public function run(bool $isAll, ?string $paymentMethodHandlerIdentifier): void echo "* $paymentMethodName \n"; foreach ($salesChannels as $salesChannel) { - $this->enablePaymentMethod($paymentMethod->getId(), $salesChannel['id']); + if ($isActive) { + $this->enablePaymentMethod($paymentMethod->getId(), $salesChannel['id']); + } else { + $this->disablePaymentMethod($paymentMethod->getId(), $salesChannel['id']); + } } } } - private function enablePaymentMethod(string $paymentMethodId, string $salesChannelId) + private function enablePaymentMethod(string $paymentMethodId, string $salesChannelId): void { $this->salesChannelPaymentMethodRepository->create( [ @@ -113,4 +118,13 @@ private function enablePaymentMethod(string $paymentMethodId, string $salesChann Context::createDefaultContext() ); } + + private function disablePaymentMethod(string $paymentMethodId, string $salesChannelId): void + { + $this->salesChannelPaymentMethodRepository + ->delete( + [['paymentMethodId' => $paymentMethodId, 'salesChannelId' => $salesChannelId]], + Context::createDefaultContext() + ); + } } diff --git a/src/Handlers/DeCadeaukaartGiftCardPaymentMethodHandler.php b/src/Handlers/DeCadeaukaartGiftCardPaymentMethodHandler.php index 588680c2..416dde12 100644 --- a/src/Handlers/DeCadeaukaartGiftCardPaymentMethodHandler.php +++ b/src/Handlers/DeCadeaukaartGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class DeCadeaukaartGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Handlers/Facilypay10xPaymentMethodHandler.php b/src/Handlers/Facilypay10xPaymentMethodHandler.php index 2a38b382..36b49eb1 100644 --- a/src/Handlers/Facilypay10xPaymentMethodHandler.php +++ b/src/Handlers/Facilypay10xPaymentMethodHandler.php @@ -28,8 +28,8 @@ class Facilypay10xPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $isOpenInvoice = true; - public static $supportsManualCapture = true; + public static bool $isOpenInvoice = true; + public static bool $supportsManualCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/Facilypay12xPaymentMethodHandler.php b/src/Handlers/Facilypay12xPaymentMethodHandler.php index 71e51f52..4ae0614a 100644 --- a/src/Handlers/Facilypay12xPaymentMethodHandler.php +++ b/src/Handlers/Facilypay12xPaymentMethodHandler.php @@ -28,8 +28,8 @@ class Facilypay12xPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $isOpenInvoice = true; - public static $supportsManualCapture = true; + public static bool $isOpenInvoice = true; + public static bool $supportsManualCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/Facilypay3xPaymentMethodHandler.php b/src/Handlers/Facilypay3xPaymentMethodHandler.php index b7456e5d..18e6237f 100644 --- a/src/Handlers/Facilypay3xPaymentMethodHandler.php +++ b/src/Handlers/Facilypay3xPaymentMethodHandler.php @@ -28,8 +28,8 @@ class Facilypay3xPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $isOpenInvoice = true; - public static $supportsManualCapture = true; + public static bool $isOpenInvoice = true; + public static bool $supportsManualCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/Facilypay4xPaymentMethodHandler.php b/src/Handlers/Facilypay4xPaymentMethodHandler.php index b0cc5298..069f0318 100644 --- a/src/Handlers/Facilypay4xPaymentMethodHandler.php +++ b/src/Handlers/Facilypay4xPaymentMethodHandler.php @@ -28,8 +28,8 @@ class Facilypay4xPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $isOpenInvoice = true; - public static $supportsManualCapture = true; + public static bool $isOpenInvoice = true; + public static bool $supportsManualCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/Facilypay6xPaymentMethodHandler.php b/src/Handlers/Facilypay6xPaymentMethodHandler.php index 3178354d..4cc6d313 100644 --- a/src/Handlers/Facilypay6xPaymentMethodHandler.php +++ b/src/Handlers/Facilypay6xPaymentMethodHandler.php @@ -28,8 +28,8 @@ class Facilypay6xPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $isOpenInvoice = true; - public static $supportsManualCapture = true; + public static bool $isOpenInvoice = true; + public static bool $supportsManualCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/FashionChequeGiftCardPaymentMethodHandler.php b/src/Handlers/FashionChequeGiftCardPaymentMethodHandler.php index e0e93f17..cb3dbe41 100644 --- a/src/Handlers/FashionChequeGiftCardPaymentMethodHandler.php +++ b/src/Handlers/FashionChequeGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class FashionChequeGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Handlers/GallGallGiftCardPaymentMethodHandler.php b/src/Handlers/GallGallGiftCardPaymentMethodHandler.php index b834a72a..c3c2bb2d 100644 --- a/src/Handlers/GallGallGiftCardPaymentMethodHandler.php +++ b/src/Handlers/GallGallGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class GallGallGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Handlers/GenericGiftCardPaymentMethodHandler.php b/src/Handlers/GenericGiftCardPaymentMethodHandler.php index 78efefac..ae4ea239 100644 --- a/src/Handlers/GenericGiftCardPaymentMethodHandler.php +++ b/src/Handlers/GenericGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class GenericGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Handlers/GiftCardPaymentMethodHandler.php b/src/Handlers/GiftCardPaymentMethodHandler.php new file mode 100644 index 00000000..d1b7f01a --- /dev/null +++ b/src/Handlers/GiftCardPaymentMethodHandler.php @@ -0,0 +1,12 @@ +setRefusalReason($response['refusalReason']); + // TODO Add argument type declaration for response and remove the following block on V4. + if (!($response instanceof PaymentResponse) && !($response instanceof PaymentDetailsResponse)) { + throw new \InvalidArgumentException('Invalid $paymentDetailsResponse type.'); } - if (array_key_exists('refusalReasonCode', $response)) { - $paymentResponseHandlerResult->setRefusalReasonCode($response['refusalReasonCode']); - } + // Retrieve result code from response array + $resultCode = $response->getResultCode(); + $paymentResponseHandlerResult = new PaymentResponseHandlerResult(); + $paymentResponseHandlerResult->setRefusalReason($response->getRefusalReason()); + $paymentResponseHandlerResult->setRefusalReasonCode($response->getRefusalReasonCode()); $paymentResponseHandlerResult->setResultCode($resultCode); - // Retrieve PSP reference from response array if available - if (!empty($response[self::PSP_REFERENCE])) { - $paymentResponseHandlerResult->setPspReference($response[self::PSP_REFERENCE]); + if (($response instanceof PaymentResponse) && !empty($response->getAction())) { + $paymentResponseHandlerResult->setAction($response->getAction()->toArray()); } - // Set action in result object if available - if (!empty($response[self::ACTION])) { - $paymentResponseHandlerResult->setAction($response[self::ACTION]); - } - - // Set additionalData in result object if available - if (!empty($response[self::ADDITIONAL_DATA])) { - $paymentResponseHandlerResult->setAdditionalData($response[self::ADDITIONAL_DATA]); - } + $paymentResponseHandlerResult->setPspReference($response->getPspReference()); + $paymentResponseHandlerResult->setAdditionalData($response->getAdditionalData()); /* * If this payment is a part of an Adyen order, * payment response contains `order` object. */ $isGiftcardOrderResponse = false; - if (!empty($response['paymentMethod']) && - !empty($response['paymentMethod']['type']) && - $response['paymentMethod']['type'] === 'giftcard' && - array_key_exists('order', $response)) { + + $method = $response->getPaymentMethod(); + + if (!empty($method) && + !empty($method->getType()) && + $method->getType() === 'giftcard') { $isGiftcardOrderResponse = true; } $paymentResponseHandlerResult->setIsGiftcardOrder($isGiftcardOrderResponse); + $donationToken = $response->getDonationToken(); + // Set Donation Token if response contains it, except for giftcards - if (!empty($response[self::DONATION_TOKEN]) && !$isGiftcardOrderResponse) { - $paymentResponseHandlerResult->setDonationToken($response[self::DONATION_TOKEN]); + if (!empty($donationToken) && !$isGiftcardOrderResponse) { + $paymentResponseHandlerResult->setDonationToken($donationToken); } // Store response for cart until the payment is finalised @@ -188,7 +183,7 @@ public function handlePaymentResponse( // Log Refused, no further steps needed $this->logger->error( "The payment was refused, order transaction merchant reference: " . - $response[self::MERCHANT_REFERENCE] + $response->getMerchantReference() ); break; diff --git a/src/Handlers/PaypalPaymentMethodHandler.php b/src/Handlers/PaypalPaymentMethodHandler.php index 1d7d6aed..08d5a6fc 100644 --- a/src/Handlers/PaypalPaymentMethodHandler.php +++ b/src/Handlers/PaypalPaymentMethodHandler.php @@ -27,8 +27,8 @@ class PaypalPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $supportsManualCapture = true; - public static $supportsPartialCapture = true; + public static bool $supportsManualCapture = true; + public static bool $supportsPartialCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/RatepayDirectdebitPaymentMethodHandler.php b/src/Handlers/RatepayDirectdebitPaymentMethodHandler.php index 47bd2922..26ef4ccb 100644 --- a/src/Handlers/RatepayDirectdebitPaymentMethodHandler.php +++ b/src/Handlers/RatepayDirectdebitPaymentMethodHandler.php @@ -28,9 +28,9 @@ class RatepayDirectdebitPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $isOpenInvoice = true; - public static $supportsManualCapture = true; - public static $supportsPartialCapture = true; + public static bool $isOpenInvoice = true; + public static bool $supportsManualCapture = true; + public static bool $supportsPartialCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/RatepayPaymentMethodHandler.php b/src/Handlers/RatepayPaymentMethodHandler.php index 40f95c9a..a04efc81 100644 --- a/src/Handlers/RatepayPaymentMethodHandler.php +++ b/src/Handlers/RatepayPaymentMethodHandler.php @@ -27,9 +27,9 @@ class RatepayPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $isOpenInvoice = true; - public static $supportsManualCapture = true; - public static $supportsPartialCapture = true; + public static bool $isOpenInvoice = true; + public static bool $supportsManualCapture = true; + public static bool $supportsPartialCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/ResultHandler.php b/src/Handlers/ResultHandler.php index 859b7ed0..b36c2906 100644 --- a/src/Handlers/ResultHandler.php +++ b/src/Handlers/ResultHandler.php @@ -25,7 +25,9 @@ namespace Adyen\Shopware\Handlers; -use Adyen\Service\Validator\DataArrayValidator; +use Adyen\Model\Checkout\PaymentCompletionDetails; +use Adyen\Model\Checkout\PaymentDetailsRequest; +use Adyen\Shopware\Util\DataArrayValidator; use Adyen\Shopware\Exception\PaymentCancelledException; use Adyen\Shopware\Exception\PaymentException; use Adyen\Shopware\Exception\PaymentFailedException; @@ -134,8 +136,11 @@ public function processResult( } // Validate the return + + $paymentDetailRequest = new PaymentDetailsRequest(['details'=>$details]); + $result = $this->paymentDetailsService->getPaymentDetails( - ['details' => $details], + $paymentDetailRequest, $transaction->getOrderTransaction() ); } diff --git a/src/Handlers/SVSGiftCardPaymentMethodHandler.php b/src/Handlers/SVSGiftCardPaymentMethodHandler.php index 5358e6c5..f3a332bd 100644 --- a/src/Handlers/SVSGiftCardPaymentMethodHandler.php +++ b/src/Handlers/SVSGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class SVSGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Handlers/SepaPaymentMethodHandler.php b/src/Handlers/SepaPaymentMethodHandler.php index c2ae97fc..928db540 100644 --- a/src/Handlers/SepaPaymentMethodHandler.php +++ b/src/Handlers/SepaPaymentMethodHandler.php @@ -27,7 +27,7 @@ class SepaPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $supportsManualCapture = true; + public static bool $supportsManualCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/TCSTestGiftCardPaymentMethodHandler.php b/src/Handlers/TCSTestGiftCardPaymentMethodHandler.php index 9b63cb73..c14a62ed 100644 --- a/src/Handlers/TCSTestGiftCardPaymentMethodHandler.php +++ b/src/Handlers/TCSTestGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class TCSTestGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Handlers/TwintPaymentMethodHandler.php b/src/Handlers/TwintPaymentMethodHandler.php index 13dc0464..d1796e7e 100644 --- a/src/Handlers/TwintPaymentMethodHandler.php +++ b/src/Handlers/TwintPaymentMethodHandler.php @@ -27,8 +27,8 @@ class TwintPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $supportsManualCapture = true; - public static $supportsPartialCapture = true; + public static bool $supportsManualCapture = true; + public static bool $supportsPartialCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/VVVGiftCardPaymentMethodHandler.php b/src/Handlers/VVVGiftCardPaymentMethodHandler.php index d877e29d..a22c2f49 100644 --- a/src/Handlers/VVVGiftCardPaymentMethodHandler.php +++ b/src/Handlers/VVVGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class VVVGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Handlers/VippsPaymentMethodHandler.php b/src/Handlers/VippsPaymentMethodHandler.php index ff65fcd3..66b0c7ab 100644 --- a/src/Handlers/VippsPaymentMethodHandler.php +++ b/src/Handlers/VippsPaymentMethodHandler.php @@ -27,8 +27,8 @@ class VippsPaymentMethodHandler extends AbstractPaymentMethodHandler { - public static $supportsManualCapture = true; - public static $supportsPartialCapture = true; + public static bool $supportsManualCapture = true; + public static bool $supportsPartialCapture = true; public static function getPaymentMethodCode() { diff --git a/src/Handlers/WebshopGiftCardPaymentMethodHandler.php b/src/Handlers/WebshopGiftCardPaymentMethodHandler.php index 2afa12f4..2d3245b7 100644 --- a/src/Handlers/WebshopGiftCardPaymentMethodHandler.php +++ b/src/Handlers/WebshopGiftCardPaymentMethodHandler.php @@ -25,6 +25,10 @@ namespace Adyen\Shopware\Handlers; +/** + * @deprecated Individual gift card payment methods were deprecated and will be removed on v4.0.0. + * Use GiftCardPaymentMethod instead. + */ class WebshopGiftCardPaymentMethodHandler extends AbstractPaymentMethodHandler { public static $isGiftCard = true; diff --git a/src/Migration/Migration1713255011AlterAdyenPayment.php b/src/Migration/Migration1713255011AlterAdyenPayment.php new file mode 100644 index 00000000..f082d850 --- /dev/null +++ b/src/Migration/Migration1713255011AlterAdyenPayment.php @@ -0,0 +1,26 @@ +executeStatement(<<{var a=n(6285),i=n(3206),o=n(8254),r=n(4690);class d extends a.Z{init(){let e=this;this._client=new o.Z,this.adyenCheckout=Promise,this.paymentMethodInstance=null,this.selectedGiftcard=null,this.initializeCheckoutComponent().then(function(){this.observeGiftcardSelection()}.bind(this)),this.adyenGiftcard=i.Z.querySelectorAll(document,".adyen-giftcard"),this.giftcardHeader=i.Z.querySelector(document,".adyen-giftcard-header"),this.giftcardComponentClose=i.Z.querySelector(document,".adyen-close-giftcard-component"),this.removeGiftcardButton=i.Z.querySelector(document,".adyen-remove-giftcard"),this.remainingBalanceField=i.Z.querySelector(document,".adyen-remaining-balance"),this.minorUnitsQuotient=adyenGiftcardsConfiguration.totalInMinorUnits/adyenGiftcardsConfiguration.totalPrice,this.giftcardDiscount=(adyenGiftcardsConfiguration.giftcardDiscount/this.minorUnitsQuotient).toFixed(2),this.remainingAmount=(adyenGiftcardsConfiguration.totalPrice-this.giftcardDiscount).toFixed(2),this.remainingGiftcardBalance=(adyenGiftcardsConfiguration.giftcardBalance/this.minorUnitsQuotient).toFixed(2),this.shoppingCartSummaryBlock=i.Z.querySelectorAll(document,".checkout-aside-summary-list"),this.offCanvasSummaryDetails=null,this.shoppingCartSummaryDetails=null,this.giftcardComponentClose.onclick=function(t){t.currentTarget.style.display="none",e.selectedGiftcard=null,e.giftcardHeader.innerHTML=" ",e.paymentMethodInstance&&e.paymentMethodInstance.unmount()},this.removeGiftcardButton.onclick=function(t){e.removeGiftcard()},window.addEventListener("DOMContentLoaded",(e=>{parseInt(adyenGiftcardsConfiguration.giftcardDiscount,10)&&this.onGiftcardSelected()}))}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,a={locale:e,clientKey:t,environment:n,amount:{currency:adyenGiftcardsConfiguration.currency,value:adyenGiftcardsConfiguration.totalInMinorUnits}};this.adyenCheckout=await AdyenCheckout(a)}observeGiftcardSelection(){let e=this;for(let t=0;t0)return;this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),r.Z.create(i.Z.querySelector(document,"#adyen-giftcard-component")),this.giftcardHeader.innerHTML=e.name,this.giftcardComponentClose.style.display="block";const t=Object.assign({},e,{showPayButton:!0,onBalanceCheck:this.handleBalanceCheck.bind(this)});try{this.paymentMethodInstance=this.adyenCheckout.create("giftcard",t),this.paymentMethodInstance.mount("#adyen-giftcard-component")}catch(e){console.log("giftcard not available")}r.Z.remove(i.Z.querySelector(document,"#adyen-giftcard-component"))}handleBalanceCheck(e,t,n){let a={};a.paymentMethod=JSON.stringify(n.paymentMethod),a.amount=JSON.stringify({currency:adyenGiftcardsConfiguration.currency,value:adyenGiftcardsConfiguration.totalInMinorUnits}),this._client.post(`${adyenGiftcardsConfiguration.checkBalanceUrl}`,JSON.stringify(a),function(e){if((e=JSON.parse(e)).hasOwnProperty("pspReference")){const t=e.transactionLimit?parseFloat(e.transactionLimit.value):parseFloat(e.balance.value);let a=t-adyenGiftcardsConfiguration.totalInMinorUnits;t>=adyenGiftcardsConfiguration.totalInMinorUnits?(this.remainingGiftcardBalance=(a/this.minorUnitsQuotient).toFixed(2),this.setGiftcardAsPaymentMethod(n,a)):(this.remainingAmount=((adyenGiftcardsConfiguration.totalInMinorUnits-t)/this.minorUnitsQuotient).toFixed(2),this.saveGiftcardStateData(n,t.toString(),0,this.selectedGiftcard.id)),this.remainingBalanceField.style.display="block";let i=adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingBalance+": "+adyenGiftcardsConfiguration.currencySymbol+this.remainingGiftcardBalance;this.remainingBalanceField.innerHTML=i}else console.error(e.resultCode),t(e.resultCode)}.bind(this))}saveGiftcardStateData(e,t,n,a){e=JSON.stringify(e),this._client.post(adyenGiftcardsConfiguration.setGiftcardUrl,JSON.stringify({stateData:e,amount:t,balance:n,paymentMethodId:a}),function(e){"paymentMethodId"in(e=JSON.parse(e))&&(this.giftcardDiscount=(t/this.minorUnitsQuotient).toFixed(2),this.remainingAmount=(adyenGiftcardsConfiguration.totalPrice-this.giftcardDiscount).toFixed(2),this.onGiftcardSelected(),r.Z.remove(document.body))}.bind(this))}setGiftcardAsPaymentMethod(e,t){this._client.patch(adyenGiftcardsConfiguration.switchContextUrl,JSON.stringify({paymentMethodId:this.selectedGiftcard.id}),function(n){this.saveGiftcardStateData(e,adyenGiftcardsConfiguration.totalInMinorUnits,t,this.selectedGiftcard.id)}.bind(this))}removeGiftcard(){r.Z.create(document.body),this._client.post(adyenGiftcardsConfiguration.removeGiftcardUrl,new FormData,function(e){if("token"in(e=JSON.parse(e))){if(this.giftcardDiscount=0,this.remainingAmount=(adyenGiftcardsConfiguration.totalPrice-this.giftcardDiscount).toFixed(2),this.shoppingCartSummaryBlock.length){let e=this.shoppingCartSummaryBlock[0].querySelectorAll(".adyen-giftcard-summary");for(let t=0;t
'+adyenGiftcardsConfiguration.currencySymbol+this.giftcardDiscount+'
'+adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingAmount+'
'+adyenGiftcardsConfiguration.currencySymbol+this.remainingAmount+"
";this.shoppingCartSummaryBlock[0].innerHTML+=e}}onGiftcardSelected(){this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),this.giftcardComponentClose.style.display="none";for(var e=0;e{console.log(e),t.setStatus("ready")}}},paymentMethodTypeHandlers:{scheme:"handler_adyen_cardspaymentmethodhandler",ideal:"handler_adyen_idealpaymentmethodhandler",klarna:"handler_adyen_klarnapaylaterpaymentmethodhandler",klarna_account:"handler_adyen_klarnaaccountpaymentmethodhandler",klarna_paynow:"handler_adyen_klarnapaynowpaymentmethodhandler",ratepay:"handler_adyen_ratepaypaymentmethodhandler",ratepay_directdebit:"handler_adyen_ratepaydirectdebitpaymentmethodhandler",sepadirectdebit:"handler_adyen_sepapaymentmethodhandler",sofort:"handler_adyen_sofortpaymentmethodhandler",paypal:"handler_adyen_paypalpaymentmethodhandler",oneclick:"handler_adyen_oneclickpaymentmethodhandler",giropay:"handler_adyen_giropaypaymentmethodhandler",applepay:"handler_adyen_applepaypaymentmethodhandler",googlepay:"handler_adyen_googlepaypaymentmethodhandler",dotpay:"handler_adyen_dotpaypaymentmethodhandler",bcmc:"handler_adyen_bancontactcardpaymentmethodhandler",bcmc_mobile:"handler_adyen_bancontactmobilepaymentmethodhandler",amazonpay:"handler_adyen_amazonpaypaymentmethodhandler",twint:"handler_adyen_twintpaymentmethodhandler",eps:"handler_adyen_epspaymentmethodhandler",swish:"handler_adyen_swishpaymentmethodhandler",alipay:"handler_adyen_alipaypaymentmethodhandler",alipay_hk:"handler_adyen_alipayhkpaymentmethodhandler",blik:"handler_adyen_blikpaymentmethodhandler",clearpay:"handler_adyen_clearpaypaymentmethodhandler",facilypay_3x:"handler_adyen_facilypay3xpaymentmethodhandler",facilypay_4x:"handler_adyen_facilypay4xpaymentmethodhandler",facilypay_6x:"handler_adyen_facilypay6xpaymentmethodhandler",facilypay_10x:"handler_adyen_facilypay10xpaymentmethodhandler",facilypay_12x:"handler_adyen_facilypay12xpaymentmethodhandler",afterpay_default:"handler_adyen_afterpaydefaultpaymentmethodhandler",trustly:"handler_adyen_trustlypaymentmethodhandler",paysafecard:"handler_adyen_paysafecardpaymentmethodhandler",givex:"handler_adyen_givexgiftcardpaymentmethodhandler",webshopgiftcard:"handler_adyen_webshopgiftcardpaymentmethodhandler",kadowereld:"handler_adyen_kadowereldgiftcardpaymentmethodhandler",tcstestgiftcard:"handler_adyen_tcstestgiftcardpaymentmethodhandler",albelligiftcard:"handler_adyen_albelligiftcardpaymentmethodhandler",bijcadeaucard:"handler_adyen_bijenkorfgiftcardpaymentmethodhandler",vvvgiftcard:"handler_adyen_vvvgiftcardpaymentmethodhandler",genericgiftcard:"handler_adyen_genericgiftcardpaymentmethodhandler",gallgall:"handler_adyen_gallgallgiftcardpaymentmethodhandler",hmlingerie:"handler_adyen_hunkemollerlingeriegiftcardpaymentmethodhandler",beautycadeaukaart:"handler_adyen_beautygiftcardpaymentmethodhandler",svs:"handler_adyen_svsgiftcardpaymentmethodhandler",fashioncheque:"handler_adyen_fashionchequegiftcardpaymentmethodhandler",decadeaukaart:"handler_adyen_decadeaukaartgiftcardpaymentmethodhandler",mbway:"handler_adyen_mbwaypaymentmethodhandler",multibanco:"handler_adyen_multibancopaymentmethodhandler",wechatpayQR:"handler_adyen_wechatpayqrpaymentmethodhandler",wechatpayWeb:"handler_adyen_wechatpaywebpaymentmethodhandler",mobilepay:"handler_adyen_mobilepaypaymentmethodhandler",vipps:"handler_adyen_vippspaymentmethodhandler",affirm:"handler_adyen_affirmpaymentmethodhandler",paybright:"handler_adyen_paybrightpaymentmethodhandler",paybybank:"handler_adyen_openbankingpaymentmethodhandler"}};class l extends a.Z{init(){this._client=new o.Z,this.selectedAdyenPaymentMethod=this.getSelectedPaymentMethodKey(),this.confirmOrderForm=i.Z.querySelector(document,"#confirmOrderForm"),this.confirmFormSubmit=i.Z.querySelector(document,'#confirmOrderForm button[type="submit"]'),this.shoppingCartSummaryBlock=i.Z.querySelectorAll(document,".checkout-aside-summary-list"),this.minorUnitsQuotient=adyenCheckoutOptions.amount/adyenCheckoutOptions.totalPrice,this.giftcardDiscount=(adyenCheckoutOptions.giftcardDiscount/this.minorUnitsQuotient).toFixed(2),this.remainingAmount=(adyenCheckoutOptions.totalPrice-this.giftcardDiscount).toFixed(2),this.responseHandler=this.handlePaymentAction,this.adyenCheckout=Promise,this.initializeCheckoutComponent().then(function(){adyenCheckoutOptions.selectedPaymentMethodPluginId===adyenCheckoutOptions.adyenPluginId&&(adyenCheckoutOptions&&adyenCheckoutOptions.paymentStatusUrl&&adyenCheckoutOptions.checkoutOrderUrl&&adyenCheckoutOptions.paymentHandleUrl?(this.selectedAdyenPaymentMethod in c.componentsWithPayButton&&this.initializeCustomPayButton(),c.updatablePaymentMethods.includes(this.selectedAdyenPaymentMethod)&&!this.stateData?this.renderPaymentComponent(this.selectedAdyenPaymentMethod):this.confirmFormSubmit.addEventListener("click",this.onConfirmOrderSubmit.bind(this))):console.error("Adyen payment configuration missing."))}.bind(this)),parseInt(adyenCheckoutOptions.payInFullWithGiftcard,10)?parseInt(adyenCheckoutOptions.adyenGiftcardSelected,10)&&this.appendGiftcardSummary():this.appendGiftcardSummary()}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n,merchantAccount:a}=adyenCheckoutConfiguration,i=adyenCheckoutOptions.paymentMethodsResponse,o={locale:e,clientKey:t,environment:n,showPayButton:this.selectedAdyenPaymentMethod in c.componentsWithPayButton,hasHolderName:!0,paymentMethodsResponse:JSON.parse(i),onAdditionalDetails:this.handleOnAdditionalDetails.bind(this),countryCode:activeShippingAddress.country,paymentMethodsConfiguration:{card:{hasHolderName:!0,clickToPayConfiguration:{merchantDisplayName:a,shopperEmail:shopperDetails.shopperEmail}}}};this.adyenCheckout=await AdyenCheckout(o)}handleOnAdditionalDetails(e){this._client.post(`${adyenCheckoutOptions.paymentDetailsUrl}`,JSON.stringify({orderId:this.orderId,stateData:JSON.stringify(e.data)}),function(e){200===this._client._request.status?this.responseHandler(e):location.href=this.errorUrl.toString()}.bind(this))}onConfirmOrderSubmit(e){const t=i.Z.querySelector(document,"#confirmOrderForm");if(!t.checkValidity())return;e.preventDefault(),r.Z.create(document.body);const n=s.Z.serialize(t);this.confirmOrder(n)}renderPaymentComponent(e){if("oneclick"===e)return void this.renderStoredPaymentMethodComponents();let t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((function(t){return t.type===e}));if(0===t.length)return void("test"===this.adyenCheckout.options.environment&&console.error("Payment method configuration not found. ",e));let n=t[0];this.mountPaymentComponent(n,!1)}renderStoredPaymentMethodComponents(){this.adyenCheckout.paymentMethodsResponse.storedPaymentMethods.forEach((e=>{let t=`[data-adyen-stored-payment-method-id="${e.id}"]`;this.mountPaymentComponent(e,!0,t)})),this.hideStorePaymentMethodComponents();let e=null;i.Z.querySelectorAll(document,"[name=adyenStoredPaymentMethodId]").forEach((t=>{e||(e=t.value),t.addEventListener("change",this.showSelectedStoredPaymentMethod.bind(this))})),this.showSelectedStoredPaymentMethod(null,e)}showSelectedStoredPaymentMethod(e,t=null){this.hideStorePaymentMethodComponents();let n=`[data-adyen-stored-payment-method-id="${t=e?e.target.value:t}"]`;i.Z.querySelector(document,n).style.display="block"}hideStorePaymentMethodComponents(){i.Z.querySelectorAll(document,".stored-payment-component").forEach((e=>{e.style.display="none"}))}confirmOrder(e,t={}){const n=adyenCheckoutOptions.orderId;e.set("affiliateCode",adyenCheckoutOptions.affiliateCode),e.set("campaignCode",adyenCheckoutOptions.campaignCode),n?this.updatePayment(e,n,t):this.createOrder(e,t)}updatePayment(e,t,n){e.set("orderId",t),this._client.post(adyenCheckoutOptions.updatePaymentUrl,e,this.afterSetPayment.bind(this,n))}createOrder(e,t){parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&!parseInt(adyenCheckoutOptions.payInFullWithGiftcard,10)?this._client.post(adyenCheckoutOptions.createOrderUrl,JSON.stringify({orderAmount:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency}),function(n){const a=JSON.parse(n);"Success"===a.resultCode&&(t=Object.assign(t,{order:a})),this._client.post(adyenCheckoutOptions.checkoutOrderUrl,e,this.afterCreateOrder.bind(this,t))}.bind(this)):this._client.post(adyenCheckoutOptions.checkoutOrderUrl,e,this.afterCreateOrder.bind(this,t))}afterCreateOrder(e={},t){let n;try{n=JSON.parse(t)}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}this.orderId=n.id,this.finishUrl=new URL(location.origin+adyenCheckoutOptions.paymentFinishUrl),this.finishUrl.searchParams.set("orderId",n.id),this.errorUrl=new URL(location.origin+adyenCheckoutOptions.paymentErrorUrl),this.errorUrl.searchParams.set("orderId",n.id);let a={orderId:this.orderId,finishUrl:this.finishUrl.toString(),errorUrl:this.errorUrl.toString()};for(const t in e)a[t]=e[t];this._client.post(adyenCheckoutOptions.paymentHandleUrl,JSON.stringify(a),this.afterPayOrder.bind(this,this.orderId))}afterSetPayment(e={},t){try{JSON.parse(t).success&&this.afterCreateOrder(e,JSON.stringify({id:adyenCheckoutOptions.orderId}))}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}}afterPayOrder(e,t){try{t=JSON.parse(t),this.returnUrl=t.redirectUrl}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}this.returnUrl===this.errorUrl.toString()&&(location.href=this.returnUrl);try{this._client.post(`${adyenCheckoutOptions.paymentStatusUrl}`,JSON.stringify({orderId:e}),this.responseHandler.bind(this))}catch(e){console.log(e)}}handlePaymentAction(e){try{const t=JSON.parse(e);if((t.isFinal||"voucher"===t.action.type)&&(location.href=this.returnUrl),t.action){const e={};"threeDS2"===t.action.type&&(e.challengeWindowSize="05"),this.adyenCheckout.createFromAction(t.action,e).mount("[data-adyen-payment-action-container]");if(["threeDS2","qrCode"].includes(t.action.type))if(window.jQuery)$("[data-adyen-payment-action-modal]").modal({show:!0});else new bootstrap.Modal(document.getElementById("adyen-payment-action-modal"),{keyboard:!1}).show()}}catch(e){console.log(e)}}initializeCustomPayButton(){const e=c.componentsWithPayButton[this.selectedAdyenPaymentMethod];this.completePendingPayment(this.selectedAdyenPaymentMethod,e);let t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((e=>e.type===this.selectedAdyenPaymentMethod));if(t.length<1&&"googlepay"===this.selectedAdyenPaymentMethod&&(t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((e=>"paywithgoogle"===e.type))),t.length<1)return;let n=t[0];if(!adyenCheckoutOptions.amount)return void console.error("Failed to fetch Cart/Order total amount.");if(e.prePayRedirect)return void this.renderPrePaymentButton(e,n);const a=Object.assign(e.extra,n,{amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onClick:(t,n)=>{if(!e.onClick(t,n,this))return!1;r.Z.create(document.body)},onSubmit:function(t,n){if(t.isValid){let a={stateData:JSON.stringify(t.data)},i=s.Z.serialize(this.confirmOrderForm);"responseHandler"in e&&(this.responseHandler=e.responseHandler.bind(n,this)),this.confirmOrder(i,a)}else n.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",t)}.bind(this),onCancel:(t,n)=>{r.Z.remove(document.body),e.onCancel(t,n,this)},onError:(t,n)=>{"PayPal"===n.props.name&&"CANCEL"===t.name&&this._client.post(`${adyenCheckoutOptions.cancelOrderTransactionUrl}`,JSON.stringify({orderId:this.orderId})),r.Z.remove(document.body),e.onError(t,n,this),console.log(t)}}),i=this.adyenCheckout.create(n.type,a);try{"isAvailable"in i?i.isAvailable().then(function(){this.mountCustomPayButton(i)}.bind(this)).catch((e=>{console.log(n.type+" is not available",e)})):this.mountCustomPayButton(i)}catch(e){console.log(e)}}renderPrePaymentButton(e,t){"amazonpay"===t.type&&(e.extra=this.setAddressDetails(e.extra));const n=Object.assign(e.extra,t,{configuration:t.configuration,amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},onClick:(t,n)=>{if(!e.onClick(t,n,this))return!1;r.Z.create(document.body)},onError:(t,n)=>{r.Z.remove(document.body),e.onError(t,n,this),console.log(t)}});let a=this.adyenCheckout.create(t.type,n);this.mountCustomPayButton(a)}completePendingPayment(e,t){const n=new URL(location.href);if(n.searchParams.has(t.sessionKey)){r.Z.create(document.body);const a=this.adyenCheckout.create(e,{[t.sessionKey]:n.searchParams.get(t.sessionKey),showOrderButton:!1,onSubmit:function(e,t){if(e.isValid){let t={stateData:JSON.stringify(e.data)},n=s.Z.serialize(this.confirmOrderForm);this.confirmOrder(n,t)}}.bind(this)});this.mountCustomPayButton(a),a.submit()}}getSelectedPaymentMethodKey(){return Object.keys(c.paymentMethodTypeHandlers).find((e=>c.paymentMethodTypeHandlers[e]===adyenCheckoutOptions.selectedPaymentMethodHandler))}mountCustomPayButton(e){let t=document.querySelector("#confirmOrderForm");if(t){let n=t.querySelector("button[type=submit]");if(n&&!n.disabled){let a=document.createElement("div");a.id="adyen-confirm-button",a.setAttribute("data-adyen-confirm-button",""),t.appendChild(a),e.mount(a),n.remove()}}}mountPaymentComponent(e,t=!1,n=null){const a=Object.assign({},e,{data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onSubmit:function(e,t){if(e.isValid){let t={stateData:JSON.stringify(e.data)},n=s.Z.serialize(this.confirmOrderForm);r.Z.create(document.body),this.confirmOrder(n,t)}else t.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",e)}.bind(this)});!t&&"scheme"===e.type&&adyenCheckoutOptions.displaySaveCreditCardOption&&(a.enableStoreDetails=!0);let o=t?n:"#"+this.el.id;try{const t=this.adyenCheckout.create(e.type,a);t.mount(o),this.confirmFormSubmit.addEventListener("click",function(e){i.Z.querySelector(document,"#confirmOrderForm").checkValidity()&&(e.preventDefault(),this.el.parentNode.scrollIntoView({behavior:"smooth",block:"start"}),t.submit())}.bind(this))}catch(t){return console.error(e.type,t),!1}}appendGiftcardSummary(){if(parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&this.shoppingCartSummaryBlock.length){let e='
'+adyenCheckoutOptions.translationAdyenGiftcardDiscount+'
'+adyenCheckoutOptions.currencySymbol+this.giftcardDiscount+'
'+adyenCheckoutOptions.translationAdyenGiftcardRemainingAmount+'
'+adyenCheckoutOptions.currencySymbol+this.remainingAmount+"
";this.shoppingCartSummaryBlock[0].innerHTML+=e}}setAddressDetails(e){return""!==activeShippingAddress.phoneNumber?e.addressDetails={name:shopperDetails.firstName+" "+shopperDetails.lastName,addressLine1:activeShippingAddress.street,city:activeShippingAddress.city,postalCode:activeShippingAddress.postalCode,countryCode:activeShippingAddress.country,phoneNumber:activeShippingAddress.phoneNumber}:e.productType="PayOnly",e}}class h extends a.Z{init(){this._client=new o.Z,this.adyenCheckout=Promise,this.initializeCheckoutComponent().bind(this)}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,{currency:a,values:i,backgroundUrl:o,logoUrl:r,name:d,description:s,url:c}=adyenGivingConfiguration,l={locale:e,clientKey:t,environment:n},h={amounts:{currency:a,values:i.split(",").map((e=>Number(e)))},backgroundUrl:o,logoUrl:r,description:s,name:d,url:c,showCancelButton:!0,onDonate:this.handleOnDonate.bind(this),onCancel:this.handleOnCancel.bind(this)};this.adyenCheckout=await AdyenCheckout(l),this.adyenCheckout.create("donation",h).mount("#donation-container")}handleOnDonate(e,t){const n=adyenGivingConfiguration.orderId;let a={stateData:JSON.stringify(e.data),orderId:n};a.returnUrl=window.location.href,this._client.post(`${adyenGivingConfiguration.donationEndpointUrl}`,JSON.stringify({...a}),function(e){200!==this._client._request.status?t.setStatus("error"):t.setStatus("success")}.bind(this))}handleOnCancel(){let e=adyenGivingConfiguration.continueActionUrl;window.location=e}}class y extends a.Z{init(){this.adyenCheckout=Promise,this.initializeCheckoutComponent().bind(this)}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,{action:a}=adyenSuccessActionConfiguration,i={locale:e,clientKey:t,environment:n};this.adyenCheckout=await AdyenCheckout(i),this.adyenCheckout.createFromAction(JSON.parse(a)).mount("#success-action-container")}}const m=window.PluginManager;m.register("CartPlugin",d,"#adyen-giftcards-container"),m.register("ConfirmOrderPlugin",l,"#adyen-payment-checkout-mask"),m.register("AdyenGivingPlugin",h,"#adyen-giving-container"),m.register("AdyenSuccessAction",y,"#adyen-success-action-container")}},e=>{e.O(0,["vendor-node","vendor-shared"],(()=>{return t=7815,e(e.s=t);var t}));e.O()}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([["adyen-payment-shopware6"],{7815:(e,t,n)=>{var a=n(6285),i=n(3206),o=n(8254),r=n(4690);class d extends a.Z{init(){let e=this;this._client=new o.Z,this.adyenCheckout=Promise,this.paymentMethodInstance=null,this.selectedGiftcard=null,this.initializeCheckoutComponent().then(function(){this.observeGiftcardSelection()}.bind(this)),this.adyenGiftcardDropDown=i.Z.querySelectorAll(document,"#giftcardDropdown"),this.adyenGiftcard=i.Z.querySelectorAll(document,".adyen-giftcard"),this.giftcardHeader=i.Z.querySelector(document,".adyen-giftcard-header"),this.giftcardItem=i.Z.querySelector(document,".adyen-giftcard-item"),this.giftcardComponentClose=i.Z.querySelector(document,".adyen-close-giftcard-component"),this.minorUnitsQuotient=adyenGiftcardsConfiguration.totalInMinorUnits/adyenGiftcardsConfiguration.totalPrice,this.giftcardDiscount=adyenGiftcardsConfiguration.giftcardDiscount,this.remainingAmount=(adyenGiftcardsConfiguration.totalPrice-this.giftcardDiscount).toFixed(2),this.remainingGiftcardBalance=(adyenGiftcardsConfiguration.giftcardBalance/this.minorUnitsQuotient).toFixed(2),this.shoppingCartSummaryBlock=i.Z.querySelectorAll(document,".checkout-aside-summary-list"),this.offCanvasSummaryDetails=null,this.shoppingCartSummaryDetails=null,this.giftcardComponentClose.onclick=function(t){t.currentTarget.style.display="none",e.selectedGiftcard=null,e.giftcardItem.innerHTML="",e.giftcardHeader.innerHTML=" ",e.paymentMethodInstance&&e.paymentMethodInstance.unmount()},document.getElementById("showGiftcardButton").addEventListener("click",(function(){this.style.display="none",document.getElementById("giftcardDropdown").style.display="block"})),window.addEventListener("DOMContentLoaded",(()=>{document.getElementById("giftcardsContainer").addEventListener("click",(e=>{if(e.target.classList.contains("adyen-remove-giftcard")){const t=e.target.getAttribute("dataid");this.removeGiftcard(t)}}))})),window.addEventListener("DOMContentLoaded",(e=>{parseInt(adyenGiftcardsConfiguration.giftcardDiscount,10)&&this.fetchRedeemedGiftcards()}))}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,a={locale:e,clientKey:t,environment:n,amount:{currency:adyenGiftcardsConfiguration.currency,value:adyenGiftcardsConfiguration.totalInMinorUnits}};this.adyenCheckout=await AdyenCheckout(a)}observeGiftcardSelection(){let e=this,t=document.getElementById("giftcardDropdown"),n=document.querySelector(".btn-outline-info");t.addEventListener("change",(function(){t.value&&(e.selectedGiftcard=JSON.parse(event.currentTarget.options[event.currentTarget.selectedIndex].dataset.giftcard),e.mountGiftcardComponent(e.selectedGiftcard),t.value="",n.style.display="none")}))}mountGiftcardComponent(e){this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),this.giftcardItem.innerHTML="",r.Z.create(i.Z.querySelector(document,"#adyen-giftcard-component"));var t=document.createElement("img");t.src="https://checkoutshopper-live.adyen.com/checkoutshopper/images/logos/"+e.brand+".svg",t.classList.add("adyen-giftcard-logo"),this.giftcardItem.insertBefore(t,this.giftcardItem.firstChild),this.giftcardHeader.innerHTML=e.name,this.giftcardComponentClose.style.display="block";const n=Object.assign({},e,{showPayButton:!0,onBalanceCheck:this.handleBalanceCheck.bind(this,e)});try{this.paymentMethodInstance=this.adyenCheckout.create("giftcard",n),this.paymentMethodInstance.mount("#adyen-giftcard-component")}catch(e){console.log("giftcard not available")}r.Z.remove(i.Z.querySelector(document,"#adyen-giftcard-component"))}handleBalanceCheck(e,t,n,a){let i={};i.paymentMethod=JSON.stringify(a.paymentMethod),i.amount=JSON.stringify({currency:adyenGiftcardsConfiguration.currency,value:adyenGiftcardsConfiguration.totalInMinorUnits}),this._client.post(`${adyenGiftcardsConfiguration.checkBalanceUrl}`,JSON.stringify(i),function(t){if((t=JSON.parse(t)).hasOwnProperty("pspReference")){const n=t.transactionLimit?parseFloat(t.transactionLimit.value):parseFloat(t.balance.value);a.giftcard={currency:adyenGiftcardsConfiguration.currency,value:(n/this.minorUnitsQuotient).toFixed(2),title:e.name},this.saveGiftcardStateData(a)}else n(t.resultCode)}.bind(this))}fetchRedeemedGiftcards(){this._client.get(adyenGiftcardsConfiguration.fetchRedeemedGiftcardsUrl,function(e){e=JSON.parse(e);let t=document.getElementById("giftcardsContainer"),n=document.querySelector(".btn-outline-info");t.innerHTML="",e.redeemedGiftcards.giftcards.forEach((function(e){let n=parseFloat(e.deductedAmount);n=n.toFixed(2);let a=adyenGiftcardsConfiguration.translationAdyenGiftcardDeductedBalance+": "+adyenGiftcardsConfiguration.currencySymbol+n,i=document.createElement("div");var o=document.createElement("img");o.src="https://checkoutshopper-live.adyen.com/checkoutshopper/images/logos/"+e.brand+".svg",o.classList.add("adyen-giftcard-logo");let r=document.createElement("a");r.href="#",r.textContent=adyenGiftcardsConfiguration.translationAdyenGiftcardRemove,r.setAttribute("dataid",e.stateDataId),r.classList.add("adyen-remove-giftcard"),r.style.display="block",i.appendChild(o),i.innerHTML+=`${e.title}`,i.appendChild(r),i.innerHTML+=`

${a}


`,t.appendChild(i)})),this.remainingAmount=e.redeemedGiftcards.remainingAmount,this.giftcardDiscount=e.redeemedGiftcards.totalDiscount,this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),this.giftcardComponentClose.style.display="none",this.giftcardItem.innerHTML="",this.giftcardHeader.innerHTML=" ",this.appendGiftcardSummary(),this.remainingAmount>0?n.style.display="block":(this.adyenGiftcardDropDown.length>0&&(this.adyenGiftcardDropDown[0].style.display="none"),n.style.display="none");document.getElementById("giftcardsContainer")}.bind(this))}saveGiftcardStateData(e){e=JSON.stringify(e),this._client.post(adyenGiftcardsConfiguration.setGiftcardUrl,JSON.stringify({stateData:e}),function(e){"token"in(e=JSON.parse(e))&&(this.fetchRedeemedGiftcards(),r.Z.remove(document.body))}.bind(this))}removeGiftcard(e){r.Z.create(document.body),this._client.post(adyenGiftcardsConfiguration.removeGiftcardUrl,JSON.stringify({stateDataId:e}),(e=>{"token"in(e=JSON.parse(e))&&(this.fetchRedeemedGiftcards(),r.Z.remove(document.body))}))}appendGiftcardSummary(){if(this.shoppingCartSummaryBlock.length){let e=this.shoppingCartSummaryBlock[0].querySelectorAll(".adyen-giftcard-summary");for(let t=0;t
'+adyenGiftcardsConfiguration.currencySymbol+e+'
'+adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingAmount+'
'+adyenGiftcardsConfiguration.currencySymbol+t+"
";this.shoppingCartSummaryBlock[0].innerHTML+=n}}}var s=n(207);const c={updatablePaymentMethods:["scheme","ideal","sepadirectdebit","oneclick","dotpay","bcmc","bcmc_mobile","blik","eps","facilypay_3x","facilypay_4x","facilypay_6x","facilypay_10x","facilypay_12x","afterpay_default","ratepay","ratepay_directdebit","giftcard","paybright","affirm","multibanco","mbway","vipps","mobilepay","wechatpayQR","wechatpayWeb","paybybank"],componentsWithPayButton:{applepay:{extra:{},onClick(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)}},googlepay:{extra:{buttonSizeMode:"fill"},onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)},onError:function(e,t,n){"CANCELED"!==e.statusCode&&("statusMessage"in e?console.log(e.statusMessage):console.log(e.statusCode))}},paypal:{extra:{},onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()},onError:function(e,t,n){t.setStatus("ready"),window.location.href=n.errorUrl.toString()},onCancel:function(e,t,n){t.setStatus("ready"),window.location.href=n.errorUrl.toString()},responseHandler:function(e,t){try{(t=JSON.parse(t)).isFinal&&(location.href=e.returnUrl),this.handleAction(t.action)}catch(e){console.error(e)}}},amazonpay:{extra:{productType:"PayAndShip",checkoutMode:"ProcessOrder",returnUrl:location.href},prePayRedirect:!0,sessionKey:"amazonCheckoutSessionId",onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)},onError:(e,t)=>{console.log(e),t.setStatus("ready")}}},paymentMethodTypeHandlers:{scheme:"handler_adyen_cardspaymentmethodhandler",ideal:"handler_adyen_idealpaymentmethodhandler",klarna:"handler_adyen_klarnapaylaterpaymentmethodhandler",klarna_account:"handler_adyen_klarnaaccountpaymentmethodhandler",klarna_paynow:"handler_adyen_klarnapaynowpaymentmethodhandler",ratepay:"handler_adyen_ratepaypaymentmethodhandler",ratepay_directdebit:"handler_adyen_ratepaydirectdebitpaymentmethodhandler",sepadirectdebit:"handler_adyen_sepapaymentmethodhandler",sofort:"handler_adyen_sofortpaymentmethodhandler",paypal:"handler_adyen_paypalpaymentmethodhandler",oneclick:"handler_adyen_oneclickpaymentmethodhandler",giropay:"handler_adyen_giropaypaymentmethodhandler",applepay:"handler_adyen_applepaypaymentmethodhandler",googlepay:"handler_adyen_googlepaypaymentmethodhandler",dotpay:"handler_adyen_dotpaypaymentmethodhandler",bcmc:"handler_adyen_bancontactcardpaymentmethodhandler",bcmc_mobile:"handler_adyen_bancontactmobilepaymentmethodhandler",amazonpay:"handler_adyen_amazonpaypaymentmethodhandler",twint:"handler_adyen_twintpaymentmethodhandler",eps:"handler_adyen_epspaymentmethodhandler",swish:"handler_adyen_swishpaymentmethodhandler",alipay:"handler_adyen_alipaypaymentmethodhandler",alipay_hk:"handler_adyen_alipayhkpaymentmethodhandler",blik:"handler_adyen_blikpaymentmethodhandler",clearpay:"handler_adyen_clearpaypaymentmethodhandler",facilypay_3x:"handler_adyen_facilypay3xpaymentmethodhandler",facilypay_4x:"handler_adyen_facilypay4xpaymentmethodhandler",facilypay_6x:"handler_adyen_facilypay6xpaymentmethodhandler",facilypay_10x:"handler_adyen_facilypay10xpaymentmethodhandler",facilypay_12x:"handler_adyen_facilypay12xpaymentmethodhandler",afterpay_default:"handler_adyen_afterpaydefaultpaymentmethodhandler",trustly:"handler_adyen_trustlypaymentmethodhandler",paysafecard:"handler_adyen_paysafecardpaymentmethodhandler",giftcard:"handler_adyen_giftcardpaymentmethodhandler",mbway:"handler_adyen_mbwaypaymentmethodhandler",multibanco:"handler_adyen_multibancopaymentmethodhandler",wechatpayQR:"handler_adyen_wechatpayqrpaymentmethodhandler",wechatpayWeb:"handler_adyen_wechatpaywebpaymentmethodhandler",mobilepay:"handler_adyen_mobilepaypaymentmethodhandler",vipps:"handler_adyen_vippspaymentmethodhandler",affirm:"handler_adyen_affirmpaymentmethodhandler",paybright:"handler_adyen_paybrightpaymentmethodhandler",paybybank:"handler_adyen_openbankingpaymentmethodhandler"}};class l extends a.Z{init(){this._client=new o.Z,this._client=new o.Z,this.selectedAdyenPaymentMethod=this.getSelectedPaymentMethodKey(),this.confirmOrderForm=i.Z.querySelector(document,"#confirmOrderForm"),this.confirmFormSubmit=i.Z.querySelector(document,'#confirmOrderForm button[type="submit"]'),this.shoppingCartSummaryBlock=i.Z.querySelectorAll(document,".checkout-aside-summary-list"),this.minorUnitsQuotient=adyenCheckoutOptions.amount/adyenCheckoutOptions.totalPrice,this.giftcardDiscount=adyenCheckoutOptions.giftcardDiscount,this.remainingAmount=adyenCheckoutOptions.totalPrice-this.giftcardDiscount,this.responseHandler=this.handlePaymentAction,this.adyenCheckout=Promise,this.initializeCheckoutComponent().then(function(){adyenCheckoutOptions.selectedPaymentMethodPluginId===adyenCheckoutOptions.adyenPluginId&&(adyenCheckoutOptions&&adyenCheckoutOptions.paymentStatusUrl&&adyenCheckoutOptions.checkoutOrderUrl&&adyenCheckoutOptions.paymentHandleUrl?(this.selectedAdyenPaymentMethod in c.componentsWithPayButton&&this.initializeCustomPayButton(),c.updatablePaymentMethods.includes(this.selectedAdyenPaymentMethod)&&!this.stateData?this.renderPaymentComponent(this.selectedAdyenPaymentMethod):this.confirmFormSubmit.addEventListener("click",this.onConfirmOrderSubmit.bind(this))):console.error("Adyen payment configuration missing."))}.bind(this)),adyenCheckoutOptions.payInFullWithGiftcard>0?parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&this.appendGiftcardSummary():this.appendGiftcardSummary()}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n,merchantAccount:a}=adyenCheckoutConfiguration,i=adyenCheckoutOptions.paymentMethodsResponse,o={locale:e,clientKey:t,environment:n,showPayButton:this.selectedAdyenPaymentMethod in c.componentsWithPayButton,hasHolderName:!0,paymentMethodsResponse:JSON.parse(i),onAdditionalDetails:this.handleOnAdditionalDetails.bind(this),countryCode:activeShippingAddress.country,paymentMethodsConfiguration:{card:{hasHolderName:!0,clickToPayConfiguration:{merchantDisplayName:a,shopperEmail:shopperDetails.shopperEmail}}}};this.adyenCheckout=await AdyenCheckout(o)}handleOnAdditionalDetails(e){this._client.post(`${adyenCheckoutOptions.paymentDetailsUrl}`,JSON.stringify({orderId:this.orderId,stateData:JSON.stringify(e.data)}),function(e){200===this._client._request.status?this.responseHandler(e):location.href=this.errorUrl.toString()}.bind(this))}onConfirmOrderSubmit(e){const t=i.Z.querySelector(document,"#confirmOrderForm");if(!t.checkValidity())return;e.preventDefault(),r.Z.create(document.body);const n=s.Z.serialize(t);this.confirmOrder(n)}renderPaymentComponent(e){if("oneclick"===e)return void this.renderStoredPaymentMethodComponents();if("giftcard"===e)return;let t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((function(t){return t.type===e}));if(0===t.length)return void("test"===this.adyenCheckout.options.environment&&console.error("Payment method configuration not found. ",e));let n=t[0];this.mountPaymentComponent(n,!1)}renderStoredPaymentMethodComponents(){this.adyenCheckout.paymentMethodsResponse.storedPaymentMethods.forEach((e=>{let t=`[data-adyen-stored-payment-method-id="${e.id}"]`;this.mountPaymentComponent(e,!0,t)})),this.hideStorePaymentMethodComponents();let e=null;i.Z.querySelectorAll(document,"[name=adyenStoredPaymentMethodId]").forEach((t=>{e||(e=t.value),t.addEventListener("change",this.showSelectedStoredPaymentMethod.bind(this))})),this.showSelectedStoredPaymentMethod(null,e)}showSelectedStoredPaymentMethod(e,t=null){this.hideStorePaymentMethodComponents();let n=`[data-adyen-stored-payment-method-id="${t=e?e.target.value:t}"]`;i.Z.querySelector(document,n).style.display="block"}hideStorePaymentMethodComponents(){i.Z.querySelectorAll(document,".stored-payment-component").forEach((e=>{e.style.display="none"}))}confirmOrder(e,t={}){const n=adyenCheckoutOptions.orderId;e.set("affiliateCode",adyenCheckoutOptions.affiliateCode),e.set("campaignCode",adyenCheckoutOptions.campaignCode),n?this.updatePayment(e,n,t):this.createOrder(e,t)}updatePayment(e,t,n){e.set("orderId",t),this._client.post(adyenCheckoutOptions.updatePaymentUrl,e,this.afterSetPayment.bind(this,n))}createOrder(e,t){this._client.post(adyenCheckoutOptions.checkoutOrderUrl,e,this.afterCreateOrder.bind(this,t))}afterCreateOrder(e={},t){let n;try{n=JSON.parse(t)}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}this.orderId=n.id,this.finishUrl=new URL(location.origin+adyenCheckoutOptions.paymentFinishUrl),this.finishUrl.searchParams.set("orderId",n.id),this.errorUrl=new URL(location.origin+adyenCheckoutOptions.paymentErrorUrl),this.errorUrl.searchParams.set("orderId",n.id);let a={orderId:this.orderId,finishUrl:this.finishUrl.toString(),errorUrl:this.errorUrl.toString()};for(const t in e)a[t]=e[t];this._client.post(adyenCheckoutOptions.paymentHandleUrl,JSON.stringify(a),this.afterPayOrder.bind(this,this.orderId))}afterSetPayment(e={},t){try{JSON.parse(t).success&&this.afterCreateOrder(e,JSON.stringify({id:adyenCheckoutOptions.orderId}))}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}}afterPayOrder(e,t){try{t=JSON.parse(t),this.returnUrl=t.redirectUrl}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}this.returnUrl===this.errorUrl.toString()&&(location.href=this.returnUrl);try{this._client.post(`${adyenCheckoutOptions.paymentStatusUrl}`,JSON.stringify({orderId:e}),this.responseHandler.bind(this))}catch(e){console.log(e)}}handlePaymentAction(e){try{const t=JSON.parse(e);if((t.isFinal||"voucher"===t.action.type)&&(location.href=this.returnUrl),t.action){const e={};"threeDS2"===t.action.type&&(e.challengeWindowSize="05"),this.adyenCheckout.createFromAction(t.action,e).mount("[data-adyen-payment-action-container]");if(["threeDS2","qrCode"].includes(t.action.type))if(window.jQuery)$("[data-adyen-payment-action-modal]").modal({show:!0});else new bootstrap.Modal(document.getElementById("adyen-payment-action-modal"),{keyboard:!1}).show()}}catch(e){console.log(e)}}initializeCustomPayButton(){const e=c.componentsWithPayButton[this.selectedAdyenPaymentMethod];this.completePendingPayment(this.selectedAdyenPaymentMethod,e);let t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((e=>e.type===this.selectedAdyenPaymentMethod));if(t.length<1&&"googlepay"===this.selectedAdyenPaymentMethod&&(t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((e=>"paywithgoogle"===e.type))),t.length<1)return;let n=t[0];if(!adyenCheckoutOptions.amount)return void console.error("Failed to fetch Cart/Order total amount.");if(e.prePayRedirect)return void this.renderPrePaymentButton(e,n);const a=Object.assign(e.extra,n,{amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onClick:(t,n)=>{if(!e.onClick(t,n,this))return!1;r.Z.create(document.body)},onSubmit:function(t,n){if(t.isValid){let a={stateData:JSON.stringify(t.data)},i=s.Z.serialize(this.confirmOrderForm);"responseHandler"in e&&(this.responseHandler=e.responseHandler.bind(n,this)),this.confirmOrder(i,a)}else n.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",t)}.bind(this),onCancel:(t,n)=>{r.Z.remove(document.body),e.onCancel(t,n,this)},onError:(t,n)=>{"PayPal"===n.props.name&&"CANCEL"===t.name&&this._client.post(`${adyenCheckoutOptions.cancelOrderTransactionUrl}`,JSON.stringify({orderId:this.orderId})),r.Z.remove(document.body),e.onError(t,n,this),console.log(t)}}),i=this.adyenCheckout.create(n.type,a);try{"isAvailable"in i?i.isAvailable().then(function(){this.mountCustomPayButton(i)}.bind(this)).catch((e=>{console.log(n.type+" is not available",e)})):this.mountCustomPayButton(i)}catch(e){console.log(e)}}renderPrePaymentButton(e,t){"amazonpay"===t.type&&(e.extra=this.setAddressDetails(e.extra));const n=Object.assign(e.extra,t,{configuration:t.configuration,amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},onClick:(t,n)=>{if(!e.onClick(t,n,this))return!1;r.Z.create(document.body)},onError:(t,n)=>{r.Z.remove(document.body),e.onError(t,n,this),console.log(t)}});let a=this.adyenCheckout.create(t.type,n);this.mountCustomPayButton(a)}completePendingPayment(e,t){const n=new URL(location.href);if(n.searchParams.has(t.sessionKey)){r.Z.create(document.body);const a=this.adyenCheckout.create(e,{[t.sessionKey]:n.searchParams.get(t.sessionKey),showOrderButton:!1,onSubmit:function(e,t){if(e.isValid){let t={stateData:JSON.stringify(e.data)},n=s.Z.serialize(this.confirmOrderForm);this.confirmOrder(n,t)}}.bind(this)});this.mountCustomPayButton(a),a.submit()}}getSelectedPaymentMethodKey(){return Object.keys(c.paymentMethodTypeHandlers).find((e=>c.paymentMethodTypeHandlers[e]===adyenCheckoutOptions.selectedPaymentMethodHandler))}mountCustomPayButton(e){let t=document.querySelector("#confirmOrderForm");if(t){let n=t.querySelector("button[type=submit]");if(n&&!n.disabled){let a=document.createElement("div");a.id="adyen-confirm-button",a.setAttribute("data-adyen-confirm-button",""),t.appendChild(a),e.mount(a),n.remove()}}}mountPaymentComponent(e,t=!1,n=null){const a=Object.assign({},e,{data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onSubmit:function(e,t){if(e.isValid){let t={stateData:JSON.stringify(e.data)},n=s.Z.serialize(this.confirmOrderForm);r.Z.create(document.body),this.confirmOrder(n,t)}else t.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",e)}.bind(this)});!t&&"scheme"===e.type&&adyenCheckoutOptions.displaySaveCreditCardOption&&(a.enableStoreDetails=!0);let o=t?n:"#"+this.el.id;try{const t=this.adyenCheckout.create(e.type,a);t.mount(o),this.confirmFormSubmit.addEventListener("click",function(e){i.Z.querySelector(document,"#confirmOrderForm").checkValidity()&&(e.preventDefault(),this.el.parentNode.scrollIntoView({behavior:"smooth",block:"start"}),t.submit())}.bind(this))}catch(t){return console.error(e.type,t),!1}}appendGiftcardSummary(){if(parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&this.shoppingCartSummaryBlock.length){let e=parseFloat(this.giftcardDiscount).toFixed(2),t=parseFloat(this.remainingAmount).toFixed(2),n='
'+adyenCheckoutOptions.translationAdyenGiftcardDiscount+'
'+adyenCheckoutOptions.currencySymbol+e+'
'+adyenCheckoutOptions.translationAdyenGiftcardRemainingAmount+'
'+adyenCheckoutOptions.currencySymbol+t+"
";this.shoppingCartSummaryBlock[0].innerHTML+=n}}setAddressDetails(e){return""!==activeShippingAddress.phoneNumber?e.addressDetails={name:shopperDetails.firstName+" "+shopperDetails.lastName,addressLine1:activeShippingAddress.street,city:activeShippingAddress.city,postalCode:activeShippingAddress.postalCode,countryCode:activeShippingAddress.country,phoneNumber:activeShippingAddress.phoneNumber}:e.productType="PayOnly",e}}class h extends a.Z{init(){this._client=new o.Z,this.adyenCheckout=Promise,this.initializeCheckoutComponent().bind(this)}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,{currency:a,values:i,backgroundUrl:o,logoUrl:r,name:d,description:s,url:c}=adyenGivingConfiguration,l={locale:e,clientKey:t,environment:n},h={amounts:{currency:a,values:i.split(",").map((e=>Number(e)))},backgroundUrl:o,logoUrl:r,description:s,name:d,url:c,showCancelButton:!0,onDonate:this.handleOnDonate.bind(this),onCancel:this.handleOnCancel.bind(this)};this.adyenCheckout=await AdyenCheckout(l),this.adyenCheckout.create("donation",h).mount("#donation-container")}handleOnDonate(e,t){const n=adyenGivingConfiguration.orderId;let a={stateData:JSON.stringify(e.data),orderId:n};a.returnUrl=window.location.href,this._client.post(`${adyenGivingConfiguration.donationEndpointUrl}`,JSON.stringify({...a}),function(e){200!==this._client._request.status?t.setStatus("error"):t.setStatus("success")}.bind(this))}handleOnCancel(){let e=adyenGivingConfiguration.continueActionUrl;window.location=e}}class y extends a.Z{init(){this.adyenCheckout=Promise,this.initializeCheckoutComponent().bind(this)}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,{action:a}=adyenSuccessActionConfiguration,i={locale:e,clientKey:t,environment:n};this.adyenCheckout=await AdyenCheckout(i),this.adyenCheckout.createFromAction(JSON.parse(a)).mount("#success-action-container")}}const m=window.PluginManager;m.register("CartPlugin",d,"#adyen-giftcards-container"),m.register("ConfirmOrderPlugin",l,"#adyen-payment-checkout-mask"),m.register("AdyenGivingPlugin",h,"#adyen-giving-container"),m.register("AdyenSuccessAction",y,"#adyen-success-action-container")}},e=>{e.O(0,["vendor-node","vendor-shared"],(()=>{return t=7815,e(e.s=t);var t}));e.O()}]); \ No newline at end of file diff --git a/src/Resources/app/storefront/dist/storefront/js/adyen-payment-shopware64.js.dist b/src/Resources/app/storefront/dist/storefront/js/adyen-payment-shopware64.js.dist index 8b43d145..fda6129f 100644 --- a/src/Resources/app/storefront/dist/storefront/js/adyen-payment-shopware64.js.dist +++ b/src/Resources/app/storefront/dist/storefront/js/adyen-payment-shopware64.js.dist @@ -1 +1 @@ -(window.webpackJsonp=window.webpackJsonp||[]).push([["adyen-payment-shopware6"],{HNRU:function(e,t,n){"use strict";t.a={updatablePaymentMethods:["scheme","ideal","sepadirectdebit","oneclick","dotpay","bcmc","bcmc_mobile","blik","eps","facilypay_3x","facilypay_4x","facilypay_6x","facilypay_10x","facilypay_12x","afterpay_default","ratepay","ratepay_directdebit","giftcard","paybright","affirm","multibanco","mbway","vipps","mobilepay","wechatpayQR","wechatpayWeb","paybybank"],componentsWithPayButton:{applepay:{extra:{},onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)}},googlepay:{extra:{buttonSizeMode:"fill"},onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)},onError:function(e,t,n){"CANCELED"!==e.statusCode&&("statusMessage"in e?console.log(e.statusMessage):console.log(e.statusCode))}},paypal:{extra:{},onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()},onError:function(e,t,n){t.setStatus("ready"),window.location.href=n.errorUrl.toString()},onCancel:function(e,t,n){t.setStatus("ready"),window.location.href=n.errorUrl.toString()},responseHandler:function(e,t){try{(t=JSON.parse(t)).isFinal&&(location.href=e.returnUrl),this.handleAction(t.action)}catch(e){console.error(e)}}},amazonpay:{extra:{productType:"PayAndShip",checkoutMode:"ProcessOrder",returnUrl:location.href},prePayRedirect:!0,sessionKey:"amazonCheckoutSessionId",onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)},onError:function(e,t){console.log(e),t.setStatus("ready")}}},paymentMethodTypeHandlers:{scheme:"handler_adyen_cardspaymentmethodhandler",ideal:"handler_adyen_idealpaymentmethodhandler",klarna:"handler_adyen_klarnapaylaterpaymentmethodhandler",klarna_account:"handler_adyen_klarnaaccountpaymentmethodhandler",klarna_paynow:"handler_adyen_klarnapaynowpaymentmethodhandler",ratepay:"handler_adyen_ratepaypaymentmethodhandler",ratepay_directdebit:"handler_adyen_ratepaydirectdebitpaymentmethodhandler",sepadirectdebit:"handler_adyen_sepapaymentmethodhandler",sofort:"handler_adyen_sofortpaymentmethodhandler",paypal:"handler_adyen_paypalpaymentmethodhandler",oneclick:"handler_adyen_oneclickpaymentmethodhandler",giropay:"handler_adyen_giropaypaymentmethodhandler",applepay:"handler_adyen_applepaypaymentmethodhandler",googlepay:"handler_adyen_googlepaypaymentmethodhandler",dotpay:"handler_adyen_dotpaypaymentmethodhandler",bcmc:"handler_adyen_bancontactcardpaymentmethodhandler",bcmc_mobile:"handler_adyen_bancontactmobilepaymentmethodhandler",amazonpay:"handler_adyen_amazonpaypaymentmethodhandler",twint:"handler_adyen_twintpaymentmethodhandler",eps:"handler_adyen_epspaymentmethodhandler",swish:"handler_adyen_swishpaymentmethodhandler",alipay:"handler_adyen_alipaypaymentmethodhandler",alipay_hk:"handler_adyen_alipayhkpaymentmethodhandler",blik:"handler_adyen_blikpaymentmethodhandler",clearpay:"handler_adyen_clearpaypaymentmethodhandler",facilypay_3x:"handler_adyen_facilypay3xpaymentmethodhandler",facilypay_4x:"handler_adyen_facilypay4xpaymentmethodhandler",facilypay_6x:"handler_adyen_facilypay6xpaymentmethodhandler",facilypay_10x:"handler_adyen_facilypay10xpaymentmethodhandler",facilypay_12x:"handler_adyen_facilypay12xpaymentmethodhandler",afterpay_default:"handler_adyen_afterpaydefaultpaymentmethodhandler",trustly:"handler_adyen_trustlypaymentmethodhandler",paysafecard:"handler_adyen_paysafecardpaymentmethodhandler",givex:"handler_adyen_givexgiftcardpaymentmethodhandler",webshopgiftcard:"handler_adyen_webshopgiftcardpaymentmethodhandler",kadowereld:"handler_adyen_kadowereldgiftcardpaymentmethodhandler",tcstestgiftcard:"handler_adyen_tcstestgiftcardpaymentmethodhandler",albelligiftcard:"handler_adyen_albelligiftcardpaymentmethodhandler",bijcadeaucard:"handler_adyen_bijenkorfgiftcardpaymentmethodhandler",vvvgiftcard:"handler_adyen_vvvgiftcardpaymentmethodhandler",genericgiftcard:"handler_adyen_genericgiftcardpaymentmethodhandler",gallgall:"handler_adyen_gallgallgiftcardpaymentmethodhandler",hmlingerie:"handler_adyen_hunkemollerlingeriegiftcardpaymentmethodhandler",beautycadeaukaart:"handler_adyen_beautygiftcardpaymentmethodhandler",svs:"handler_adyen_svsgiftcardpaymentmethodhandler",fashioncheque:"handler_adyen_fashionchequegiftcardpaymentmethodhandler",decadeaukaart:"handler_adyen_decadeaukaartgiftcardpaymentmethodhandler",mbway:"handler_adyen_mbwaypaymentmethodhandler",multibanco:"handler_adyen_multibancopaymentmethodhandler",wechatpayQR:"handler_adyen_wechatpayqrpaymentmethodhandler",wechatpayWeb:"handler_adyen_wechatpaywebpaymentmethodhandler",mobilepay:"handler_adyen_mobilepaypaymentmethodhandler",vipps:"handler_adyen_vippspaymentmethodhandler",affirm:"handler_adyen_affirmpaymentmethodhandler",paybright:"handler_adyen_paybrightpaymentmethodhandler",paybybank:"handler_adyen_openbankingpaymentmethodhandler"}}},TVZM:function(e,t,n){"use strict";n.r(t);var a=n("FGIj"),r=n("gHbT"),o=n("k8s9"),i=n("u0Tz");function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function d(){return(d=Object.assign||function(e){for(var t=1;t0)){this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),i.a.create(r.a.querySelector(document,"#adyen-giftcard-component")),this.giftcardHeader.innerHTML=e.name,this.giftcardComponentClose.style.display="block";var t=d({},e,{showPayButton:!0,onBalanceCheck:this.handleBalanceCheck.bind(this)});try{this.paymentMethodInstance=this.adyenCheckout.create("giftcard",t),this.paymentMethodInstance.mount("#adyen-giftcard-component")}catch(e){console.log("giftcard not available")}i.a.remove(r.a.querySelector(document,"#adyen-giftcard-component"))}}},{key:"handleBalanceCheck",value:function(e,t,n){var a={};a.paymentMethod=JSON.stringify(n.paymentMethod),a.amount=JSON.stringify({currency:adyenGiftcardsConfiguration.currency,value:adyenGiftcardsConfiguration.totalInMinorUnits}),this._client.post("".concat(adyenGiftcardsConfiguration.checkBalanceUrl),JSON.stringify(a),function(e){if((e=JSON.parse(e)).hasOwnProperty("pspReference")){var a=e.transactionLimit?parseFloat(e.transactionLimit.value):parseFloat(e.balance.value),r=a-adyenGiftcardsConfiguration.totalInMinorUnits;a>=adyenGiftcardsConfiguration.totalInMinorUnits?(this.remainingGiftcardBalance=(r/this.minorUnitsQuotient).toFixed(2),this.setGiftcardAsPaymentMethod(n,r)):(this.remainingAmount=((adyenGiftcardsConfiguration.totalInMinorUnits-a)/this.minorUnitsQuotient).toFixed(2),this.saveGiftcardStateData(n,a.toString(),0,this.selectedGiftcard.id)),this.remainingBalanceField.style.display="block";var o=adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingBalance+": "+adyenGiftcardsConfiguration.currencySymbol+this.remainingGiftcardBalance;this.remainingBalanceField.innerHTML=o}else console.error(e.resultCode),t(e.resultCode)}.bind(this))}},{key:"saveGiftcardStateData",value:function(e,t,n,a){e=JSON.stringify(e),this._client.post(adyenGiftcardsConfiguration.setGiftcardUrl,JSON.stringify({stateData:e,amount:t,balance:n,paymentMethodId:a}),function(e){"paymentMethodId"in(e=JSON.parse(e))&&(this.giftcardDiscount=(t/this.minorUnitsQuotient).toFixed(2),this.remainingAmount=(adyenGiftcardsConfiguration.totalPrice-this.giftcardDiscount).toFixed(2),this.onGiftcardSelected(),i.a.remove(document.body))}.bind(this))}},{key:"setGiftcardAsPaymentMethod",value:function(e,t){this._client.patch(adyenGiftcardsConfiguration.switchContextUrl,JSON.stringify({paymentMethodId:this.selectedGiftcard.id}),function(n){this.saveGiftcardStateData(e,adyenGiftcardsConfiguration.totalInMinorUnits,t,this.selectedGiftcard.id)}.bind(this))}},{key:"removeGiftcard",value:function(){i.a.create(document.body),this._client.post(adyenGiftcardsConfiguration.removeGiftcardUrl,new FormData,function(e){if("token"in(e=JSON.parse(e))){if(this.giftcardDiscount=0,this.remainingAmount=(adyenGiftcardsConfiguration.totalPrice-this.giftcardDiscount).toFixed(2),this.shoppingCartSummaryBlock.length)for(var t=this.shoppingCartSummaryBlock[0].querySelectorAll(".adyen-giftcard-summary"),n=0;n
'+adyenGiftcardsConfiguration.currencySymbol+this.giftcardDiscount+'
'+adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingAmount+'
'+adyenGiftcardsConfiguration.currencySymbol+this.remainingAmount+"
";this.shoppingCartSummaryBlock[0].innerHTML+=e}}},{key:"onGiftcardSelected",value:function(){this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),this.giftcardComponentClose.style.display="none";for(var e=0;e1&&void 0!==arguments[1]?arguments[1]:null;this.hideStorePaymentMethodComponents(),t=e?e.target.value:t;var n='[data-adyen-stored-payment-method-id="'.concat(t,'"]'),a=o.a.querySelector(document,n);a.style.display="block"}},{key:"hideStorePaymentMethodComponents",value:function(){o.a.querySelectorAll(document,".stored-payment-component").forEach((function(e){e.style.display="none"}))}},{key:"confirmOrder",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=adyenCheckoutOptions.orderId;e.set("affiliateCode",adyenCheckoutOptions.affiliateCode),e.set("campaignCode",adyenCheckoutOptions.campaignCode),n?this.updatePayment(e,n,t):this.createOrder(e,t)}},{key:"updatePayment",value:function(e,t,n){e.set("orderId",t),this._client.post(adyenCheckoutOptions.updatePaymentUrl,e,this.afterSetPayment.bind(this,n))}},{key:"createOrder",value:function(e,t){parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&!parseInt(adyenCheckoutOptions.payInFullWithGiftcard,10)?this._client.post(adyenCheckoutOptions.createOrderUrl,JSON.stringify({orderAmount:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency}),function(n){var a=JSON.parse(n);"Success"===a.resultCode&&(t=y(t,{order:a})),this._client.post(adyenCheckoutOptions.checkoutOrderUrl,e,this.afterCreateOrder.bind(this,t))}.bind(this)):this._client.post(adyenCheckoutOptions.checkoutOrderUrl,e,this.afterCreateOrder.bind(this,t))}},{key:"afterCreateOrder",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;try{e=JSON.parse(n)}catch(e){return d.a.remove(document.body),void console.log("Error: invalid response from Shopware API",n)}this.orderId=e.id,this.finishUrl=new URL(location.origin+adyenCheckoutOptions.paymentFinishUrl),this.finishUrl.searchParams.set("orderId",e.id),this.errorUrl=new URL(location.origin+adyenCheckoutOptions.paymentErrorUrl),this.errorUrl.searchParams.set("orderId",e.id);var a={orderId:this.orderId,finishUrl:this.finishUrl.toString(),errorUrl:this.errorUrl.toString()};for(var r in t)a[r]=t[r];this._client.post(adyenCheckoutOptions.paymentHandleUrl,JSON.stringify(a),this.afterPayOrder.bind(this,this.orderId))}},{key:"afterSetPayment",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;try{var n=JSON.parse(t);n.success&&this.afterCreateOrder(e,JSON.stringify({id:adyenCheckoutOptions.orderId}))}catch(e){return d.a.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}}},{key:"afterPayOrder",value:function(e,t){try{t=JSON.parse(t),this.returnUrl=t.redirectUrl}catch(e){return d.a.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}this.returnUrl===this.errorUrl.toString()&&(location.href=this.returnUrl);try{this._client.post("".concat(adyenCheckoutOptions.paymentStatusUrl),JSON.stringify({orderId:e}),this.responseHandler.bind(this))}catch(e){console.log(e)}}},{key:"handlePaymentAction",value:function(t){try{var n=JSON.parse(t);if((n.isFinal||"voucher"===n.action.type)&&(location.href=this.returnUrl),n.action){var r={};"threeDS2"===n.action.type&&(r.challengeWindowSize="05"),this.adyenCheckout.createFromAction(n.action,r).mount("[data-adyen-payment-action-container]"),["threeDS2","qrCode"].includes(n.action.type)&&(e?a("[data-adyen-payment-action-modal]").modal({show:!0}):new bootstrap.Modal(document.getElementById("adyen-payment-action-modal"),{keyboard:!1}).show())}}catch(e){console.log(e)}}},{key:"initializeCustomPayButton",value:function(){var e=this,t=s.a.componentsWithPayButton[this.selectedAdyenPaymentMethod];this.completePendingPayment(this.selectedAdyenPaymentMethod,t);var n=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((function(t){return t.type===e.selectedAdyenPaymentMethod}));if(n.length<1&&"googlepay"===this.selectedAdyenPaymentMethod&&(n=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((function(e){return"paywithgoogle"===e.type}))),!(n.length<1)){var a=n[0];if(adyenCheckoutOptions.amount)if(t.prePayRedirect)this.renderPrePaymentButton(t,a);else{var r=y(t.extra,a,{amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onClick:function(n,a){if(!t.onClick(n,a,e))return!1;d.a.create(document.body)},onSubmit:function(e,n){if(e.isValid){var a={stateData:JSON.stringify(e.data)},r=c.a.serialize(this.confirmOrderForm);"responseHandler"in t&&(this.responseHandler=t.responseHandler.bind(n,this)),this.confirmOrder(r,a)}else n.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",e)}.bind(this),onCancel:function(n,a){d.a.remove(document.body),t.onCancel(n,a,e)},onError:function(n,a){"PayPal"===a.props.name&&"CANCEL"===n.name&&e._client.post("".concat(adyenCheckoutOptions.cancelOrderTransactionUrl),JSON.stringify({orderId:e.orderId})),d.a.remove(document.body),t.onError(n,a,e),console.log(n)}}),o=this.adyenCheckout.create(a.type,r);try{"isAvailable"in o?o.isAvailable().then(function(){this.mountCustomPayButton(o)}.bind(this)).catch((function(e){console.log(a.type+" is not available",e)})):this.mountCustomPayButton(o)}catch(e){console.log(e)}}else console.error("Failed to fetch Cart/Order total amount.")}}},{key:"renderPrePaymentButton",value:function(e,t){var n=this;"amazonpay"===t.type&&(e.extra=this.setAddressDetails(e.extra));var a=y(e.extra,t,{configuration:t.configuration,amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},onClick:function(t,a){if(!e.onClick(t,a,n))return!1;d.a.create(document.body)},onError:function(t,a){d.a.remove(document.body),e.onError(t,a,n),console.log(t)}}),r=this.adyenCheckout.create(t.type,a);this.mountCustomPayButton(r)}},{key:"completePendingPayment",value:function(e,t){var n=new URL(location.href);if(n.searchParams.has(t.sessionKey)){var a;d.a.create(document.body);var r=this.adyenCheckout.create(e,(u(a={},t.sessionKey,n.searchParams.get(t.sessionKey)),u(a,"showOrderButton",!1),u(a,"onSubmit",function(e,t){if(e.isValid){var n={stateData:JSON.stringify(e.data)},a=c.a.serialize(this.confirmOrderForm);this.confirmOrder(a,n)}}.bind(this)),a));this.mountCustomPayButton(r),r.submit()}}},{key:"getSelectedPaymentMethodKey",value:function(){return Object.keys(s.a.paymentMethodTypeHandlers).find((function(e){return s.a.paymentMethodTypeHandlers[e]===adyenCheckoutOptions.selectedPaymentMethodHandler}))}},{key:"mountCustomPayButton",value:function(e){var t=document.querySelector("#confirmOrderForm");if(t){var n=t.querySelector("button[type=submit]");if(n&&!n.disabled){var a=document.createElement("div");a.id="adyen-confirm-button",a.setAttribute("data-adyen-confirm-button",""),t.appendChild(a),e.mount(a),n.remove()}}}},{key:"mountPaymentComponent",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=y({},e,{data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onSubmit:function(e,t){if(e.isValid){var n={stateData:JSON.stringify(e.data)},a=c.a.serialize(this.confirmOrderForm);d.a.create(document.body),this.confirmOrder(a,n)}else t.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",e)}.bind(this)});!t&&"scheme"===e.type&&adyenCheckoutOptions.displaySaveCreditCardOption&&(a.enableStoreDetails=!0);var r=t?n:"#"+this.el.id;try{var i=this.adyenCheckout.create(e.type,a);i.mount(r),this.confirmFormSubmit.addEventListener("click",function(e){o.a.querySelector(document,"#confirmOrderForm").checkValidity()&&(e.preventDefault(),this.el.parentNode.scrollIntoView({behavior:"smooth",block:"start"}),i.submit())}.bind(this))}catch(t){return console.error(e.type,t),!1}}},{key:"appendGiftcardSummary",value:function(){if(parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&this.shoppingCartSummaryBlock.length){var e='
'+adyenCheckoutOptions.translationAdyenGiftcardDiscount+'
'+adyenCheckoutOptions.currencySymbol+this.giftcardDiscount+'
'+adyenCheckoutOptions.translationAdyenGiftcardRemainingAmount+'
'+adyenCheckoutOptions.currencySymbol+this.remainingAmount+"
";this.shoppingCartSummaryBlock[0].innerHTML+=e}}},{key:"setAddressDetails",value:function(e){return""!==activeShippingAddress.phoneNumber?e.addressDetails={name:shopperDetails.firstName+" "+shopperDetails.lastName,addressLine1:activeShippingAddress.street,city:activeShippingAddress.city,postalCode:activeShippingAddress.postalCode,countryCode:activeShippingAddress.country,phoneNumber:activeShippingAddress.phoneNumber}:e.productType="PayOnly",e}}])&&f(r.prototype,l),b&&f(r,b),n}(r.a)}).call(this,n("UoTJ"),n("UoTJ"))}},[["TVZM","runtime","vendor-node","vendor-shared"]]]); \ No newline at end of file +(window.webpackJsonp=window.webpackJsonp||[]).push([["adyen-payment-shopware6"],{HNRU:function(e,t,n){"use strict";t.a={updatablePaymentMethods:["scheme","ideal","sepadirectdebit","oneclick","dotpay","bcmc","bcmc_mobile","blik","eps","facilypay_3x","facilypay_4x","facilypay_6x","facilypay_10x","facilypay_12x","afterpay_default","ratepay","ratepay_directdebit","giftcard","paybright","affirm","multibanco","mbway","vipps","mobilepay","wechatpayQR","wechatpayWeb","paybybank"],componentsWithPayButton:{applepay:{extra:{},onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)}},googlepay:{extra:{buttonSizeMode:"fill"},onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)},onError:function(e,t,n){"CANCELED"!==e.statusCode&&("statusMessage"in e?console.log(e.statusMessage):console.log(e.statusCode))}},paypal:{extra:{},onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()},onError:function(e,t,n){t.setStatus("ready"),window.location.href=n.errorUrl.toString()},onCancel:function(e,t,n){t.setStatus("ready"),window.location.href=n.errorUrl.toString()},responseHandler:function(e,t){try{(t=JSON.parse(t)).isFinal&&(location.href=e.returnUrl),this.handleAction(t.action)}catch(e){console.error(e)}}},amazonpay:{extra:{productType:"PayAndShip",checkoutMode:"ProcessOrder",returnUrl:location.href},prePayRedirect:!0,sessionKey:"amazonCheckoutSessionId",onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)},onError:function(e,t){console.log(e),t.setStatus("ready")}}},paymentMethodTypeHandlers:{scheme:"handler_adyen_cardspaymentmethodhandler",ideal:"handler_adyen_idealpaymentmethodhandler",klarna:"handler_adyen_klarnapaylaterpaymentmethodhandler",klarna_account:"handler_adyen_klarnaaccountpaymentmethodhandler",klarna_paynow:"handler_adyen_klarnapaynowpaymentmethodhandler",ratepay:"handler_adyen_ratepaypaymentmethodhandler",ratepay_directdebit:"handler_adyen_ratepaydirectdebitpaymentmethodhandler",sepadirectdebit:"handler_adyen_sepapaymentmethodhandler",sofort:"handler_adyen_sofortpaymentmethodhandler",paypal:"handler_adyen_paypalpaymentmethodhandler",oneclick:"handler_adyen_oneclickpaymentmethodhandler",giropay:"handler_adyen_giropaypaymentmethodhandler",applepay:"handler_adyen_applepaypaymentmethodhandler",googlepay:"handler_adyen_googlepaypaymentmethodhandler",dotpay:"handler_adyen_dotpaypaymentmethodhandler",bcmc:"handler_adyen_bancontactcardpaymentmethodhandler",bcmc_mobile:"handler_adyen_bancontactmobilepaymentmethodhandler",amazonpay:"handler_adyen_amazonpaypaymentmethodhandler",twint:"handler_adyen_twintpaymentmethodhandler",eps:"handler_adyen_epspaymentmethodhandler",swish:"handler_adyen_swishpaymentmethodhandler",alipay:"handler_adyen_alipaypaymentmethodhandler",alipay_hk:"handler_adyen_alipayhkpaymentmethodhandler",blik:"handler_adyen_blikpaymentmethodhandler",clearpay:"handler_adyen_clearpaypaymentmethodhandler",facilypay_3x:"handler_adyen_facilypay3xpaymentmethodhandler",facilypay_4x:"handler_adyen_facilypay4xpaymentmethodhandler",facilypay_6x:"handler_adyen_facilypay6xpaymentmethodhandler",facilypay_10x:"handler_adyen_facilypay10xpaymentmethodhandler",facilypay_12x:"handler_adyen_facilypay12xpaymentmethodhandler",afterpay_default:"handler_adyen_afterpaydefaultpaymentmethodhandler",trustly:"handler_adyen_trustlypaymentmethodhandler",paysafecard:"handler_adyen_paysafecardpaymentmethodhandler",giftcard:"handler_adyen_giftcardpaymentmethodhandler",mbway:"handler_adyen_mbwaypaymentmethodhandler",multibanco:"handler_adyen_multibancopaymentmethodhandler",wechatpayQR:"handler_adyen_wechatpayqrpaymentmethodhandler",wechatpayWeb:"handler_adyen_wechatpaywebpaymentmethodhandler",mobilepay:"handler_adyen_mobilepaypaymentmethodhandler",vipps:"handler_adyen_vippspaymentmethodhandler",affirm:"handler_adyen_affirmpaymentmethodhandler",paybright:"handler_adyen_paybrightpaymentmethodhandler",paybybank:"handler_adyen_openbankingpaymentmethodhandler"}}},TVZM:function(e,t,n){"use strict";n.r(t);var a=n("FGIj"),o=n("gHbT"),r=n("k8s9"),i=n("u0Tz");function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function d(){return(d=Object.assign||function(e){for(var t=1;t".concat(e.title,""),o.appendChild(i),o.innerHTML+='

'.concat(a,"


"),t.appendChild(o)})),this.remainingAmount=e.redeemedGiftcards.remainingAmount,this.giftcardDiscount=e.redeemedGiftcards.totalDiscount,this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),this.giftcardComponentClose.style.display="none",this.giftcardItem.innerHTML="",this.giftcardHeader.innerHTML=" ",this.appendGiftcardSummary(),this.remainingAmount>0?n.style.display="block":(this.adyenGiftcardDropDown.length>0&&(this.adyenGiftcardDropDown[0].style.display="none"),n.style.display="none"),document.getElementById("giftcardsContainer")}.bind(this))}},{key:"saveGiftcardStateData",value:function(e){e=JSON.stringify(e),this._client.post(adyenGiftcardsConfiguration.setGiftcardUrl,JSON.stringify({stateData:e}),function(e){"token"in(e=JSON.parse(e))&&(this.fetchRedeemedGiftcards(),i.a.remove(document.body))}.bind(this))}},{key:"removeGiftcard",value:function(e){var t=this;i.a.create(document.body),this._client.post(adyenGiftcardsConfiguration.removeGiftcardUrl,JSON.stringify({stateDataId:e}),(function(e){"token"in(e=JSON.parse(e))&&(t.fetchRedeemedGiftcards(),i.a.remove(document.body))}))}},{key:"appendGiftcardSummary",value:function(){if(this.shoppingCartSummaryBlock.length)for(var e=this.shoppingCartSummaryBlock[0].querySelectorAll(".adyen-giftcard-summary"),t=0;t
'+adyenGiftcardsConfiguration.currencySymbol+n+'
'+adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingAmount+'
'+adyenGiftcardsConfiguration.currencySymbol+a+"
";this.shoppingCartSummaryBlock[0].innerHTML+=o}}}])&&u(n.prototype,a),c&&u(n,c),t}(a.a),f=n("h8V8");function g(e){return(g="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function v(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function b(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function k(e,t,n,a,o,r,i){try{var c=e[r](i),d=c.value}catch(e){return void n(e)}c.done?t(d):Promise.resolve(d).then(a,o)}function C(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function O(e,t){for(var n=0;n0?parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&this.appendGiftcardSummary():this.appendGiftcardSummary()}},{key:"initializeCheckoutComponent",value:(k=regeneratorRuntime.mark((function e(){var t,n,a,o,r,i,c;return regeneratorRuntime.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=adyenCheckoutConfiguration,n=t.locale,a=t.clientKey,o=t.environment,r=t.merchantAccount,i=adyenCheckoutOptions.paymentMethodsResponse,c={locale:n,clientKey:a,environment:o,showPayButton:this.selectedAdyenPaymentMethod in s.a.componentsWithPayButton,hasHolderName:!0,paymentMethodsResponse:JSON.parse(i),onAdditionalDetails:this.handleOnAdditionalDetails.bind(this),countryCode:activeShippingAddress.country,paymentMethodsConfiguration:{card:{hasHolderName:!0,clickToPayConfiguration:{merchantDisplayName:r,shopperEmail:shopperDetails.shopperEmail}}}},e.next=5,AdyenCheckout(c);case 5:this.adyenCheckout=e.sent;case 6:case"end":return e.stop()}}),e,this)})),C=function(){var e=this,t=arguments;return new Promise((function(n,a){var o=k.apply(e,t);function r(e){h(o,n,a,r,i,"next",e)}function i(e){h(o,n,a,r,i,"throw",e)}r(void 0)}))},function(){return C.apply(this,arguments)})},{key:"handleOnAdditionalDetails",value:function(e){this._client.post("".concat(adyenCheckoutOptions.paymentDetailsUrl),JSON.stringify({orderId:this.orderId,stateData:JSON.stringify(e.data)}),function(e){200===this._client._request.status?this.responseHandler(e):location.href=this.errorUrl.toString()}.bind(this))}},{key:"onConfirmOrderSubmit",value:function(e){var t=r.a.querySelector(document,"#confirmOrderForm");if(t.checkValidity()){e.preventDefault(),d.a.create(document.body);var n=c.a.serialize(t);this.confirmOrder(n)}}},{key:"renderPaymentComponent",value:function(e){if("oneclick"!==e){if("giftcard"!==e){var t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((function(t){return t.type===e}));if(0!==t.length){var n=t[0];this.mountPaymentComponent(n,!1)}else"test"===this.adyenCheckout.options.environment&&console.error("Payment method configuration not found. ",e)}}else this.renderStoredPaymentMethodComponents()}},{key:"renderStoredPaymentMethodComponents",value:function(){var e=this;this.adyenCheckout.paymentMethodsResponse.storedPaymentMethods.forEach((function(t){var n='[data-adyen-stored-payment-method-id="'.concat(t.id,'"]');e.mountPaymentComponent(t,!0,n)})),this.hideStorePaymentMethodComponents();var t=null;r.a.querySelectorAll(document,"[name=adyenStoredPaymentMethodId]").forEach((function(n){t||(t=n.value),n.addEventListener("change",e.showSelectedStoredPaymentMethod.bind(e))})),this.showSelectedStoredPaymentMethod(null,t)}},{key:"showSelectedStoredPaymentMethod",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;this.hideStorePaymentMethodComponents(),t=e?e.target.value:t;var n='[data-adyen-stored-payment-method-id="'.concat(t,'"]'),a=r.a.querySelector(document,n);a.style.display="block"}},{key:"hideStorePaymentMethodComponents",value:function(){r.a.querySelectorAll(document,".stored-payment-component").forEach((function(e){e.style.display="none"}))}},{key:"confirmOrder",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=adyenCheckoutOptions.orderId;e.set("affiliateCode",adyenCheckoutOptions.affiliateCode),e.set("campaignCode",adyenCheckoutOptions.campaignCode),n?this.updatePayment(e,n,t):this.createOrder(e,t)}},{key:"updatePayment",value:function(e,t,n){e.set("orderId",t),this._client.post(adyenCheckoutOptions.updatePaymentUrl,e,this.afterSetPayment.bind(this,n))}},{key:"createOrder",value:function(e,t){this._client.post(adyenCheckoutOptions.checkoutOrderUrl,e,this.afterCreateOrder.bind(this,t))}},{key:"afterCreateOrder",value:function(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;try{e=JSON.parse(n)}catch(e){return d.a.remove(document.body),void console.log("Error: invalid response from Shopware API",n)}this.orderId=e.id,this.finishUrl=new URL(location.origin+adyenCheckoutOptions.paymentFinishUrl),this.finishUrl.searchParams.set("orderId",e.id),this.errorUrl=new URL(location.origin+adyenCheckoutOptions.paymentErrorUrl),this.errorUrl.searchParams.set("orderId",e.id);var a={orderId:this.orderId,finishUrl:this.finishUrl.toString(),errorUrl:this.errorUrl.toString()};for(var o in t)a[o]=t[o];this._client.post(adyenCheckoutOptions.paymentHandleUrl,JSON.stringify(a),this.afterPayOrder.bind(this,this.orderId))}},{key:"afterSetPayment",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0;try{var n=JSON.parse(t);n.success&&this.afterCreateOrder(e,JSON.stringify({id:adyenCheckoutOptions.orderId}))}catch(e){return d.a.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}}},{key:"afterPayOrder",value:function(e,t){try{t=JSON.parse(t),this.returnUrl=t.redirectUrl}catch(e){return d.a.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}this.returnUrl===this.errorUrl.toString()&&(location.href=this.returnUrl);try{this._client.post("".concat(adyenCheckoutOptions.paymentStatusUrl),JSON.stringify({orderId:e}),this.responseHandler.bind(this))}catch(e){console.log(e)}}},{key:"handlePaymentAction",value:function(t){try{var n=JSON.parse(t);if((n.isFinal||"voucher"===n.action.type)&&(location.href=this.returnUrl),n.action){var o={};"threeDS2"===n.action.type&&(o.challengeWindowSize="05"),this.adyenCheckout.createFromAction(n.action,o).mount("[data-adyen-payment-action-container]"),["threeDS2","qrCode"].includes(n.action.type)&&(e?a("[data-adyen-payment-action-modal]").modal({show:!0}):new bootstrap.Modal(document.getElementById("adyen-payment-action-modal"),{keyboard:!1}).show())}}catch(e){console.log(e)}}},{key:"initializeCustomPayButton",value:function(){var e=this,t=s.a.componentsWithPayButton[this.selectedAdyenPaymentMethod];this.completePendingPayment(this.selectedAdyenPaymentMethod,t);var n=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((function(t){return t.type===e.selectedAdyenPaymentMethod}));if(n.length<1&&"googlepay"===this.selectedAdyenPaymentMethod&&(n=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((function(e){return"paywithgoogle"===e.type}))),!(n.length<1)){var a=n[0];if(adyenCheckoutOptions.amount)if(t.prePayRedirect)this.renderPrePaymentButton(t,a);else{var o=y(t.extra,a,{amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onClick:function(n,a){if(!t.onClick(n,a,e))return!1;d.a.create(document.body)},onSubmit:function(e,n){if(e.isValid){var a={stateData:JSON.stringify(e.data)},o=c.a.serialize(this.confirmOrderForm);"responseHandler"in t&&(this.responseHandler=t.responseHandler.bind(n,this)),this.confirmOrder(o,a)}else n.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",e)}.bind(this),onCancel:function(n,a){d.a.remove(document.body),t.onCancel(n,a,e)},onError:function(n,a){"PayPal"===a.props.name&&"CANCEL"===n.name&&e._client.post("".concat(adyenCheckoutOptions.cancelOrderTransactionUrl),JSON.stringify({orderId:e.orderId})),d.a.remove(document.body),t.onError(n,a,e),console.log(n)}}),r=this.adyenCheckout.create(a.type,o);try{"isAvailable"in r?r.isAvailable().then(function(){this.mountCustomPayButton(r)}.bind(this)).catch((function(e){console.log(a.type+" is not available",e)})):this.mountCustomPayButton(r)}catch(e){console.log(e)}}else console.error("Failed to fetch Cart/Order total amount.")}}},{key:"renderPrePaymentButton",value:function(e,t){var n=this;"amazonpay"===t.type&&(e.extra=this.setAddressDetails(e.extra));var a=y(e.extra,t,{configuration:t.configuration,amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},onClick:function(t,a){if(!e.onClick(t,a,n))return!1;d.a.create(document.body)},onError:function(t,a){d.a.remove(document.body),e.onError(t,a,n),console.log(t)}}),o=this.adyenCheckout.create(t.type,a);this.mountCustomPayButton(o)}},{key:"completePendingPayment",value:function(e,t){var n=new URL(location.href);if(n.searchParams.has(t.sessionKey)){var a;d.a.create(document.body);var o=this.adyenCheckout.create(e,(u(a={},t.sessionKey,n.searchParams.get(t.sessionKey)),u(a,"showOrderButton",!1),u(a,"onSubmit",function(e,t){if(e.isValid){var n={stateData:JSON.stringify(e.data)},a=c.a.serialize(this.confirmOrderForm);this.confirmOrder(a,n)}}.bind(this)),a));this.mountCustomPayButton(o),o.submit()}}},{key:"getSelectedPaymentMethodKey",value:function(){return Object.keys(s.a.paymentMethodTypeHandlers).find((function(e){return s.a.paymentMethodTypeHandlers[e]===adyenCheckoutOptions.selectedPaymentMethodHandler}))}},{key:"mountCustomPayButton",value:function(e){var t=document.querySelector("#confirmOrderForm");if(t){var n=t.querySelector("button[type=submit]");if(n&&!n.disabled){var a=document.createElement("div");a.id="adyen-confirm-button",a.setAttribute("data-adyen-confirm-button",""),t.appendChild(a),e.mount(a),n.remove()}}}},{key:"mountPaymentComponent",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=y({},e,{data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onSubmit:function(e,t){if(e.isValid){var n={stateData:JSON.stringify(e.data)},a=c.a.serialize(this.confirmOrderForm);d.a.create(document.body),this.confirmOrder(a,n)}else t.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",e)}.bind(this)});!t&&"scheme"===e.type&&adyenCheckoutOptions.displaySaveCreditCardOption&&(a.enableStoreDetails=!0);var o=t?n:"#"+this.el.id;try{var i=this.adyenCheckout.create(e.type,a);i.mount(o),this.confirmFormSubmit.addEventListener("click",function(e){r.a.querySelector(document,"#confirmOrderForm").checkValidity()&&(e.preventDefault(),this.el.parentNode.scrollIntoView({behavior:"smooth",block:"start"}),i.submit())}.bind(this))}catch(t){return console.error(e.type,t),!1}}},{key:"appendGiftcardSummary",value:function(){if(parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&this.shoppingCartSummaryBlock.length){var e=parseFloat(this.giftcardDiscount).toFixed(2),t=parseFloat(this.remainingAmount).toFixed(2),n='
'+adyenCheckoutOptions.translationAdyenGiftcardDiscount+'
'+adyenCheckoutOptions.currencySymbol+e+'
'+adyenCheckoutOptions.translationAdyenGiftcardRemainingAmount+'
'+adyenCheckoutOptions.currencySymbol+t+"
";this.shoppingCartSummaryBlock[0].innerHTML+=n}}},{key:"setAddressDetails",value:function(e){return""!==activeShippingAddress.phoneNumber?e.addressDetails={name:shopperDetails.firstName+" "+shopperDetails.lastName,addressLine1:activeShippingAddress.street,city:activeShippingAddress.city,postalCode:activeShippingAddress.postalCode,countryCode:activeShippingAddress.country,phoneNumber:activeShippingAddress.phoneNumber}:e.productType="PayOnly",e}}])&&p(o.prototype,l),b&&p(o,b),n}(o.a)}).call(this,n("UoTJ"),n("UoTJ"))}},[["TVZM","runtime","vendor-node","vendor-shared"]]]); diff --git a/src/Resources/app/storefront/dist/storefront/js/adyen-payment-shopware65.js.dist b/src/Resources/app/storefront/dist/storefront/js/adyen-payment-shopware65.js.dist index 13220282..393868e7 100644 --- a/src/Resources/app/storefront/dist/storefront/js/adyen-payment-shopware65.js.dist +++ b/src/Resources/app/storefront/dist/storefront/js/adyen-payment-shopware65.js.dist @@ -1 +1 @@ -"use strict";(self.webpackChunk=self.webpackChunk||[]).push([["adyen-payment-shopware6"],{7815:(e,t,n)=>{var a=n(6285),i=n(3206),o=n(8254),r=n(4690);class d extends a.Z{init(){let e=this;this._client=new o.Z,this.adyenCheckout=Promise,this.paymentMethodInstance=null,this.selectedGiftcard=null,this.initializeCheckoutComponent().then(function(){this.observeGiftcardSelection()}.bind(this)),this.adyenGiftcard=i.Z.querySelectorAll(document,".adyen-giftcard"),this.giftcardHeader=i.Z.querySelector(document,".adyen-giftcard-header"),this.giftcardComponentClose=i.Z.querySelector(document,".adyen-close-giftcard-component"),this.removeGiftcardButton=i.Z.querySelector(document,".adyen-remove-giftcard"),this.remainingBalanceField=i.Z.querySelector(document,".adyen-remaining-balance"),this.minorUnitsQuotient=adyenGiftcardsConfiguration.totalInMinorUnits/adyenGiftcardsConfiguration.totalPrice,this.giftcardDiscount=(adyenGiftcardsConfiguration.giftcardDiscount/this.minorUnitsQuotient).toFixed(2),this.remainingAmount=(adyenGiftcardsConfiguration.totalPrice-this.giftcardDiscount).toFixed(2),this.remainingGiftcardBalance=(adyenGiftcardsConfiguration.giftcardBalance/this.minorUnitsQuotient).toFixed(2),this.shoppingCartSummaryBlock=i.Z.querySelectorAll(document,".checkout-aside-summary-list"),this.offCanvasSummaryDetails=null,this.shoppingCartSummaryDetails=null,this.giftcardComponentClose.onclick=function(t){t.currentTarget.style.display="none",e.selectedGiftcard=null,e.giftcardHeader.innerHTML=" ",e.paymentMethodInstance&&e.paymentMethodInstance.unmount()},this.removeGiftcardButton.onclick=function(t){e.removeGiftcard()},window.addEventListener("DOMContentLoaded",(e=>{parseInt(adyenGiftcardsConfiguration.giftcardDiscount,10)&&this.onGiftcardSelected()}))}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,a={locale:e,clientKey:t,environment:n,amount:{currency:adyenGiftcardsConfiguration.currency,value:adyenGiftcardsConfiguration.totalInMinorUnits}};this.adyenCheckout=await AdyenCheckout(a)}observeGiftcardSelection(){let e=this;for(let t=0;t0)return;this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),r.Z.create(i.Z.querySelector(document,"#adyen-giftcard-component")),this.giftcardHeader.innerHTML=e.name,this.giftcardComponentClose.style.display="block";const t=Object.assign({},e,{showPayButton:!0,onBalanceCheck:this.handleBalanceCheck.bind(this)});try{this.paymentMethodInstance=this.adyenCheckout.create("giftcard",t),this.paymentMethodInstance.mount("#adyen-giftcard-component")}catch(e){console.log("giftcard not available")}r.Z.remove(i.Z.querySelector(document,"#adyen-giftcard-component"))}handleBalanceCheck(e,t,n){let a={};a.paymentMethod=JSON.stringify(n.paymentMethod),a.amount=JSON.stringify({currency:adyenGiftcardsConfiguration.currency,value:adyenGiftcardsConfiguration.totalInMinorUnits}),this._client.post(`${adyenGiftcardsConfiguration.checkBalanceUrl}`,JSON.stringify(a),function(e){if((e=JSON.parse(e)).hasOwnProperty("pspReference")){const t=e.transactionLimit?parseFloat(e.transactionLimit.value):parseFloat(e.balance.value);let a=t-adyenGiftcardsConfiguration.totalInMinorUnits;t>=adyenGiftcardsConfiguration.totalInMinorUnits?(this.remainingGiftcardBalance=(a/this.minorUnitsQuotient).toFixed(2),this.setGiftcardAsPaymentMethod(n,a)):(this.remainingAmount=((adyenGiftcardsConfiguration.totalInMinorUnits-t)/this.minorUnitsQuotient).toFixed(2),this.saveGiftcardStateData(n,t.toString(),0,this.selectedGiftcard.id)),this.remainingBalanceField.style.display="block";let i=adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingBalance+": "+adyenGiftcardsConfiguration.currencySymbol+this.remainingGiftcardBalance;this.remainingBalanceField.innerHTML=i}else console.error(e.resultCode),t(e.resultCode)}.bind(this))}saveGiftcardStateData(e,t,n,a){e=JSON.stringify(e),this._client.post(adyenGiftcardsConfiguration.setGiftcardUrl,JSON.stringify({stateData:e,amount:t,balance:n,paymentMethodId:a}),function(e){"paymentMethodId"in(e=JSON.parse(e))&&(this.giftcardDiscount=(t/this.minorUnitsQuotient).toFixed(2),this.remainingAmount=(adyenGiftcardsConfiguration.totalPrice-this.giftcardDiscount).toFixed(2),this.onGiftcardSelected(),r.Z.remove(document.body))}.bind(this))}setGiftcardAsPaymentMethod(e,t){this._client.patch(adyenGiftcardsConfiguration.switchContextUrl,JSON.stringify({paymentMethodId:this.selectedGiftcard.id}),function(n){this.saveGiftcardStateData(e,adyenGiftcardsConfiguration.totalInMinorUnits,t,this.selectedGiftcard.id)}.bind(this))}removeGiftcard(){r.Z.create(document.body),this._client.post(adyenGiftcardsConfiguration.removeGiftcardUrl,new FormData,function(e){if("token"in(e=JSON.parse(e))){if(this.giftcardDiscount=0,this.remainingAmount=(adyenGiftcardsConfiguration.totalPrice-this.giftcardDiscount).toFixed(2),this.shoppingCartSummaryBlock.length){let e=this.shoppingCartSummaryBlock[0].querySelectorAll(".adyen-giftcard-summary");for(let t=0;t
'+adyenGiftcardsConfiguration.currencySymbol+this.giftcardDiscount+'
'+adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingAmount+'
'+adyenGiftcardsConfiguration.currencySymbol+this.remainingAmount+"
";this.shoppingCartSummaryBlock[0].innerHTML+=e}}onGiftcardSelected(){this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),this.giftcardComponentClose.style.display="none";for(var e=0;e{console.log(e),t.setStatus("ready")}}},paymentMethodTypeHandlers:{scheme:"handler_adyen_cardspaymentmethodhandler",ideal:"handler_adyen_idealpaymentmethodhandler",klarna:"handler_adyen_klarnapaylaterpaymentmethodhandler",klarna_account:"handler_adyen_klarnaaccountpaymentmethodhandler",klarna_paynow:"handler_adyen_klarnapaynowpaymentmethodhandler",ratepay:"handler_adyen_ratepaypaymentmethodhandler",ratepay_directdebit:"handler_adyen_ratepaydirectdebitpaymentmethodhandler",sepadirectdebit:"handler_adyen_sepapaymentmethodhandler",sofort:"handler_adyen_sofortpaymentmethodhandler",paypal:"handler_adyen_paypalpaymentmethodhandler",oneclick:"handler_adyen_oneclickpaymentmethodhandler",giropay:"handler_adyen_giropaypaymentmethodhandler",applepay:"handler_adyen_applepaypaymentmethodhandler",googlepay:"handler_adyen_googlepaypaymentmethodhandler",dotpay:"handler_adyen_dotpaypaymentmethodhandler",bcmc:"handler_adyen_bancontactcardpaymentmethodhandler",bcmc_mobile:"handler_adyen_bancontactmobilepaymentmethodhandler",amazonpay:"handler_adyen_amazonpaypaymentmethodhandler",twint:"handler_adyen_twintpaymentmethodhandler",eps:"handler_adyen_epspaymentmethodhandler",swish:"handler_adyen_swishpaymentmethodhandler",alipay:"handler_adyen_alipaypaymentmethodhandler",alipay_hk:"handler_adyen_alipayhkpaymentmethodhandler",blik:"handler_adyen_blikpaymentmethodhandler",clearpay:"handler_adyen_clearpaypaymentmethodhandler",facilypay_3x:"handler_adyen_facilypay3xpaymentmethodhandler",facilypay_4x:"handler_adyen_facilypay4xpaymentmethodhandler",facilypay_6x:"handler_adyen_facilypay6xpaymentmethodhandler",facilypay_10x:"handler_adyen_facilypay10xpaymentmethodhandler",facilypay_12x:"handler_adyen_facilypay12xpaymentmethodhandler",afterpay_default:"handler_adyen_afterpaydefaultpaymentmethodhandler",trustly:"handler_adyen_trustlypaymentmethodhandler",paysafecard:"handler_adyen_paysafecardpaymentmethodhandler",givex:"handler_adyen_givexgiftcardpaymentmethodhandler",webshopgiftcard:"handler_adyen_webshopgiftcardpaymentmethodhandler",kadowereld:"handler_adyen_kadowereldgiftcardpaymentmethodhandler",tcstestgiftcard:"handler_adyen_tcstestgiftcardpaymentmethodhandler",albelligiftcard:"handler_adyen_albelligiftcardpaymentmethodhandler",bijcadeaucard:"handler_adyen_bijenkorfgiftcardpaymentmethodhandler",vvvgiftcard:"handler_adyen_vvvgiftcardpaymentmethodhandler",genericgiftcard:"handler_adyen_genericgiftcardpaymentmethodhandler",gallgall:"handler_adyen_gallgallgiftcardpaymentmethodhandler",hmlingerie:"handler_adyen_hunkemollerlingeriegiftcardpaymentmethodhandler",beautycadeaukaart:"handler_adyen_beautygiftcardpaymentmethodhandler",svs:"handler_adyen_svsgiftcardpaymentmethodhandler",fashioncheque:"handler_adyen_fashionchequegiftcardpaymentmethodhandler",decadeaukaart:"handler_adyen_decadeaukaartgiftcardpaymentmethodhandler",mbway:"handler_adyen_mbwaypaymentmethodhandler",multibanco:"handler_adyen_multibancopaymentmethodhandler",wechatpayQR:"handler_adyen_wechatpayqrpaymentmethodhandler",wechatpayWeb:"handler_adyen_wechatpaywebpaymentmethodhandler",mobilepay:"handler_adyen_mobilepaypaymentmethodhandler",vipps:"handler_adyen_vippspaymentmethodhandler",affirm:"handler_adyen_affirmpaymentmethodhandler",paybright:"handler_adyen_paybrightpaymentmethodhandler",paybybank:"handler_adyen_openbankingpaymentmethodhandler"}};class l extends a.Z{init(){this._client=new o.Z,this.selectedAdyenPaymentMethod=this.getSelectedPaymentMethodKey(),this.confirmOrderForm=i.Z.querySelector(document,"#confirmOrderForm"),this.confirmFormSubmit=i.Z.querySelector(document,'#confirmOrderForm button[type="submit"]'),this.shoppingCartSummaryBlock=i.Z.querySelectorAll(document,".checkout-aside-summary-list"),this.minorUnitsQuotient=adyenCheckoutOptions.amount/adyenCheckoutOptions.totalPrice,this.giftcardDiscount=(adyenCheckoutOptions.giftcardDiscount/this.minorUnitsQuotient).toFixed(2),this.remainingAmount=(adyenCheckoutOptions.totalPrice-this.giftcardDiscount).toFixed(2),this.responseHandler=this.handlePaymentAction,this.adyenCheckout=Promise,this.initializeCheckoutComponent().then(function(){adyenCheckoutOptions.selectedPaymentMethodPluginId===adyenCheckoutOptions.adyenPluginId&&(adyenCheckoutOptions&&adyenCheckoutOptions.paymentStatusUrl&&adyenCheckoutOptions.checkoutOrderUrl&&adyenCheckoutOptions.paymentHandleUrl?(this.selectedAdyenPaymentMethod in c.componentsWithPayButton&&this.initializeCustomPayButton(),c.updatablePaymentMethods.includes(this.selectedAdyenPaymentMethod)&&!this.stateData?this.renderPaymentComponent(this.selectedAdyenPaymentMethod):this.confirmFormSubmit.addEventListener("click",this.onConfirmOrderSubmit.bind(this))):console.error("Adyen payment configuration missing."))}.bind(this)),parseInt(adyenCheckoutOptions.payInFullWithGiftcard,10)?parseInt(adyenCheckoutOptions.adyenGiftcardSelected,10)&&this.appendGiftcardSummary():this.appendGiftcardSummary()}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n,merchantAccount:a}=adyenCheckoutConfiguration,i=adyenCheckoutOptions.paymentMethodsResponse,o={locale:e,clientKey:t,environment:n,showPayButton:this.selectedAdyenPaymentMethod in c.componentsWithPayButton,hasHolderName:!0,paymentMethodsResponse:JSON.parse(i),onAdditionalDetails:this.handleOnAdditionalDetails.bind(this),countryCode:activeShippingAddress.country,paymentMethodsConfiguration:{card:{hasHolderName:!0,clickToPayConfiguration:{merchantDisplayName:a,shopperEmail:shopperDetails.shopperEmail}}}};this.adyenCheckout=await AdyenCheckout(o)}handleOnAdditionalDetails(e){this._client.post(`${adyenCheckoutOptions.paymentDetailsUrl}`,JSON.stringify({orderId:this.orderId,stateData:JSON.stringify(e.data)}),function(e){200===this._client._request.status?this.responseHandler(e):location.href=this.errorUrl.toString()}.bind(this))}onConfirmOrderSubmit(e){const t=i.Z.querySelector(document,"#confirmOrderForm");if(!t.checkValidity())return;e.preventDefault(),r.Z.create(document.body);const n=s.Z.serialize(t);this.confirmOrder(n)}renderPaymentComponent(e){if("oneclick"===e)return void this.renderStoredPaymentMethodComponents();let t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((function(t){return t.type===e}));if(0===t.length)return void("test"===this.adyenCheckout.options.environment&&console.error("Payment method configuration not found. ",e));let n=t[0];this.mountPaymentComponent(n,!1)}renderStoredPaymentMethodComponents(){this.adyenCheckout.paymentMethodsResponse.storedPaymentMethods.forEach((e=>{let t=`[data-adyen-stored-payment-method-id="${e.id}"]`;this.mountPaymentComponent(e,!0,t)})),this.hideStorePaymentMethodComponents();let e=null;i.Z.querySelectorAll(document,"[name=adyenStoredPaymentMethodId]").forEach((t=>{e||(e=t.value),t.addEventListener("change",this.showSelectedStoredPaymentMethod.bind(this))})),this.showSelectedStoredPaymentMethod(null,e)}showSelectedStoredPaymentMethod(e,t=null){this.hideStorePaymentMethodComponents();let n=`[data-adyen-stored-payment-method-id="${t=e?e.target.value:t}"]`;i.Z.querySelector(document,n).style.display="block"}hideStorePaymentMethodComponents(){i.Z.querySelectorAll(document,".stored-payment-component").forEach((e=>{e.style.display="none"}))}confirmOrder(e,t={}){const n=adyenCheckoutOptions.orderId;e.set("affiliateCode",adyenCheckoutOptions.affiliateCode),e.set("campaignCode",adyenCheckoutOptions.campaignCode),n?this.updatePayment(e,n,t):this.createOrder(e,t)}updatePayment(e,t,n){e.set("orderId",t),this._client.post(adyenCheckoutOptions.updatePaymentUrl,e,this.afterSetPayment.bind(this,n))}createOrder(e,t){parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&!parseInt(adyenCheckoutOptions.payInFullWithGiftcard,10)?this._client.post(adyenCheckoutOptions.createOrderUrl,JSON.stringify({orderAmount:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency}),function(n){const a=JSON.parse(n);"Success"===a.resultCode&&(t=Object.assign(t,{order:a})),this._client.post(adyenCheckoutOptions.checkoutOrderUrl,e,this.afterCreateOrder.bind(this,t))}.bind(this)):this._client.post(adyenCheckoutOptions.checkoutOrderUrl,e,this.afterCreateOrder.bind(this,t))}afterCreateOrder(e={},t){let n;try{n=JSON.parse(t)}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}this.orderId=n.id,this.finishUrl=new URL(location.origin+adyenCheckoutOptions.paymentFinishUrl),this.finishUrl.searchParams.set("orderId",n.id),this.errorUrl=new URL(location.origin+adyenCheckoutOptions.paymentErrorUrl),this.errorUrl.searchParams.set("orderId",n.id);let a={orderId:this.orderId,finishUrl:this.finishUrl.toString(),errorUrl:this.errorUrl.toString()};for(const t in e)a[t]=e[t];this._client.post(adyenCheckoutOptions.paymentHandleUrl,JSON.stringify(a),this.afterPayOrder.bind(this,this.orderId))}afterSetPayment(e={},t){try{JSON.parse(t).success&&this.afterCreateOrder(e,JSON.stringify({id:adyenCheckoutOptions.orderId}))}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}}afterPayOrder(e,t){try{t=JSON.parse(t),this.returnUrl=t.redirectUrl}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}this.returnUrl===this.errorUrl.toString()&&(location.href=this.returnUrl);try{this._client.post(`${adyenCheckoutOptions.paymentStatusUrl}`,JSON.stringify({orderId:e}),this.responseHandler.bind(this))}catch(e){console.log(e)}}handlePaymentAction(e){try{const t=JSON.parse(e);if((t.isFinal||"voucher"===t.action.type)&&(location.href=this.returnUrl),t.action){const e={};"threeDS2"===t.action.type&&(e.challengeWindowSize="05"),this.adyenCheckout.createFromAction(t.action,e).mount("[data-adyen-payment-action-container]");if(["threeDS2","qrCode"].includes(t.action.type))if(window.jQuery)$("[data-adyen-payment-action-modal]").modal({show:!0});else new bootstrap.Modal(document.getElementById("adyen-payment-action-modal"),{keyboard:!1}).show()}}catch(e){console.log(e)}}initializeCustomPayButton(){const e=c.componentsWithPayButton[this.selectedAdyenPaymentMethod];this.completePendingPayment(this.selectedAdyenPaymentMethod,e);let t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((e=>e.type===this.selectedAdyenPaymentMethod));if(t.length<1&&"googlepay"===this.selectedAdyenPaymentMethod&&(t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((e=>"paywithgoogle"===e.type))),t.length<1)return;let n=t[0];if(!adyenCheckoutOptions.amount)return void console.error("Failed to fetch Cart/Order total amount.");if(e.prePayRedirect)return void this.renderPrePaymentButton(e,n);const a=Object.assign(e.extra,n,{amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onClick:(t,n)=>{if(!e.onClick(t,n,this))return!1;r.Z.create(document.body)},onSubmit:function(t,n){if(t.isValid){let a={stateData:JSON.stringify(t.data)},i=s.Z.serialize(this.confirmOrderForm);"responseHandler"in e&&(this.responseHandler=e.responseHandler.bind(n,this)),this.confirmOrder(i,a)}else n.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",t)}.bind(this),onCancel:(t,n)=>{r.Z.remove(document.body),e.onCancel(t,n,this)},onError:(t,n)=>{"PayPal"===n.props.name&&"CANCEL"===t.name&&this._client.post(`${adyenCheckoutOptions.cancelOrderTransactionUrl}`,JSON.stringify({orderId:this.orderId})),r.Z.remove(document.body),e.onError(t,n,this),console.log(t)}}),i=this.adyenCheckout.create(n.type,a);try{"isAvailable"in i?i.isAvailable().then(function(){this.mountCustomPayButton(i)}.bind(this)).catch((e=>{console.log(n.type+" is not available",e)})):this.mountCustomPayButton(i)}catch(e){console.log(e)}}renderPrePaymentButton(e,t){"amazonpay"===t.type&&(e.extra=this.setAddressDetails(e.extra));const n=Object.assign(e.extra,t,{configuration:t.configuration,amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},onClick:(t,n)=>{if(!e.onClick(t,n,this))return!1;r.Z.create(document.body)},onError:(t,n)=>{r.Z.remove(document.body),e.onError(t,n,this),console.log(t)}});let a=this.adyenCheckout.create(t.type,n);this.mountCustomPayButton(a)}completePendingPayment(e,t){const n=new URL(location.href);if(n.searchParams.has(t.sessionKey)){r.Z.create(document.body);const a=this.adyenCheckout.create(e,{[t.sessionKey]:n.searchParams.get(t.sessionKey),showOrderButton:!1,onSubmit:function(e,t){if(e.isValid){let t={stateData:JSON.stringify(e.data)},n=s.Z.serialize(this.confirmOrderForm);this.confirmOrder(n,t)}}.bind(this)});this.mountCustomPayButton(a),a.submit()}}getSelectedPaymentMethodKey(){return Object.keys(c.paymentMethodTypeHandlers).find((e=>c.paymentMethodTypeHandlers[e]===adyenCheckoutOptions.selectedPaymentMethodHandler))}mountCustomPayButton(e){let t=document.querySelector("#confirmOrderForm");if(t){let n=t.querySelector("button[type=submit]");if(n&&!n.disabled){let a=document.createElement("div");a.id="adyen-confirm-button",a.setAttribute("data-adyen-confirm-button",""),t.appendChild(a),e.mount(a),n.remove()}}}mountPaymentComponent(e,t=!1,n=null){const a=Object.assign({},e,{data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onSubmit:function(e,t){if(e.isValid){let t={stateData:JSON.stringify(e.data)},n=s.Z.serialize(this.confirmOrderForm);r.Z.create(document.body),this.confirmOrder(n,t)}else t.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",e)}.bind(this)});!t&&"scheme"===e.type&&adyenCheckoutOptions.displaySaveCreditCardOption&&(a.enableStoreDetails=!0);let o=t?n:"#"+this.el.id;try{const t=this.adyenCheckout.create(e.type,a);t.mount(o),this.confirmFormSubmit.addEventListener("click",function(e){i.Z.querySelector(document,"#confirmOrderForm").checkValidity()&&(e.preventDefault(),this.el.parentNode.scrollIntoView({behavior:"smooth",block:"start"}),t.submit())}.bind(this))}catch(t){return console.error(e.type,t),!1}}appendGiftcardSummary(){if(parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&this.shoppingCartSummaryBlock.length){let e='
'+adyenCheckoutOptions.translationAdyenGiftcardDiscount+'
'+adyenCheckoutOptions.currencySymbol+this.giftcardDiscount+'
'+adyenCheckoutOptions.translationAdyenGiftcardRemainingAmount+'
'+adyenCheckoutOptions.currencySymbol+this.remainingAmount+"
";this.shoppingCartSummaryBlock[0].innerHTML+=e}}setAddressDetails(e){return""!==activeShippingAddress.phoneNumber?e.addressDetails={name:shopperDetails.firstName+" "+shopperDetails.lastName,addressLine1:activeShippingAddress.street,city:activeShippingAddress.city,postalCode:activeShippingAddress.postalCode,countryCode:activeShippingAddress.country,phoneNumber:activeShippingAddress.phoneNumber}:e.productType="PayOnly",e}}class h extends a.Z{init(){this._client=new o.Z,this.adyenCheckout=Promise,this.initializeCheckoutComponent().bind(this)}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,{currency:a,values:i,backgroundUrl:o,logoUrl:r,name:d,description:s,url:c}=adyenGivingConfiguration,l={locale:e,clientKey:t,environment:n},h={amounts:{currency:a,values:i.split(",").map((e=>Number(e)))},backgroundUrl:o,logoUrl:r,description:s,name:d,url:c,showCancelButton:!0,onDonate:this.handleOnDonate.bind(this),onCancel:this.handleOnCancel.bind(this)};this.adyenCheckout=await AdyenCheckout(l),this.adyenCheckout.create("donation",h).mount("#donation-container")}handleOnDonate(e,t){const n=adyenGivingConfiguration.orderId;let a={stateData:JSON.stringify(e.data),orderId:n};a.returnUrl=window.location.href,this._client.post(`${adyenGivingConfiguration.donationEndpointUrl}`,JSON.stringify({...a}),function(e){200!==this._client._request.status?t.setStatus("error"):t.setStatus("success")}.bind(this))}handleOnCancel(){let e=adyenGivingConfiguration.continueActionUrl;window.location=e}}class y extends a.Z{init(){this.adyenCheckout=Promise,this.initializeCheckoutComponent().bind(this)}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,{action:a}=adyenSuccessActionConfiguration,i={locale:e,clientKey:t,environment:n};this.adyenCheckout=await AdyenCheckout(i),this.adyenCheckout.createFromAction(JSON.parse(a)).mount("#success-action-container")}}const m=window.PluginManager;m.register("CartPlugin",d,"#adyen-giftcards-container"),m.register("ConfirmOrderPlugin",l,"#adyen-payment-checkout-mask"),m.register("AdyenGivingPlugin",h,"#adyen-giving-container"),m.register("AdyenSuccessAction",y,"#adyen-success-action-container")}},e=>{e.O(0,["vendor-node","vendor-shared"],(()=>{return t=7815,e(e.s=t);var t}));e.O()}]); \ No newline at end of file +"use strict";(self.webpackChunk=self.webpackChunk||[]).push([["adyen-payment-shopware6"],{7815:(e,t,n)=>{var a=n(6285),i=n(3206),o=n(8254),r=n(4690);class d extends a.Z{init(){let e=this;this._client=new o.Z,this.adyenCheckout=Promise,this.paymentMethodInstance=null,this.selectedGiftcard=null,this.initializeCheckoutComponent().then(function(){this.observeGiftcardSelection()}.bind(this)),this.adyenGiftcardDropDown=i.Z.querySelectorAll(document,"#giftcardDropdown"),this.adyenGiftcard=i.Z.querySelectorAll(document,".adyen-giftcard"),this.giftcardHeader=i.Z.querySelector(document,".adyen-giftcard-header"),this.giftcardItem=i.Z.querySelector(document,".adyen-giftcard-item"),this.giftcardComponentClose=i.Z.querySelector(document,".adyen-close-giftcard-component"),this.minorUnitsQuotient=adyenGiftcardsConfiguration.totalInMinorUnits/adyenGiftcardsConfiguration.totalPrice,this.giftcardDiscount=adyenGiftcardsConfiguration.giftcardDiscount,this.remainingAmount=(adyenGiftcardsConfiguration.totalPrice-this.giftcardDiscount).toFixed(2),this.remainingGiftcardBalance=(adyenGiftcardsConfiguration.giftcardBalance/this.minorUnitsQuotient).toFixed(2),this.shoppingCartSummaryBlock=i.Z.querySelectorAll(document,".checkout-aside-summary-list"),this.offCanvasSummaryDetails=null,this.shoppingCartSummaryDetails=null,this.giftcardComponentClose.onclick=function(t){t.currentTarget.style.display="none",e.selectedGiftcard=null,e.giftcardItem.innerHTML="",e.giftcardHeader.innerHTML=" ",e.paymentMethodInstance&&e.paymentMethodInstance.unmount()},document.getElementById("showGiftcardButton").addEventListener("click",(function(){this.style.display="none",document.getElementById("giftcardDropdown").style.display="block"})),window.addEventListener("DOMContentLoaded",(()=>{document.getElementById("giftcardsContainer").addEventListener("click",(e=>{if(e.target.classList.contains("adyen-remove-giftcard")){const t=e.target.getAttribute("dataid");this.removeGiftcard(t)}}))})),window.addEventListener("DOMContentLoaded",(e=>{parseInt(adyenGiftcardsConfiguration.giftcardDiscount,10)&&this.fetchRedeemedGiftcards()}))}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,a={locale:e,clientKey:t,environment:n,amount:{currency:adyenGiftcardsConfiguration.currency,value:adyenGiftcardsConfiguration.totalInMinorUnits}};this.adyenCheckout=await AdyenCheckout(a)}observeGiftcardSelection(){let e=this,t=document.getElementById("giftcardDropdown"),n=document.querySelector(".btn-outline-info");t.addEventListener("change",(function(){t.value&&(e.selectedGiftcard=JSON.parse(event.currentTarget.options[event.currentTarget.selectedIndex].dataset.giftcard),e.mountGiftcardComponent(e.selectedGiftcard),t.value="",n.style.display="none")}))}mountGiftcardComponent(e){this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),this.giftcardItem.innerHTML="",r.Z.create(i.Z.querySelector(document,"#adyen-giftcard-component"));var t=document.createElement("img");t.src="https://checkoutshopper-live.adyen.com/checkoutshopper/images/logos/"+e.brand+".svg",t.classList.add("adyen-giftcard-logo"),this.giftcardItem.insertBefore(t,this.giftcardItem.firstChild),this.giftcardHeader.innerHTML=e.name,this.giftcardComponentClose.style.display="block";const n=Object.assign({},e,{showPayButton:!0,onBalanceCheck:this.handleBalanceCheck.bind(this,e)});try{this.paymentMethodInstance=this.adyenCheckout.create("giftcard",n),this.paymentMethodInstance.mount("#adyen-giftcard-component")}catch(e){console.log("giftcard not available")}r.Z.remove(i.Z.querySelector(document,"#adyen-giftcard-component"))}handleBalanceCheck(e,t,n,a){let i={};i.paymentMethod=JSON.stringify(a.paymentMethod),i.amount=JSON.stringify({currency:adyenGiftcardsConfiguration.currency,value:adyenGiftcardsConfiguration.totalInMinorUnits}),this._client.post(`${adyenGiftcardsConfiguration.checkBalanceUrl}`,JSON.stringify(i),function(t){if((t=JSON.parse(t)).hasOwnProperty("pspReference")){const n=t.transactionLimit?parseFloat(t.transactionLimit.value):parseFloat(t.balance.value);a.giftcard={currency:adyenGiftcardsConfiguration.currency,value:(n/this.minorUnitsQuotient).toFixed(2),title:e.name},this.saveGiftcardStateData(a)}else n(t.resultCode)}.bind(this))}fetchRedeemedGiftcards(){this._client.get(adyenGiftcardsConfiguration.fetchRedeemedGiftcardsUrl,function(e){e=JSON.parse(e);let t=document.getElementById("giftcardsContainer"),n=document.querySelector(".btn-outline-info");t.innerHTML="",e.redeemedGiftcards.giftcards.forEach((function(e){let n=parseFloat(e.deductedAmount);n=n.toFixed(2);let a=adyenGiftcardsConfiguration.translationAdyenGiftcardDeductedBalance+": "+adyenGiftcardsConfiguration.currencySymbol+n,i=document.createElement("div");var o=document.createElement("img");o.src="https://checkoutshopper-live.adyen.com/checkoutshopper/images/logos/"+e.brand+".svg",o.classList.add("adyen-giftcard-logo");let r=document.createElement("a");r.href="#",r.textContent=adyenGiftcardsConfiguration.translationAdyenGiftcardRemove,r.setAttribute("dataid",e.stateDataId),r.classList.add("adyen-remove-giftcard"),r.style.display="block",i.appendChild(o),i.innerHTML+=`${e.title}`,i.appendChild(r),i.innerHTML+=`

${a}


`,t.appendChild(i)})),this.remainingAmount=e.redeemedGiftcards.remainingAmount,this.giftcardDiscount=e.redeemedGiftcards.totalDiscount,this.paymentMethodInstance&&this.paymentMethodInstance.unmount(),this.giftcardComponentClose.style.display="none",this.giftcardItem.innerHTML="",this.giftcardHeader.innerHTML=" ",this.appendGiftcardSummary(),this.remainingAmount>0?n.style.display="block":(this.adyenGiftcardDropDown.length>0&&(this.adyenGiftcardDropDown[0].style.display="none"),n.style.display="none");document.getElementById("giftcardsContainer")}.bind(this))}saveGiftcardStateData(e){e=JSON.stringify(e),this._client.post(adyenGiftcardsConfiguration.setGiftcardUrl,JSON.stringify({stateData:e}),function(e){"token"in(e=JSON.parse(e))&&(this.fetchRedeemedGiftcards(),r.Z.remove(document.body))}.bind(this))}removeGiftcard(e){r.Z.create(document.body),this._client.post(adyenGiftcardsConfiguration.removeGiftcardUrl,JSON.stringify({stateDataId:e}),(e=>{"token"in(e=JSON.parse(e))&&(this.fetchRedeemedGiftcards(),r.Z.remove(document.body))}))}appendGiftcardSummary(){if(this.shoppingCartSummaryBlock.length){let e=this.shoppingCartSummaryBlock[0].querySelectorAll(".adyen-giftcard-summary");for(let t=0;t
'+adyenGiftcardsConfiguration.currencySymbol+e+'
'+adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingAmount+'
'+adyenGiftcardsConfiguration.currencySymbol+t+"
";this.shoppingCartSummaryBlock[0].innerHTML+=n}}}var s=n(207);const c={updatablePaymentMethods:["scheme","ideal","sepadirectdebit","oneclick","dotpay","bcmc","bcmc_mobile","blik","eps","facilypay_3x","facilypay_4x","facilypay_6x","facilypay_10x","facilypay_12x","afterpay_default","ratepay","ratepay_directdebit","giftcard","paybright","affirm","multibanco","mbway","vipps","mobilepay","wechatpayQR","wechatpayWeb","paybybank"],componentsWithPayButton:{applepay:{extra:{},onClick(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)}},googlepay:{extra:{buttonSizeMode:"fill"},onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)},onError:function(e,t,n){"CANCELED"!==e.statusCode&&("statusMessage"in e?console.log(e.statusMessage):console.log(e.statusCode))}},paypal:{extra:{},onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()},onError:function(e,t,n){t.setStatus("ready"),window.location.href=n.errorUrl.toString()},onCancel:function(e,t,n){t.setStatus("ready"),window.location.href=n.errorUrl.toString()},responseHandler:function(e,t){try{(t=JSON.parse(t)).isFinal&&(location.href=e.returnUrl),this.handleAction(t.action)}catch(e){console.error(e)}}},amazonpay:{extra:{productType:"PayAndShip",checkoutMode:"ProcessOrder",returnUrl:location.href},prePayRedirect:!0,sessionKey:"amazonCheckoutSessionId",onClick:function(e,t,n){return n.confirmOrderForm.checkValidity()?(e(),!0):(t(),!1)},onError:(e,t)=>{console.log(e),t.setStatus("ready")}}},paymentMethodTypeHandlers:{scheme:"handler_adyen_cardspaymentmethodhandler",ideal:"handler_adyen_idealpaymentmethodhandler",klarna:"handler_adyen_klarnapaylaterpaymentmethodhandler",klarna_account:"handler_adyen_klarnaaccountpaymentmethodhandler",klarna_paynow:"handler_adyen_klarnapaynowpaymentmethodhandler",ratepay:"handler_adyen_ratepaypaymentmethodhandler",ratepay_directdebit:"handler_adyen_ratepaydirectdebitpaymentmethodhandler",sepadirectdebit:"handler_adyen_sepapaymentmethodhandler",sofort:"handler_adyen_sofortpaymentmethodhandler",paypal:"handler_adyen_paypalpaymentmethodhandler",oneclick:"handler_adyen_oneclickpaymentmethodhandler",giropay:"handler_adyen_giropaypaymentmethodhandler",applepay:"handler_adyen_applepaypaymentmethodhandler",googlepay:"handler_adyen_googlepaypaymentmethodhandler",dotpay:"handler_adyen_dotpaypaymentmethodhandler",bcmc:"handler_adyen_bancontactcardpaymentmethodhandler",bcmc_mobile:"handler_adyen_bancontactmobilepaymentmethodhandler",amazonpay:"handler_adyen_amazonpaypaymentmethodhandler",twint:"handler_adyen_twintpaymentmethodhandler",eps:"handler_adyen_epspaymentmethodhandler",swish:"handler_adyen_swishpaymentmethodhandler",alipay:"handler_adyen_alipaypaymentmethodhandler",alipay_hk:"handler_adyen_alipayhkpaymentmethodhandler",blik:"handler_adyen_blikpaymentmethodhandler",clearpay:"handler_adyen_clearpaypaymentmethodhandler",facilypay_3x:"handler_adyen_facilypay3xpaymentmethodhandler",facilypay_4x:"handler_adyen_facilypay4xpaymentmethodhandler",facilypay_6x:"handler_adyen_facilypay6xpaymentmethodhandler",facilypay_10x:"handler_adyen_facilypay10xpaymentmethodhandler",facilypay_12x:"handler_adyen_facilypay12xpaymentmethodhandler",afterpay_default:"handler_adyen_afterpaydefaultpaymentmethodhandler",trustly:"handler_adyen_trustlypaymentmethodhandler",paysafecard:"handler_adyen_paysafecardpaymentmethodhandler",giftcard:"handler_adyen_giftcardpaymentmethodhandler",mbway:"handler_adyen_mbwaypaymentmethodhandler",multibanco:"handler_adyen_multibancopaymentmethodhandler",wechatpayQR:"handler_adyen_wechatpayqrpaymentmethodhandler",wechatpayWeb:"handler_adyen_wechatpaywebpaymentmethodhandler",mobilepay:"handler_adyen_mobilepaypaymentmethodhandler",vipps:"handler_adyen_vippspaymentmethodhandler",affirm:"handler_adyen_affirmpaymentmethodhandler",paybright:"handler_adyen_paybrightpaymentmethodhandler",paybybank:"handler_adyen_openbankingpaymentmethodhandler"}};class l extends a.Z{init(){this._client=new o.Z,this._client=new o.Z,this.selectedAdyenPaymentMethod=this.getSelectedPaymentMethodKey(),this.confirmOrderForm=i.Z.querySelector(document,"#confirmOrderForm"),this.confirmFormSubmit=i.Z.querySelector(document,'#confirmOrderForm button[type="submit"]'),this.shoppingCartSummaryBlock=i.Z.querySelectorAll(document,".checkout-aside-summary-list"),this.minorUnitsQuotient=adyenCheckoutOptions.amount/adyenCheckoutOptions.totalPrice,this.giftcardDiscount=adyenCheckoutOptions.giftcardDiscount,this.remainingAmount=adyenCheckoutOptions.totalPrice-this.giftcardDiscount,this.responseHandler=this.handlePaymentAction,this.adyenCheckout=Promise,this.initializeCheckoutComponent().then(function(){adyenCheckoutOptions.selectedPaymentMethodPluginId===adyenCheckoutOptions.adyenPluginId&&(adyenCheckoutOptions&&adyenCheckoutOptions.paymentStatusUrl&&adyenCheckoutOptions.checkoutOrderUrl&&adyenCheckoutOptions.paymentHandleUrl?(this.selectedAdyenPaymentMethod in c.componentsWithPayButton&&this.initializeCustomPayButton(),c.updatablePaymentMethods.includes(this.selectedAdyenPaymentMethod)&&!this.stateData?this.renderPaymentComponent(this.selectedAdyenPaymentMethod):this.confirmFormSubmit.addEventListener("click",this.onConfirmOrderSubmit.bind(this))):console.error("Adyen payment configuration missing."))}.bind(this)),adyenCheckoutOptions.payInFullWithGiftcard>0?parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&this.appendGiftcardSummary():this.appendGiftcardSummary()}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n,merchantAccount:a}=adyenCheckoutConfiguration,i=adyenCheckoutOptions.paymentMethodsResponse,o={locale:e,clientKey:t,environment:n,showPayButton:this.selectedAdyenPaymentMethod in c.componentsWithPayButton,hasHolderName:!0,paymentMethodsResponse:JSON.parse(i),onAdditionalDetails:this.handleOnAdditionalDetails.bind(this),countryCode:activeShippingAddress.country,paymentMethodsConfiguration:{card:{hasHolderName:!0,clickToPayConfiguration:{merchantDisplayName:a,shopperEmail:shopperDetails.shopperEmail}}}};this.adyenCheckout=await AdyenCheckout(o)}handleOnAdditionalDetails(e){this._client.post(`${adyenCheckoutOptions.paymentDetailsUrl}`,JSON.stringify({orderId:this.orderId,stateData:JSON.stringify(e.data)}),function(e){200===this._client._request.status?this.responseHandler(e):location.href=this.errorUrl.toString()}.bind(this))}onConfirmOrderSubmit(e){const t=i.Z.querySelector(document,"#confirmOrderForm");if(!t.checkValidity())return;e.preventDefault(),r.Z.create(document.body);const n=s.Z.serialize(t);this.confirmOrder(n)}renderPaymentComponent(e){if("oneclick"===e)return void this.renderStoredPaymentMethodComponents();if("giftcard"===e)return;let t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((function(t){return t.type===e}));if(0===t.length)return void("test"===this.adyenCheckout.options.environment&&console.error("Payment method configuration not found. ",e));let n=t[0];this.mountPaymentComponent(n,!1)}renderStoredPaymentMethodComponents(){this.adyenCheckout.paymentMethodsResponse.storedPaymentMethods.forEach((e=>{let t=`[data-adyen-stored-payment-method-id="${e.id}"]`;this.mountPaymentComponent(e,!0,t)})),this.hideStorePaymentMethodComponents();let e=null;i.Z.querySelectorAll(document,"[name=adyenStoredPaymentMethodId]").forEach((t=>{e||(e=t.value),t.addEventListener("change",this.showSelectedStoredPaymentMethod.bind(this))})),this.showSelectedStoredPaymentMethod(null,e)}showSelectedStoredPaymentMethod(e,t=null){this.hideStorePaymentMethodComponents();let n=`[data-adyen-stored-payment-method-id="${t=e?e.target.value:t}"]`;i.Z.querySelector(document,n).style.display="block"}hideStorePaymentMethodComponents(){i.Z.querySelectorAll(document,".stored-payment-component").forEach((e=>{e.style.display="none"}))}confirmOrder(e,t={}){const n=adyenCheckoutOptions.orderId;e.set("affiliateCode",adyenCheckoutOptions.affiliateCode),e.set("campaignCode",adyenCheckoutOptions.campaignCode),n?this.updatePayment(e,n,t):this.createOrder(e,t)}updatePayment(e,t,n){e.set("orderId",t),this._client.post(adyenCheckoutOptions.updatePaymentUrl,e,this.afterSetPayment.bind(this,n))}createOrder(e,t){this._client.post(adyenCheckoutOptions.checkoutOrderUrl,e,this.afterCreateOrder.bind(this,t))}afterCreateOrder(e={},t){let n;try{n=JSON.parse(t)}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}this.orderId=n.id,this.finishUrl=new URL(location.origin+adyenCheckoutOptions.paymentFinishUrl),this.finishUrl.searchParams.set("orderId",n.id),this.errorUrl=new URL(location.origin+adyenCheckoutOptions.paymentErrorUrl),this.errorUrl.searchParams.set("orderId",n.id);let a={orderId:this.orderId,finishUrl:this.finishUrl.toString(),errorUrl:this.errorUrl.toString()};for(const t in e)a[t]=e[t];this._client.post(adyenCheckoutOptions.paymentHandleUrl,JSON.stringify(a),this.afterPayOrder.bind(this,this.orderId))}afterSetPayment(e={},t){try{JSON.parse(t).success&&this.afterCreateOrder(e,JSON.stringify({id:adyenCheckoutOptions.orderId}))}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}}afterPayOrder(e,t){try{t=JSON.parse(t),this.returnUrl=t.redirectUrl}catch(e){return r.Z.remove(document.body),void console.log("Error: invalid response from Shopware API",t)}this.returnUrl===this.errorUrl.toString()&&(location.href=this.returnUrl);try{this._client.post(`${adyenCheckoutOptions.paymentStatusUrl}`,JSON.stringify({orderId:e}),this.responseHandler.bind(this))}catch(e){console.log(e)}}handlePaymentAction(e){try{const t=JSON.parse(e);if((t.isFinal||"voucher"===t.action.type)&&(location.href=this.returnUrl),t.action){const e={};"threeDS2"===t.action.type&&(e.challengeWindowSize="05"),this.adyenCheckout.createFromAction(t.action,e).mount("[data-adyen-payment-action-container]");if(["threeDS2","qrCode"].includes(t.action.type))if(window.jQuery)$("[data-adyen-payment-action-modal]").modal({show:!0});else new bootstrap.Modal(document.getElementById("adyen-payment-action-modal"),{keyboard:!1}).show()}}catch(e){console.log(e)}}initializeCustomPayButton(){const e=c.componentsWithPayButton[this.selectedAdyenPaymentMethod];this.completePendingPayment(this.selectedAdyenPaymentMethod,e);let t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((e=>e.type===this.selectedAdyenPaymentMethod));if(t.length<1&&"googlepay"===this.selectedAdyenPaymentMethod&&(t=this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter((e=>"paywithgoogle"===e.type))),t.length<1)return;let n=t[0];if(!adyenCheckoutOptions.amount)return void console.error("Failed to fetch Cart/Order total amount.");if(e.prePayRedirect)return void this.renderPrePaymentButton(e,n);const a=Object.assign(e.extra,n,{amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onClick:(t,n)=>{if(!e.onClick(t,n,this))return!1;r.Z.create(document.body)},onSubmit:function(t,n){if(t.isValid){let a={stateData:JSON.stringify(t.data)},i=s.Z.serialize(this.confirmOrderForm);"responseHandler"in e&&(this.responseHandler=e.responseHandler.bind(n,this)),this.confirmOrder(i,a)}else n.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",t)}.bind(this),onCancel:(t,n)=>{r.Z.remove(document.body),e.onCancel(t,n,this)},onError:(t,n)=>{"PayPal"===n.props.name&&"CANCEL"===t.name&&this._client.post(`${adyenCheckoutOptions.cancelOrderTransactionUrl}`,JSON.stringify({orderId:this.orderId})),r.Z.remove(document.body),e.onError(t,n,this),console.log(t)}}),i=this.adyenCheckout.create(n.type,a);try{"isAvailable"in i?i.isAvailable().then(function(){this.mountCustomPayButton(i)}.bind(this)).catch((e=>{console.log(n.type+" is not available",e)})):this.mountCustomPayButton(i)}catch(e){console.log(e)}}renderPrePaymentButton(e,t){"amazonpay"===t.type&&(e.extra=this.setAddressDetails(e.extra));const n=Object.assign(e.extra,t,{configuration:t.configuration,amount:{value:adyenCheckoutOptions.amount,currency:adyenCheckoutOptions.currency},onClick:(t,n)=>{if(!e.onClick(t,n,this))return!1;r.Z.create(document.body)},onError:(t,n)=>{r.Z.remove(document.body),e.onError(t,n,this),console.log(t)}});let a=this.adyenCheckout.create(t.type,n);this.mountCustomPayButton(a)}completePendingPayment(e,t){const n=new URL(location.href);if(n.searchParams.has(t.sessionKey)){r.Z.create(document.body);const a=this.adyenCheckout.create(e,{[t.sessionKey]:n.searchParams.get(t.sessionKey),showOrderButton:!1,onSubmit:function(e,t){if(e.isValid){let t={stateData:JSON.stringify(e.data)},n=s.Z.serialize(this.confirmOrderForm);this.confirmOrder(n,t)}}.bind(this)});this.mountCustomPayButton(a),a.submit()}}getSelectedPaymentMethodKey(){return Object.keys(c.paymentMethodTypeHandlers).find((e=>c.paymentMethodTypeHandlers[e]===adyenCheckoutOptions.selectedPaymentMethodHandler))}mountCustomPayButton(e){let t=document.querySelector("#confirmOrderForm");if(t){let n=t.querySelector("button[type=submit]");if(n&&!n.disabled){let a=document.createElement("div");a.id="adyen-confirm-button",a.setAttribute("data-adyen-confirm-button",""),t.appendChild(a),e.mount(a),n.remove()}}}mountPaymentComponent(e,t=!1,n=null){const a=Object.assign({},e,{data:{personalDetails:shopperDetails,billingAddress:activeBillingAddress,deliveryAddress:activeShippingAddress},onSubmit:function(e,t){if(e.isValid){let t={stateData:JSON.stringify(e.data)},n=s.Z.serialize(this.confirmOrderForm);r.Z.create(document.body),this.confirmOrder(n,t)}else t.showValidation(),"test"===this.adyenCheckout.options.environment&&console.log("Payment failed: ",e)}.bind(this)});!t&&"scheme"===e.type&&adyenCheckoutOptions.displaySaveCreditCardOption&&(a.enableStoreDetails=!0);let o=t?n:"#"+this.el.id;try{const t=this.adyenCheckout.create(e.type,a);t.mount(o),this.confirmFormSubmit.addEventListener("click",function(e){i.Z.querySelector(document,"#confirmOrderForm").checkValidity()&&(e.preventDefault(),this.el.parentNode.scrollIntoView({behavior:"smooth",block:"start"}),t.submit())}.bind(this))}catch(t){return console.error(e.type,t),!1}}appendGiftcardSummary(){if(parseInt(adyenCheckoutOptions.giftcardDiscount,10)&&this.shoppingCartSummaryBlock.length){let e=parseFloat(this.giftcardDiscount).toFixed(2),t=parseFloat(this.remainingAmount).toFixed(2),n='
'+adyenCheckoutOptions.translationAdyenGiftcardDiscount+'
'+adyenCheckoutOptions.currencySymbol+e+'
'+adyenCheckoutOptions.translationAdyenGiftcardRemainingAmount+'
'+adyenCheckoutOptions.currencySymbol+t+"
";this.shoppingCartSummaryBlock[0].innerHTML+=n}}setAddressDetails(e){return""!==activeShippingAddress.phoneNumber?e.addressDetails={name:shopperDetails.firstName+" "+shopperDetails.lastName,addressLine1:activeShippingAddress.street,city:activeShippingAddress.city,postalCode:activeShippingAddress.postalCode,countryCode:activeShippingAddress.country,phoneNumber:activeShippingAddress.phoneNumber}:e.productType="PayOnly",e}}class h extends a.Z{init(){this._client=new o.Z,this.adyenCheckout=Promise,this.initializeCheckoutComponent().bind(this)}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,{currency:a,values:i,backgroundUrl:o,logoUrl:r,name:d,description:s,url:c}=adyenGivingConfiguration,l={locale:e,clientKey:t,environment:n},h={amounts:{currency:a,values:i.split(",").map((e=>Number(e)))},backgroundUrl:o,logoUrl:r,description:s,name:d,url:c,showCancelButton:!0,onDonate:this.handleOnDonate.bind(this),onCancel:this.handleOnCancel.bind(this)};this.adyenCheckout=await AdyenCheckout(l),this.adyenCheckout.create("donation",h).mount("#donation-container")}handleOnDonate(e,t){const n=adyenGivingConfiguration.orderId;let a={stateData:JSON.stringify(e.data),orderId:n};a.returnUrl=window.location.href,this._client.post(`${adyenGivingConfiguration.donationEndpointUrl}`,JSON.stringify({...a}),function(e){200!==this._client._request.status?t.setStatus("error"):t.setStatus("success")}.bind(this))}handleOnCancel(){let e=adyenGivingConfiguration.continueActionUrl;window.location=e}}class y extends a.Z{init(){this.adyenCheckout=Promise,this.initializeCheckoutComponent().bind(this)}async initializeCheckoutComponent(){const{locale:e,clientKey:t,environment:n}=adyenCheckoutConfiguration,{action:a}=adyenSuccessActionConfiguration,i={locale:e,clientKey:t,environment:n};this.adyenCheckout=await AdyenCheckout(i),this.adyenCheckout.createFromAction(JSON.parse(a)).mount("#success-action-container")}}const m=window.PluginManager;m.register("CartPlugin",d,"#adyen-giftcards-container"),m.register("ConfirmOrderPlugin",l,"#adyen-payment-checkout-mask"),m.register("AdyenGivingPlugin",h,"#adyen-giving-container"),m.register("AdyenSuccessAction",y,"#adyen-success-action-container")}},e=>{e.O(0,["vendor-node","vendor-shared"],(()=>{return t=7815,e(e.s=t);var t}));e.O()}]); \ No newline at end of file diff --git a/src/Resources/app/storefront/src/cart/cart.plugin.js b/src/Resources/app/storefront/src/cart/cart.plugin.js index fe8f6ce4..698d3730 100644 --- a/src/Resources/app/storefront/src/cart/cart.plugin.js +++ b/src/Resources/app/storefront/src/cart/cart.plugin.js @@ -28,7 +28,6 @@ import ElementLoadingIndicatorUtil from 'src/utility/loading-indicator/element-l export default class CartPlugin extends Plugin { init() { let self = this; - this._client = new HttpClient(); this.adyenCheckout = Promise; this.paymentMethodInstance = null; @@ -36,38 +35,53 @@ export default class CartPlugin extends Plugin { this.initializeCheckoutComponent().then(function () { this.observeGiftcardSelection(); }.bind(this)); + this.adyenGiftcardDropDown = DomAccess.querySelectorAll(document, '#giftcardDropdown'); this.adyenGiftcard = DomAccess.querySelectorAll(document, '.adyen-giftcard'); this.giftcardHeader = DomAccess.querySelector(document, '.adyen-giftcard-header'); + this.giftcardItem = DomAccess.querySelector(document, '.adyen-giftcard-item'); this.giftcardComponentClose = DomAccess.querySelector(document, '.adyen-close-giftcard-component'); - this.removeGiftcardButton = DomAccess.querySelector(document, '.adyen-remove-giftcard'); - this.remainingBalanceField = DomAccess.querySelector(document, '.adyen-remaining-balance'); this.minorUnitsQuotient = adyenGiftcardsConfiguration.totalInMinorUnits/adyenGiftcardsConfiguration.totalPrice; - this.giftcardDiscount = (adyenGiftcardsConfiguration.giftcardDiscount / this.minorUnitsQuotient).toFixed(2); + this.giftcardDiscount = adyenGiftcardsConfiguration.giftcardDiscount; this.remainingAmount = (adyenGiftcardsConfiguration.totalPrice - this.giftcardDiscount).toFixed(2); this.remainingGiftcardBalance = (adyenGiftcardsConfiguration.giftcardBalance / this.minorUnitsQuotient).toFixed(2); this.shoppingCartSummaryBlock = DomAccess.querySelectorAll(document, '.checkout-aside-summary-list'); this.offCanvasSummaryDetails = null; this.shoppingCartSummaryDetails = null; - this.giftcardComponentClose.onclick = function (event) { event.currentTarget.style.display = 'none'; self.selectedGiftcard = null; + self.giftcardItem.innerHTML = ''; self.giftcardHeader.innerHTML = ' '; if (self.paymentMethodInstance) { self.paymentMethodInstance.unmount(); } }; + + document.getElementById("showGiftcardButton").addEventListener("click", function() { + // Hide the anchor tag + this.style.display = "none"; - this.removeGiftcardButton.onclick = function (event) { - self.removeGiftcard(); - }; + // Show the select dropdown + document.getElementById("giftcardDropdown").style.display = "block"; + }); + + window.addEventListener('DOMContentLoaded', () => { + const giftcardsList = document.getElementById('giftcardsContainer'); + giftcardsList.addEventListener('click', (event) => { + if (event.target.classList.contains('adyen-remove-giftcard')) { + const storeId = event.target.getAttribute('dataid'); + this.removeGiftcard(storeId); + } + }); + }); window.addEventListener("DOMContentLoaded", (event) => { if (parseInt(adyenGiftcardsConfiguration.giftcardDiscount, 10)) { - this.onGiftcardSelected(); + this.fetchRedeemedGiftcards(); } }); + } async initializeCheckoutComponent() { @@ -80,7 +94,7 @@ export default class CartPlugin extends Plugin { amount: { currency: adyenGiftcardsConfiguration.currency, value: adyenGiftcardsConfiguration.totalInMinorUnits, - } + }, }; this.adyenCheckout = await AdyenCheckout(ADYEN_CHECKOUT_CONFIG); @@ -88,29 +102,39 @@ export default class CartPlugin extends Plugin { observeGiftcardSelection() { let self = this; - - for (let i=0; i < this.adyenGiftcard.length; i++) { - this.adyenGiftcard[i].onclick = function() { - self.selectedGiftcard = JSON.parse(event.currentTarget.dataset.giftcard); - self.mountGiftcardComponent(self.selectedGiftcard.extensions.adyenGiftcardData[0]); + let giftcardDropdown = document.getElementById('giftcardDropdown'); + let addButton = document.querySelector('.btn-outline-info'); + giftcardDropdown.addEventListener('change', function () { + if (giftcardDropdown.value) { + self.selectedGiftcard = JSON.parse(event.currentTarget.options[event.currentTarget.selectedIndex].dataset.giftcard); + self.mountGiftcardComponent(self.selectedGiftcard); + giftcardDropdown.value = ""; + addButton.style.display = "none"; } - } + }); } mountGiftcardComponent(giftcard) { - if (this.giftcardDiscount > 0) { - return; - } if (this.paymentMethodInstance) { this.paymentMethodInstance.unmount(); } + this.giftcardItem.innerHTML = ''; ElementLoadingIndicatorUtil.create(DomAccess.querySelector(document, '#adyen-giftcard-component')); + + //Add Giftcard image and name + var imgElement = document.createElement('img'); + imgElement.src = 'https://checkoutshopper-live.adyen.com/checkoutshopper/images/logos/'+giftcard.brand+'.svg'; + imgElement.classList.add('adyen-giftcard-logo'); + + this.giftcardItem.insertBefore(imgElement, this.giftcardItem.firstChild); this.giftcardHeader.innerHTML = giftcard.name; + this.giftcardComponentClose.style.display = 'block'; const giftcardConfiguration = Object.assign({}, giftcard, { showPayButton: true, - onBalanceCheck: this.handleBalanceCheck.bind(this), + onBalanceCheck: this.handleBalanceCheck.bind(this, giftcard), }); + try { this.paymentMethodInstance = this.adyenCheckout.create('giftcard', giftcardConfiguration); this.paymentMethodInstance.mount('#adyen-giftcard-component'); @@ -120,122 +144,152 @@ export default class CartPlugin extends Plugin { ElementLoadingIndicatorUtil.remove(DomAccess.querySelector(document, '#adyen-giftcard-component')); } - handleBalanceCheck(resolve, reject, data) { + handleBalanceCheck(giftcard, resolve, reject, data) { let params = {}; params.paymentMethod = JSON.stringify(data.paymentMethod); params.amount = JSON.stringify({ "currency":adyenGiftcardsConfiguration.currency, "value": adyenGiftcardsConfiguration.totalInMinorUnits }); + this._client.post( `${adyenGiftcardsConfiguration.checkBalanceUrl}`, JSON.stringify(params), function (response) { response = JSON.parse(response); if (!response.hasOwnProperty('pspReference')) { - console.error(response.resultCode); reject(response.resultCode); } else { // 0. compare balance to total amount to be paid - const consumableBalance = response.transactionLimit ? parseFloat(response.transactionLimit.value) : parseFloat(response.balance.value); - let remainingGiftcardBalanceMinorUnits = (consumableBalance - adyenGiftcardsConfiguration.totalInMinorUnits); - if (consumableBalance >= adyenGiftcardsConfiguration.totalInMinorUnits) { - this.remainingGiftcardBalance = (remainingGiftcardBalanceMinorUnits / this.minorUnitsQuotient).toFixed(2); - this.setGiftcardAsPaymentMethod(data, remainingGiftcardBalanceMinorUnits); - } else { - this.remainingAmount = ((adyenGiftcardsConfiguration.totalInMinorUnits - consumableBalance) / this.minorUnitsQuotient).toFixed(2); - this.saveGiftcardStateData(data, consumableBalance.toString(), 0, this.selectedGiftcard.id); - } - - this.remainingBalanceField.style.display = 'block'; - let innerHtmlBalance = adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingBalance + ': ' + - adyenGiftcardsConfiguration.currencySymbol + this.remainingGiftcardBalance; - - this.remainingBalanceField.innerHTML = innerHtmlBalance; + const consumableBalance = (response.transactionLimit ? parseFloat(response.transactionLimit.value) : parseFloat(response.balance.value)); + + //Saving Currency and the remaining Cart amount and Giftcard Title + data.giftcard = { + "currency": adyenGiftcardsConfiguration.currency, + "value": (consumableBalance / this.minorUnitsQuotient).toFixed(2), + "title": giftcard.name + }; + this.saveGiftcardStateData(data); } }.bind(this) ); } - saveGiftcardStateData(stateData, amountInMinorUnits, balance, paymentMethodId) { - // save state data to database, set giftcard as payment method and proceed to checkout - stateData = JSON.stringify(stateData); - this._client.post(adyenGiftcardsConfiguration.setGiftcardUrl, JSON.stringify({ stateData, amount: amountInMinorUnits, balance, paymentMethodId }), function (response) { + fetchRedeemedGiftcards() { + this._client.get(adyenGiftcardsConfiguration.fetchRedeemedGiftcardsUrl, function (response) { response = JSON.parse(response); - if ('paymentMethodId' in response) { - this.giftcardDiscount = (amountInMinorUnits / this.minorUnitsQuotient).toFixed(2); - this.remainingAmount = (adyenGiftcardsConfiguration.totalPrice - this.giftcardDiscount).toFixed(2); - this.onGiftcardSelected(); - ElementLoadingIndicatorUtil.remove(document.body); + let totalBalance =0; + let giftcardsContainer = document.getElementById('giftcardsContainer'); + let addButton = document.querySelector('.btn-outline-info'); + + // Clear the container before adding new content + giftcardsContainer.innerHTML = ''; + + // Iterate through the redeemed gift cards and display them + response.redeemedGiftcards.giftcards.forEach(function(giftcard) { + let deductedAmount = parseFloat(giftcard.deductedAmount); + deductedAmount = (deductedAmount).toFixed(2); + let balanceInnerHtml = adyenGiftcardsConfiguration.translationAdyenGiftcardDeductedBalance + ': ' + + adyenGiftcardsConfiguration.currencySymbol + deductedAmount; + + //Create a new HTML element for each gift card + let giftcardElement = document.createElement('div'); + var imgElement = document.createElement('img'); + imgElement.src = 'https://checkoutshopper-live.adyen.com/checkoutshopper/images/logos/'+giftcard.brand+'.svg'; + imgElement.classList.add('adyen-giftcard-logo'); + + let removeElement = document.createElement('a'); + removeElement.href = '#'; + removeElement.textContent = adyenGiftcardsConfiguration.translationAdyenGiftcardRemove; + removeElement.setAttribute('dataid', giftcard.stateDataId); + removeElement.classList.add('adyen-remove-giftcard'); + removeElement.style.display = 'block'; + + giftcardElement.appendChild(imgElement); + giftcardElement.innerHTML += `${giftcard.title}`; + giftcardElement.appendChild(removeElement); + giftcardElement.innerHTML += `

${balanceInnerHtml}


`; + + // Append the gift card element to the container + giftcardsContainer.appendChild(giftcardElement); + + }); + //Update calculations + this.remainingAmount = response.redeemedGiftcards.remainingAmount; + this.giftcardDiscount = response.redeemedGiftcards.totalDiscount; + + // Remove component + if (this.paymentMethodInstance) { + this.paymentMethodInstance.unmount(); + } + this.giftcardComponentClose.style.display = 'none'; + this.giftcardItem.innerHTML = ''; + this.giftcardHeader.innerHTML = ' '; + this.appendGiftcardSummary(); + + //Compare the new total gift card balance with the order amount + if (this.remainingAmount > 0.00) { + //allow adding new giftcards + addButton.style.display = "block"; + } else { + // Hide giftcards dropdown and Add giftcards option + if (this.adyenGiftcardDropDown.length > 0) { + this.adyenGiftcardDropDown[0].style.display = 'none'; + } + addButton.style.display = "none"; } + let giftcardContainerElement = document.getElementById('giftcardsContainer'); // Replace with your actual container ID + }.bind(this)); } - setGiftcardAsPaymentMethod(stateData, balance) { - this._client.patch(adyenGiftcardsConfiguration.switchContextUrl, JSON.stringify({paymentMethodId: this.selectedGiftcard.id}), function (response) { - this.saveGiftcardStateData(stateData, adyenGiftcardsConfiguration.totalInMinorUnits, balance, this.selectedGiftcard.id) - }.bind(this)); + saveGiftcardStateData(stateData) { + // save state data to database, set giftcard as payment method and proceed to checkout + stateData = JSON.stringify(stateData); + this._client.post( + adyenGiftcardsConfiguration.setGiftcardUrl, + JSON.stringify({ stateData}), + function (response) { + response = JSON.parse(response); + if ('token' in response) { + this.fetchRedeemedGiftcards(); + ElementLoadingIndicatorUtil.remove(document.body); + } + }.bind(this) + ); } - removeGiftcard() { + removeGiftcard(storeId) { ElementLoadingIndicatorUtil.create(document.body); - this._client.post(adyenGiftcardsConfiguration.removeGiftcardUrl, new FormData, function(response) { + + this._client.post(adyenGiftcardsConfiguration.removeGiftcardUrl, JSON.stringify({stateDataId: storeId}), (response) => { response = JSON.parse(response); if ('token' in response) { - this.giftcardDiscount = 0; - this.remainingAmount = (adyenGiftcardsConfiguration.totalPrice - this.giftcardDiscount).toFixed(2); - - if (this.shoppingCartSummaryBlock.length) { - let giftcardSummary = this.shoppingCartSummaryBlock[0].querySelectorAll('.adyen-giftcard-summary'); - for (let i = 0; i < giftcardSummary.length; i++) { - giftcardSummary[i].remove(); - } - } - this.removeGiftcardButton.style.display = 'none'; - this.remainingBalanceField.style.display = 'none'; - // Show giftcards - for(var i=0;i' + - '
' + adyenGiftcardsConfiguration.currencySymbol + this.giftcardDiscount + '
' + + '
' + adyenGiftcardsConfiguration.currencySymbol + giftcardDiscount + '
' + '
' + adyenGiftcardsConfiguration.translationAdyenGiftcardRemainingAmount + '
' + - '
' + adyenGiftcardsConfiguration.currencySymbol + this.remainingAmount + '
'; + '
' + adyenGiftcardsConfiguration.currencySymbol + remainingAmount + '
'; this.shoppingCartSummaryBlock[0].innerHTML += innerHtmlShoppingCartSummaryDetails; } } - - onGiftcardSelected() { - // Remove component - if (this.paymentMethodInstance) { - this.paymentMethodInstance.unmount(); - } - this.giftcardComponentClose.style.display = 'none'; - // Hide giftcards - // this.adyenGiftcard.style.display = 'none'; - - for(var i=0;i 0) { + if (parseInt(adyenCheckoutOptions.giftcardDiscount, 10)) { this.appendGiftcardSummary(); } } else { @@ -138,6 +135,9 @@ export default class ConfirmOrderPlugin extends Plugin { this.renderStoredPaymentMethodComponents(); return; } + if(type === 'giftcard') { + return; + } // Get the payment method object from paymentMethodsResponse let paymentMethodConfigs = this.adyenCheckout.paymentMethodsResponse.paymentMethods.filter(function(paymentMethod) { @@ -196,7 +196,6 @@ export default class ConfirmOrderPlugin extends Plugin { const orderId = adyenCheckoutOptions.orderId; formData.set('affiliateCode', adyenCheckoutOptions.affiliateCode); formData.set('campaignCode', adyenCheckoutOptions.campaignCode); - if (!!orderId) { //Only used if the order is being edited this.updatePayment(formData, orderId, extraParams) } else { @@ -215,37 +214,11 @@ export default class ConfirmOrderPlugin extends Plugin { } createOrder(formData, extraParams) { - if ( - parseInt(adyenCheckoutOptions.giftcardDiscount, 10) && - !parseInt(adyenCheckoutOptions.payInFullWithGiftcard, 10) - ) { - // create Adyen order for partial payments - this._client.post( - adyenCheckoutOptions.createOrderUrl, - JSON.stringify({orderAmount: adyenCheckoutOptions.amount, currency: adyenCheckoutOptions.currency}), - function (response) { - const adyenOrder = JSON.parse(response); - if (adyenOrder.resultCode === 'Success') { - extraParams = Object.assign(extraParams, { - order: adyenOrder - }); - } - - // create shopware order - this._client.post( - adyenCheckoutOptions.checkoutOrderUrl, - formData, - this.afterCreateOrder.bind(this, extraParams) - ); - }.bind(this) - ) - } else { - this._client.post( - adyenCheckoutOptions.checkoutOrderUrl, - formData, - this.afterCreateOrder.bind(this, extraParams) - ); - } + this._client.post( + adyenCheckoutOptions.checkoutOrderUrl, + formData, + this.afterCreateOrder.bind(this, extraParams) + ); } afterCreateOrder(extraParams={}, response) { @@ -589,18 +562,21 @@ export default class ConfirmOrderPlugin extends Plugin { appendGiftcardSummary() { if(parseInt(adyenCheckoutOptions.giftcardDiscount, 10) && this.shoppingCartSummaryBlock.length) { + let giftcardDiscount = parseFloat(this.giftcardDiscount).toFixed(2); + let remainingAmount = parseFloat(this.remainingAmount).toFixed(2); + let shoppingCartSummaryDetails = '
' + adyenCheckoutOptions.translationAdyenGiftcardDiscount + '
' + '
' + - adyenCheckoutOptions.currencySymbol + this.giftcardDiscount + + adyenCheckoutOptions.currencySymbol + giftcardDiscount + '
' + '
' + adyenCheckoutOptions.translationAdyenGiftcardRemainingAmount + '
' + '
' + - adyenCheckoutOptions.currencySymbol + this.remainingAmount + + adyenCheckoutOptions.currencySymbol + remainingAmount + '
'; this.shoppingCartSummaryBlock[0].innerHTML += shoppingCartSummaryDetails; diff --git a/src/Resources/app/storefront/src/configuration/adyen.js b/src/Resources/app/storefront/src/configuration/adyen.js index 2b2327ff..92e96cd0 100644 --- a/src/Resources/app/storefront/src/configuration/adyen.js +++ b/src/Resources/app/storefront/src/configuration/adyen.js @@ -146,20 +146,7 @@ export default { 'afterpay_default': 'handler_adyen_afterpaydefaultpaymentmethodhandler', 'trustly': 'handler_adyen_trustlypaymentmethodhandler', 'paysafecard': 'handler_adyen_paysafecardpaymentmethodhandler', - 'givex': 'handler_adyen_givexgiftcardpaymentmethodhandler', - 'webshopgiftcard': 'handler_adyen_webshopgiftcardpaymentmethodhandler', - 'kadowereld': 'handler_adyen_kadowereldgiftcardpaymentmethodhandler', - 'tcstestgiftcard': 'handler_adyen_tcstestgiftcardpaymentmethodhandler', - 'albelligiftcard': 'handler_adyen_albelligiftcardpaymentmethodhandler', - 'bijcadeaucard': 'handler_adyen_bijenkorfgiftcardpaymentmethodhandler', - 'vvvgiftcard': 'handler_adyen_vvvgiftcardpaymentmethodhandler', - 'genericgiftcard': 'handler_adyen_genericgiftcardpaymentmethodhandler', - 'gallgall': 'handler_adyen_gallgallgiftcardpaymentmethodhandler', - 'hmlingerie': 'handler_adyen_hunkemollerlingeriegiftcardpaymentmethodhandler', - 'beautycadeaukaart': 'handler_adyen_beautygiftcardpaymentmethodhandler', - 'svs': 'handler_adyen_svsgiftcardpaymentmethodhandler', - 'fashioncheque': 'handler_adyen_fashionchequegiftcardpaymentmethodhandler', - 'decadeaukaart': 'handler_adyen_decadeaukaartgiftcardpaymentmethodhandler', + 'giftcard': 'handler_adyen_giftcardpaymentmethodhandler', 'mbway': 'handler_adyen_mbwaypaymentmethodhandler', 'multibanco': 'handler_adyen_multibancopaymentmethodhandler', 'wechatpayQR': 'handler_adyen_wechatpayqrpaymentmethodhandler', diff --git a/src/Resources/app/storefront/src/scss/base.scss b/src/Resources/app/storefront/src/scss/base.scss index d1cf5b1a..233d3bc8 100644 --- a/src/Resources/app/storefront/src/scss/base.scss +++ b/src/Resources/app/storefront/src/scss/base.scss @@ -49,11 +49,12 @@ .adyen-remove-giftcard { display: none; + float: right; + margin-left: auto; } -.adyen-remaining-balance { +.adyen-deducted-balance { display: none; - text-align: center; } .adyen-voucher-details { @@ -74,3 +75,33 @@ .adyen-payment-action-container { height: 100%; } + +#giftcardDropdown { + display: block; + background-clip: padding-box; + border: 1px solid #cccccc; + border-radius: 1px; + font-size: 14px; + height: 32px; + line-height: 1.42857143; + padding: 4px 25px 5px 10px; + vertical-align: baseline; + width: 100%; + box-sizing: border-box; +} + +.adyen-giftcard-logo { + width: 75px; + margin: 0 10px 5px 0; + float: left; +} + +#adyen-giftcard-component{ + margin: 15px 0; +} + +.adyen-giftcard-summary { + margin-top: 5px; + color: #666; + font-size: 90%; +} diff --git a/src/Resources/config/config.xml b/src/Resources/config/config.xml index 063e95c3..2cd978a6 100644 --- a/src/Resources/config/config.xml +++ b/src/Resources/config/config.xml @@ -157,6 +157,28 @@ 43200 + + Refund Settings + + refundStrategyGiftcard + + Only relevant if you accept gift cards on Adyen payments. + + + + + + + Adyen Giving diff --git a/src/Resources/config/services.xml b/src/Resources/config/services.xml index 87bae9de..6dd9ffac 100644 --- a/src/Resources/config/services.xml +++ b/src/Resources/config/services.xml @@ -84,10 +84,14 @@ + - + + + + diff --git a/src/Resources/config/services/checkout-api.xml b/src/Resources/config/services/checkout-api.xml index d80ee392..26107f5c 100644 --- a/src/Resources/config/services/checkout-api.xml +++ b/src/Resources/config/services/checkout-api.xml @@ -12,7 +12,7 @@ - + @@ -40,10 +40,12 @@ - + + + diff --git a/src/Resources/config/services/commands.xml b/src/Resources/config/services/commands.xml index 4230f2cd..5cbb04c4 100644 --- a/src/Resources/config/services/commands.xml +++ b/src/Resources/config/services/commands.xml @@ -34,23 +34,21 @@ + + + + - + - + - - - - - - - + diff --git a/src/Resources/config/services/controllers.xml b/src/Resources/config/services/controllers.xml index 1dfe6b42..3b054be5 100644 --- a/src/Resources/config/services/controllers.xml +++ b/src/Resources/config/services/controllers.xml @@ -5,15 +5,37 @@ https://symfony.com/schema/dic/services/services-1.0.xsd"> + + + + + + + + + + + + + - + + + + + + + + + diff --git a/src/Resources/config/services/payment-handlers.xml b/src/Resources/config/services/payment-handlers.xml index 209faa31..bc36af0c 100644 --- a/src/Resources/config/services/payment-handlers.xml +++ b/src/Resources/config/services/payment-handlers.xml @@ -5,15 +5,11 @@ https://symfony.com/schema/dic/services/services-1.0.xsd"> + - - - - - - - + + @@ -159,97 +155,102 @@ parent="Adyen\Shopware\Handlers\AbstractPaymentMethodHandler"> - - - - - - - - - - - - - - - - - - - - - - - + + + + diff --git a/src/Resources/config/services/subscribers.xml b/src/Resources/config/services/subscribers.xml index c686c534..37a1c794 100644 --- a/src/Resources/config/services/subscribers.xml +++ b/src/Resources/config/services/subscribers.xml @@ -18,13 +18,14 @@ - + + - + @@ -35,7 +36,7 @@ - + diff --git a/src/Resources/config/services/utils.xml b/src/Resources/config/services/utils.xml index 236f9716..59afdab2 100644 --- a/src/Resources/config/services/utils.xml +++ b/src/Resources/config/services/utils.xml @@ -14,6 +14,7 @@ - + + diff --git a/src/Resources/public/administration/js/adyen-payment-shopware6.js b/src/Resources/public/administration/js/adyen-payment-shopware6.js index b22b629c..7f769cac 100644 --- a/src/Resources/public/administration/js/adyen-payment-shopware6.js +++ b/src/Resources/public/administration/js/adyen-payment-shopware6.js @@ -1 +1,2 @@ -!function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(r,a,function(t){return e[t]}.bind(null,a));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=(window.__sw__.assetPath + '/bundles/adyenpaymentshopware6/'),n(n.s="ADFX")}({ADFX:function(e,t,n){"use strict";n.r(t);n("jZA+");var r=Shopware,a=r.Component,i=r.Mixin;a.register("adyen-config-check-button",{template:'\n',inject:["adyenService"],mixins:[i.getByName("notification")],data:function(){return{isLoading:!1,isSaveSuccessful:!1}},computed:{pluginConfig:function(){for(var e=this.$parent;!e.hasOwnProperty("actualConfigData");)e=e.$parent;var t=e.currentSalesChannelId,n=e.actualConfigData;return Object.assign({},n.null,n[t])}},methods:{saveFinish:function(){this.isSaveSuccessful=!1},check:function(){var e=this;this.isLoading=!0,this.adyenService.check(this.pluginConfig).then((function(t){t.success?(e.isSaveSuccessful=!0,e.createNotificationSuccess({title:e.$tc("adyen.configTestTitle"),message:e.$tc("adyen.configTestSuccess")})):e.createNotificationError({title:e.$tc("adyen.configTestTitle"),message:e.$tc(t.message?t.message:"adyen.configTestFail")}),e.isLoading=!1}))}}});n("H7Mt");var o=Shopware,s=o.Component,d=o.Mixin;s.register("adyen-payment-capture",{template:'{% block adyen_capture %}\n \n
\n
\n
\n {{ $tc(\'adyen.noCaptureRequests\') }}\n
\n
\n \n {{ $tc(\'adyen.sendCaptureRequest\') }}\n \n
\n \n \n \n
\n \n \n
\n
\n {{ $tc(\'adyen.error\') }}\n
\n
\n{% endblock %}\n',inject:["adyenService","systemConfigApiService"],mixins:[d.getByName("notification")],props:{order:{type:Object,required:!0}},data:function(){return{columns:[{property:"pspReference",label:this.$tc("adyen.columnHeaders.pspReference")},{property:"amount",label:this.$tc("adyen.columnHeaders.amount")},{property:"status",label:this.$tc("adyen.columnHeaders.status")},{property:"createdAt",label:this.$tc("adyen.columnHeaders.created")},{property:"updatedAt",label:this.$tc("adyen.columnHeaders.updated")}],showModal:!1,captureRequests:[],allowCapture:!1,captureEnabled:!1,errorOccurred:!1,isLoading:!0,showWidget:!1}},methods:{openModal:function(){this.showModal=!0},onCloseModal:function(){this.showModal=!1},onSubmitCapture:function(){var e=this;this.isLoading=!0,this.adyenService.capture(this.order.id).then((function(t){t.success?(e.fetchCaptureRequests(),e.createNotificationSuccess({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc("adyen.captureSuccessful")})):e.createNotificationError({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc(t.message?t.message:"adyen.error")})})).catch((function(){e.createNotificationError({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc("adyen.error")})})).finally((function(){e.isLoading=!1,e.showModal=!1}))},fetchCaptureRequests:function(){var e=this;this.isLoading=!0,this.adyenService.getCaptureRequests(this.order.id).then((function(t){e.captureRequests=t,e.isCaptureAllowed()})).catch((function(){e.errorOccurred=!0,e.captureRequests=[]})).finally((function(){e.isLoading=!1}))},isManualCaptureEnabled:function(){var e=this;this.isLoading=!0,this.adyenService.isManualCaptureEnabled(this.order.id).then((function(t){e.captureEnabled=t,e.showWidget=e.adyenService.isAdyenOrder(e.order)&&e.captureEnabled})).catch((function(){e.errorOccurred=!0,e.captureEnabled=!1})).finally((function(){e.isLoading=!1}))},isCaptureAllowed:function(){var e=this;this.isLoading=!0,this.adyenService.isCaptureAllowed(this.order.id).then((function(t){e.allowCapture=t})).catch((function(){e.errorOccurred=!0,e.allowCapture=!1})).finally((function(){e.isLoading=!1}))}},beforeMount:function(){this.isManualCaptureEnabled(),this.fetchCaptureRequests()}});n("tG31");function c(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return l(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return l(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n\n
\n
\n
\n {{ $tc(\'adyen.noRefundsCreated\') }}\n
\n
\n \n {{ $tc(\'sw-order.documentCard.labelCreateNew\') }}\n \n
\n \n
\n \n
\n \n
\n
\n \n \n
\n
\n {{ $tc(\'adyen.refundFetchError\') }}\n
\n \n{% endblock %}\n',inject:["adyenService"],mixins:[p.getByName("notification")],props:{order:{type:Object,required:!0}},data:function(){return{columns:[{property:"pspReference",label:this.$tc("adyen.columnHeaders.pspReference")},{property:"amount",label:this.$tc("adyen.columnHeaders.amount")},{property:"status",label:this.$tc("adyen.columnHeaders.status")},{property:"createdAt",label:this.$tc("adyen.columnHeaders.created")},{property:"updatedAt",label:this.$tc("adyen.columnHeaders.updated")}],refundAmount:0,showModal:!1,refunds:[],allowRefund:!0,isLoadingTable:!0,errorOccurred:!1,isLoadingRefund:!1,showWidget:!1}},methods:{openModal:function(){this.showModal=!0},onCloseModal:function(){this.showModal=!1},onRefund:function(){var e=this;this.isLoadingRefund=!0,this.adyenService.postRefund(this.order.id,this.refundAmount).then((function(t){t.success?(e.fetchRefunds(),e.createNotificationSuccess({title:e.$tc("adyen.refundTitle"),message:e.$tc("adyen.refundSuccessful")})):e.createNotificationError({title:e.$tc("adyen.refundTitle"),message:e.$tc(t.message?t.message:"adyen.error")})})).catch((function(){e.createNotificationError({title:e.$tc("adyen.refundTitle"),message:e.$tc("adyen.error")})})).finally((function(){e.isLoadingRefund=!1,e.showModal=!1}))},fetchRefunds:function(){var e=this;this.isLoadingTable=!0,this.adyenService.getRefunds(this.order.id).then((function(t){e.refunds=t,e.isRefundAllowed()})).catch((function(){e.errorOccurred=!0,e.refunds=[]})).finally((function(){e.isLoadingTable=!1}))},isRefundAllowed:function(){var e,t=0,n=c(this.refunds);try{for(n.s();!(e=n.n()).done;){var r=e.value;"Failed"!==r.status&&(t+=r.rawAmount)}}catch(e){n.e(e)}finally{n.f()}this.allowRefund=this.order.amountTotal>t/100},isAdyenOrder:function(){for(var e=this.order.transactions,t=!1,n=0;n\n \n \n {% block sw_data_grid_body_columns %}\n {% block sw_data_grid_column_actions %}\n \n {% endblock %}\n {% endblock %}\n \n

{{ $tc(\'adyen.noNotificationsReceived\') }}

\n
\n \n{% endblock %}\n',inject:["adyenService"],mixins:[m.getByName("notification")],props:{order:{type:Object,required:!0}},data:function(){return{notifications:[],columns:[{property:"pspReference",label:this.$tc("adyen.columnHeaders.pspReference")},{property:"eventCode",label:this.$tc("adyen.columnHeaders.event")},{property:"success",label:this.$tc("adyen.columnHeaders.success")},{property:"amount",label:this.$tc("adyen.columnHeaders.amount")},{property:"status",label:this.$tc("adyen.columnHeaders.status")},{property:"createdAt",label:this.$tc("adyen.columnHeaders.created")},{property:"updatedAt",label:this.$tc("adyen.columnHeaders.updated")},{property:"errorCount",label:this.$tc("adyen.columnHeaders.errorCount")},{property:"errorMessage",label:this.$tc("adyen.columnHeaders.errorMessage")}],showWidget:!1}},methods:{fetchNotifications:function(){var e=this;this.adyenService.fetchNotifications(this.order.id).then((function(t){e.notifications=t}))},onReschedule:function(e){var t=this;this.adyenService.rescheduleNotification(e.notificationId).then((function(e){t.createNotificationSuccess({title:t.$tc("adyen.reprocessNotification"),message:t.$tc("adyen.notificationRescheduleSuccess")}),t.fetchNotifications()}))}},beforeMount:function(){this.showWidget=this.adyenService.isAdyenOrder(this.order),this.showWidget&&this.fetchNotifications()}});var g={isVersionOlderThan65:function(){var e,t,n=Shopware.Context.app.config.version;return-1===(t="6.5.0.0",(e=n).startsWith(t+"-")?-1:t.startsWith(e+"-")?1:e.localeCompare(t,void 0,{numeric:!0,sensitivity:"case",caseFirst:"upper"}))}},v=g;Shopware.Component.register("adyen-partial-payments",{template:'
\n
    \n
    {{ $tc(\'adyen.authorisedPayments\') }}
    \n
    \n {{ payment.pspReference }} -\n {{ payment.method }} -\n {{ payment.amount }}\n
    \n
    {{ errorMessage }}
    \n
\n
    \n \n
    \n
    \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    \n
    \n PSP Reference\n
    \n
    \n
    \n Payment Method\n
    \n
    \n
    \n Amount\n
    \n
    \n \n \n
    \n {{ payment.method }}\n
    \n
    \n
    \n {{ payment.amount }}\n
    \n
    \n
    \n
    \n {{ errorMessage }}\n
\n
\n',inject:["adyenService"],props:{order:{type:Object,required:!0}},methods:{fetchAdyenPartialPayments:function(){var e=this;this.adyenService.fetchAdyenPartialPayments(this.order.id).then((function(t){t.length>0?e.partialPayments=t:e.errorMessage=e.$tc("adyen.pendingWebhook")}))}},data:function(){return{errorMessage:"",partialPayments:[],showWidget:!1,isVersionOlderThan65:!1}},beforeMount:function(){this.isVersionOlderThan65=v.isVersionOlderThan65(),this.showWidget=this.adyenService.isAdyenOrder(this.order),this.showWidget&&this.fetchAdyenPartialPayments()}});Shopware.Component.override("sw-order-detail-general",{template:'{% block sw_order_detail_general_line_items_card %}\n {% parent %}\n \n \n \n{% endblock %}\n'});Shopware.Component.override("sw-order-detail-base",{template:'{% block sw_order_detail_base_custom_fields %}\n {% parent %}\n \n \n \n{% endblock %}\n'});Shopware.Component.override("sw-order-user-card",{template:'{% block sw_order_detail_base_secondary_info_payment %}\n {% parent %}\n\n \n{% endblock %}\n'});Shopware.Component.override("sw-order-detail-details",{template:'{% block sw_order_detail_details_payment_method_select %}\n {% parent %}\n\n \n{% endblock %}\n'});n("vNjL");var w=n("GGYj");Shopware.Locale.extend("en-GB",w)},GGYj:function(e){e.exports=JSON.parse('{"adyen":{"configTestTitle":"Configuration test","configTestSuccess":"Configuration is successfully tested","configTestFail":"There\'s an issue in your configuration","adyenRefunds":"Adyen Refunds","refundTitle":"Refund","refundSuccessful":"A refund has been successfully submitted.","invalidRefundAmount":"Refund amount exceeds order total","error":"An error has occurred. Please check the logs.","refundFetchError":"An error has occurred while attempting to get linked refunds.","refundConfirm":"Create refund for order","createRefund":"Create Refund","noRefundsCreated":"No refunds created","columnHeaders":{"pspReference":"PSP Reference","amount":"Amount","status":"Status","event":"Event","success":"Success","created":"Created","updated":"Updated","errorCount":"Error Count","errorMessage":"Error Message"},"reprocessNotification":"Reprocess Notification","notificationRescheduleSuccess":"Notification will be processed again.","notificationsTitle":"Adyen Webhook Notifications","noNotificationsReceived":"No webhook notifications received.","adyenPaymentCaptureTitle":"Adyen Capture Requests","noCaptureRequests":"No capture requests have been sent","sendCaptureRequest":"Send Capture Request","captureConfirm":"Capture payment for order","captureSuccessful":"Capture request has been successfully sent","pendingWebhook":"Order is pending webhook.","authorisedPayments":"Authorised Payments"}}')},H7Mt:function(e,t,n){var r=n("mH+n");r.__esModule&&(r=r.default),"string"==typeof r&&(r=[[e.i,r,""]]),r.locals&&(e.exports=r.locals);(0,n("P8hj").default)("056a1238",r,!0,{})},P8hj:function(e,t,n){"use strict";function r(e,t){for(var n=[],r={},a=0;an.parts.length&&(r.parts.length=n.parts.length)}else{var o=[];for(a=0;a2&&void 0!==arguments[2]?arguments[2]:"adyen";return r(this,l),(n=d.call(this,e,t,a)).headers=n.getBasicHeaders({}),n}return t=l,(n=[{key:"check",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.post("_action/".concat(this.getApiBasePath(),"/verify"),e,{headers:t}).then((function(e){return c.handleResponse(e)}))}},{key:"capture",value:function(e){return this.httpClient.post(this.getApiBasePath()+"/capture",{orderId:e},{headers:this.headers}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during capture request: "+e.message),e}))}},{key:"getCaptureRequests",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/captures",{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during capture request: "+e.message),e}))}},{key:"isCaptureAllowed",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/is-capture-allowed",{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during is-capture-allowed request: "+e.message),e}))}},{key:"isManualCaptureEnabled",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/is-manual-capture-enabled",{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during is-capture-allowed request: "+e.message),e}))}},{key:"getRefunds",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/refunds",{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during refunds request: "+e.message),e}))}},{key:"postRefund",value:function(e,t){var n=this.getBasicHeaders({});return this.httpClient.post(this.getApiBasePath()+"/refunds",{orderId:e,refundAmount:t},{headers:n}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during post refund request: "+e.message),e}))}},{key:"fetchNotifications",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/notifications",{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred: "+e.message),e}))}},{key:"rescheduleNotification",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/reschedule-notification/"+e,{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred: "+e.message),e}))}},{key:"isAdyenOrder",value:function(e){for(var t=e.transactions,n=!1,r=0;r\n Test Configuration\n\n',inject:["adyenService"],mixins:[i.getByName("notification")],data:function(){return{isLoading:!1,isSaveSuccessful:!1}},computed:{pluginConfig:function(){for(var e=this.$parent;!e.hasOwnProperty("actualConfigData");)e=e.$parent;var t=e.currentSalesChannelId,n=e.actualConfigData;return Object.assign({},n.null,n[t])}},methods:{saveFinish:function(){this.isSaveSuccessful=!1},check:function(){var e=this;this.isLoading=!0,this.adyenService.check(this.pluginConfig).then((function(t){t.success?(e.isSaveSuccessful=!0,e.createNotificationSuccess({title:e.$tc("adyen.configTestTitle"),message:e.$tc("adyen.configTestSuccess")})):e.createNotificationError({title:e.$tc("adyen.configTestTitle"),message:e.$tc(t.message?t.message:"adyen.configTestFail")}),e.isLoading=!1}))}}});n("H7Mt");var o=Shopware,s=o.Component,d=o.Mixin;s.register("adyen-payment-capture",{template:'{% block adyen_capture %}\n \n
\n
\n
\n {{ $tc(\'adyen.noCaptureRequests\') }}\n
\n
\n \n {{ $tc(\'adyen.sendCaptureRequest\') }}\n \n
\n \n \n \n
\n \n \n
\n
\n {{ $tc(\'adyen.error\') }}\n
\n
\n{% endblock %}\n',inject:["adyenService","systemConfigApiService"],mixins:[d.getByName("notification")],props:{order:{type:Object,required:!0}},data:function(){return{columns:[{property:"pspReference",label:this.$tc("adyen.columnHeaders.pspReference")},{property:"amount",label:this.$tc("adyen.columnHeaders.amount")},{property:"status",label:this.$tc("adyen.columnHeaders.status")},{property:"createdAt",label:this.$tc("adyen.columnHeaders.created")},{property:"updatedAt",label:this.$tc("adyen.columnHeaders.updated")}],showModal:!1,captureRequests:[],allowCapture:!1,captureEnabled:!1,errorOccurred:!1,isLoading:!0,showWidget:!1}},methods:{openModal:function(){this.showModal=!0},onCloseModal:function(){this.showModal=!1},onSubmitCapture:function(){var e=this;this.isLoading=!0,this.adyenService.capture(this.order.id).then((function(t){t.success?(e.fetchCaptureRequests(),e.createNotificationSuccess({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc("adyen.captureSuccessful")})):e.createNotificationError({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc(t.message?t.message:"adyen.error")})})).catch((function(){e.createNotificationError({title:e.$tc("adyen.adyenPaymentCaptureTitle"),message:e.$tc("adyen.error")})})).finally((function(){e.isLoading=!1,e.showModal=!1}))},fetchCaptureRequests:function(){var e=this;this.isLoading=!0,this.adyenService.getCaptureRequests(this.order.id).then((function(t){e.captureRequests=t,e.isCaptureAllowed()})).catch((function(){e.errorOccurred=!0,e.captureRequests=[]})).finally((function(){e.isLoading=!1}))},isManualCaptureEnabled:function(){var e=this;this.isLoading=!0,this.adyenService.isManualCaptureEnabled(this.order.id).then((function(t){e.captureEnabled=t,e.showWidget=e.adyenService.isAdyenOrder(e.order)&&e.captureEnabled})).catch((function(){e.errorOccurred=!0,e.captureEnabled=!1})).finally((function(){e.isLoading=!1}))},isCaptureAllowed:function(){var e=this;this.isLoading=!0,this.adyenService.isCaptureAllowed(this.order.id).then((function(t){e.allowCapture=t})).catch((function(){e.errorOccurred=!0,e.allowCapture=!1})).finally((function(){e.isLoading=!1}))}},beforeMount:function(){this.isManualCaptureEnabled(),this.fetchCaptureRequests()}});n("tG31");function c(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return l(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return l(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,a=function(){};return{s:a,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,i=e},f:function(){try{o||null==n.return||n.return()}finally{if(s)throw i}}}}function l(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n\n
\n
\n
\n {{ $tc(\'adyen.noRefundsCreated\') }}\n
\n
\n \n {{ $tc(\'sw-order.documentCard.labelCreateNew\') }}\n \n
\n \n
\n \n
\n \n
\n
\n \n \n
\n
\n {{ $tc(\'adyen.refundFetchError\') }}\n
\n \n{% endblock %}\n',inject:["adyenService"],mixins:[p.getByName("notification")],props:{order:{type:Object,required:!0}},data:function(){return{columns:[{property:"pspReference",label:this.$tc("adyen.columnHeaders.pspReference")},{property:"amount",label:this.$tc("adyen.columnHeaders.amount")},{property:"status",label:this.$tc("adyen.columnHeaders.status")},{property:"createdAt",label:this.$tc("adyen.columnHeaders.created")},{property:"updatedAt",label:this.$tc("adyen.columnHeaders.updated")}],refundAmount:0,showModal:!1,refunds:[],allowRefund:!0,isLoadingTable:!0,errorOccurred:!1,isLoadingRefund:!1,showWidget:!1}},methods:{openModal:function(){this.showModal=!0},onCloseModal:function(){this.showModal=!1},onRefund:function(){var e=this;this.isLoadingRefund=!0,this.adyenService.postRefund(this.order.id,this.refundAmount).then((function(t){t.success?(e.fetchRefunds(),e.createNotificationSuccess({title:e.$tc("adyen.refundTitle"),message:e.$tc("adyen.refundSuccessful")})):e.createNotificationError({title:e.$tc("adyen.refundTitle"),message:e.$tc(t.message?t.message:"adyen.error")})})).catch((function(){e.createNotificationError({title:e.$tc("adyen.refundTitle"),message:e.$tc("adyen.error")})})).finally((function(){e.isLoadingRefund=!1,e.showModal=!1}))},fetchRefunds:function(){var e=this;this.isLoadingTable=!0,this.adyenService.getRefunds(this.order.id).then((function(t){e.refunds=t,e.isRefundAllowed()})).catch((function(){e.errorOccurred=!0,e.refunds=[]})).finally((function(){e.isLoadingTable=!1}))},isRefundAllowed:function(){var e,t=0,n=c(this.refunds);try{for(n.s();!(e=n.n()).done;){var r=e.value;"Failed"!==r.status&&(t+=r.rawAmount)}}catch(e){n.e(e)}finally{n.f()}this.allowRefund=this.order.amountTotal>t/100},isAdyenOrder:function(){for(var e=this.order.transactions,t=!1,n=0;n\n \n \n {% block sw_data_grid_body_columns %}\n {% block sw_data_grid_column_actions %}\n \n {% endblock %}\n {% endblock %}\n \n

{{ $tc(\'adyen.noNotificationsReceived\') }}

\n
\n \n{% endblock %}\n',inject:["adyenService"],mixins:[m.getByName("notification")],props:{order:{type:Object,required:!0}},data:function(){return{notifications:[],columns:[{property:"pspReference",label:this.$tc("adyen.columnHeaders.pspReference")},{property:"eventCode",label:this.$tc("adyen.columnHeaders.event")},{property:"success",label:this.$tc("adyen.columnHeaders.success")},{property:"amount",label:this.$tc("adyen.columnHeaders.amount")},{property:"status",label:this.$tc("adyen.columnHeaders.status")},{property:"createdAt",label:this.$tc("adyen.columnHeaders.created")},{property:"updatedAt",label:this.$tc("adyen.columnHeaders.updated")},{property:"errorCount",label:this.$tc("adyen.columnHeaders.errorCount")},{property:"errorMessage",label:this.$tc("adyen.columnHeaders.errorMessage")}],showWidget:!1}},methods:{fetchNotifications:function(){var e=this;this.adyenService.fetchNotifications(this.order.id).then((function(t){e.notifications=t}))},onReschedule:function(e){var t=this;this.adyenService.rescheduleNotification(e.notificationId).then((function(e){t.createNotificationSuccess({title:t.$tc("adyen.reprocessNotification"),message:t.$tc("adyen.notificationRescheduleSuccess")}),t.fetchNotifications()}))}},beforeMount:function(){this.showWidget=this.adyenService.isAdyenOrder(this.order),this.showWidget&&this.fetchNotifications()}});var g={isVersionOlderThan65:function(){var e,t,n=Shopware.Context.app.config.version;return-1===(t="6.5.0.0",(e=n).startsWith(t+"-")?-1:t.startsWith(e+"-")?1:e.localeCompare(t,void 0,{numeric:!0,sensitivity:"case",caseFirst:"upper"}))}},v=g;Shopware.Component.register("adyen-partial-payments",{template:'
\n
    \n
    {{ $tc(\'adyen.authorisedPayments\') }}
    \n
    \n {{ payment.pspReference }} -\n {{ payment.method }} -\n {{ payment.amount }}\n
    \n
    {{ errorMessage }}
    \n
\n
    \n \n
    \n
    \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    \n
    \n PSP Reference\n
    \n
    \n
    \n Payment Method\n
    \n
    \n
    \n Amount\n
    \n
    \n \n \n
    \n {{ payment.method }}\n
    \n
    \n
    \n {{ payment.amount }}\n
    \n
    \n
    \n
    \n {{ errorMessage }}\n
\n
\n',inject:["adyenService"],props:{order:{type:Object,required:!0}},methods:{fetchAdyenPartialPayments:function(){var e=this;this.adyenService.fetchAdyenPartialPayments(this.order.id).then((function(t){t.length>0?e.partialPayments=t:e.errorMessage=e.$tc("adyen.pendingWebhook")}))}},data:function(){return{errorMessage:"",partialPayments:[],showWidget:!1,isVersionOlderThan65:!1}},beforeMount:function(){this.isVersionOlderThan65=v.isVersionOlderThan65(),this.showWidget=this.adyenService.isAdyenOrder(this.order),this.showWidget&&this.fetchAdyenPartialPayments()}});Shopware.Component.override("sw-order-detail-general",{template:'{% block sw_order_detail_general_line_items_card %}\n {% parent %}\n \n \n \n{% endblock %}\n'});Shopware.Component.override("sw-order-detail-base",{template:'{% block sw_order_detail_base_custom_fields %}\n {% parent %}\n \n \n \n{% endblock %}\n'});Shopware.Component.override("sw-order-user-card",{template:'{% block sw_order_detail_base_secondary_info_payment %}\n {% parent %}\n\n \n{% endblock %}\n'});Shopware.Component.override("sw-order-detail-details",{template:'{% block sw_order_detail_details_payment_method_select %}\n {% parent %}\n\n \n{% endblock %}\n'});n("vNjL");var w=n("GGYj");Shopware.Locale.extend("en-GB",w)},GGYj:function(e){e.exports=JSON.parse('{"adyen":{"configTestTitle":"Configuration test","configTestSuccess":"Configuration is successfully tested","configTestFail":"There\'s an issue in your configuration","adyenRefunds":"Adyen Refunds","refundTitle":"Refund","refundSuccessful":"A refund has been successfully submitted.","invalidRefundAmount":"Refund amount exceeds order total","error":"An error has occurred. Please check the logs.","refundFetchError":"An error has occurred while attempting to get linked refunds.","refundConfirm":"Create refund for order","createRefund":"Create Refund","noRefundsCreated":"No refunds created","columnHeaders":{"pspReference":"PSP Reference","amount":"Amount","status":"Status","event":"Event","success":"Success","created":"Created","updated":"Updated","errorCount":"Error Count","errorMessage":"Error Message"},"reprocessNotification":"Reprocess Notification","notificationRescheduleSuccess":"Notification will be processed again.","notificationsTitle":"Adyen Webhook Notifications","noNotificationsReceived":"No webhook notifications received.","adyenPaymentCaptureTitle":"Adyen Capture Requests","noCaptureRequests":"No capture requests have been sent","sendCaptureRequest":"Send Capture Request","captureConfirm":"Capture payment for order","captureSuccessful":"Capture request has been successfully sent","pendingWebhook":"Order is pending webhook.","authorisedPayments":"Authorised Payments"}}')},H7Mt:function(e,t,n){var r=n("mH+n");r.__esModule&&(r=r.default),"string"==typeof r&&(r=[[e.i,r,""]]),r.locals&&(e.exports=r.locals);(0,n("P8hj").default)("056a1238",r,!0,{})},P8hj:function(e,t,n){"use strict";function r(e,t){for(var n=[],r={},a=0;an.parts.length&&(r.parts.length=n.parts.length)}else{var o=[];for(a=0;a2&&void 0!==arguments[2]?arguments[2]:"adyen";return r(this,l),(n=d.call(this,e,t,a)).headers=n.getBasicHeaders({}),n}return t=l,(n=[{key:"check",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.post("_action/".concat(this.getApiBasePath(),"/verify"),e,{headers:t}).then((function(e){return c.handleResponse(e)}))}},{key:"capture",value:function(e){return this.httpClient.post(this.getApiBasePath()+"/capture",{orderId:e},{headers:this.headers}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during capture request: "+e.message),e}))}},{key:"getCaptureRequests",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/captures",{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during capture request: "+e.message),e}))}},{key:"isCaptureAllowed",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/is-capture-allowed",{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during is-capture-allowed request: "+e.message),e}))}},{key:"isManualCaptureEnabled",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/is-manual-capture-enabled",{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during is-capture-allowed request: "+e.message),e}))}},{key:"getRefunds",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/refunds",{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during refunds request: "+e.message),e}))}},{key:"postRefund",value:function(e,t){var n=this.getBasicHeaders({});return this.httpClient.post(this.getApiBasePath()+"/refunds",{orderId:e,refundAmount:t},{headers:n}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred during post refund request: "+e.message),e}))}},{key:"fetchNotifications",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/orders/"+e+"/notifications",{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred: "+e.message),e}))}},{key:"rescheduleNotification",value:function(e){var t=this.getBasicHeaders({});return this.httpClient.get(this.getApiBasePath()+"/reschedule-notification/"+e,{headers:t}).then((function(e){return c.handleResponse(e)})).catch((function(e){throw console.error("An error occurred: "+e.message),e}))}},{key:"isAdyenOrder",value:function(e){for(var t=e.transactions,n=!1,r=0;r= v6.3.4.1\n // i.e. from this.$parent.$parent.$parent to this.$parent.$parent.$parent.$parent\n // @fixme This is a hack to support all versions\n let systemConfigComponent = this.$parent;\n while (!systemConfigComponent.hasOwnProperty('actualConfigData')) {\n systemConfigComponent = systemConfigComponent.$parent\n }\n let selectedSalesChannelId = systemConfigComponent.currentSalesChannelId;\n let config = systemConfigComponent.actualConfigData;\n // Properties NOT set in the sales channel config will be inherited from default config.\n return Object.assign({}, config.null, config[selectedSalesChannelId]);\n }\n },\n\n methods: {\n saveFinish() {\n this.isSaveSuccessful = false;\n },\n\n check() {\n this.isLoading = true;\n this.adyenService.check(this.pluginConfig).then((res) => {\n if (res.success) {\n this.isSaveSuccessful = true;\n this.createNotificationSuccess({\n title: this.$tc('adyen.configTestTitle'),\n message: this.$tc('adyen.configTestSuccess')\n });\n } else {\n this.createNotificationError({\n title: this.$tc('adyen.configTestTitle'),\n message: this.$tc(res.message ? res.message : 'adyen.configTestFail')\n });\n }\n\n this.isLoading = false;\n });\n }\n }\n});\n","export default \"\\n\";","export default \"{% block adyen_capture %}\\n \\n
\\n
\\n
\\n {{ $tc('adyen.noCaptureRequests') }}\\n
\\n
\\n \\n {{ $tc('adyen.sendCaptureRequest') }}\\n \\n
\\n \\n \\n \\n
\\n \\n \\n
\\n
\\n {{ $tc('adyen.error') }}\\n
\\n
\\n{% endblock %}\\n\";","/*\n * ######\n * ######\n * ############ ####( ###### #####. ###### ############ ############\n * ############# #####( ###### #####. ###### ############# #############\n * ###### #####( ###### #####. ###### ##### ###### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ######\n * ############# ############# ############# ############# ##### ######\n * ############ ############ ############# ############ ##### ######\n * ######\n * #############\n * ############\n *\n * Adyen plugin for Shopware 6\n *\n * Copyright (c) 2022 Adyen N.V.\n * This file is open source and available under the MIT license.\n * See the LICENSE file for more info.\n *\n */\n\nconst { Component, Mixin } = Shopware;\nimport template from './adyen-payment-capture.html.twig';\nimport './adyen-payment-capture.scss';\n\nComponent.register('adyen-payment-capture', {\n template,\n\n inject: ['adyenService', 'systemConfigApiService'],\n\n mixins: [\n Mixin.getByName('notification')\n ],\n\n props: {\n order: {\n type: Object,\n required: true\n },\n },\n\n data() {\n return {\n columns: [\n { property: 'pspReference', label: this.$tc('adyen.columnHeaders.pspReference') },\n { property: 'amount', label: this.$tc('adyen.columnHeaders.amount') },\n { property: 'status', label: this.$tc('adyen.columnHeaders.status') },\n { property: 'createdAt', label: this.$tc('adyen.columnHeaders.created') },\n { property: 'updatedAt', label: this.$tc('adyen.columnHeaders.updated') }\n ],\n showModal: false,\n captureRequests: [],\n allowCapture: false,\n captureEnabled: false,\n errorOccurred: false,\n isLoading: true,\n showWidget: false\n };\n },\n\n\n methods: {\n openModal() {\n this.showModal = true;\n },\n\n onCloseModal() {\n this.showModal = false;\n },\n\n onSubmitCapture() {\n this.isLoading = true;\n this.adyenService.capture(this.order.id).then(res => {\n if (res.success) {\n this.fetchCaptureRequests();\n this.createNotificationSuccess({\n title: this.$tc('adyen.adyenPaymentCaptureTitle'),\n message: this.$tc('adyen.captureSuccessful')\n });\n } else {\n this.createNotificationError({\n title: this.$tc('adyen.adyenPaymentCaptureTitle'),\n message: this.$tc(res.message ? res.message : 'adyen.error')\n });\n }\n }).catch(() => {\n this.createNotificationError({\n title: this.$tc('adyen.adyenPaymentCaptureTitle'),\n message: this.$tc('adyen.error')\n });\n }).finally(() => {\n this.isLoading = false;\n this.showModal = false;\n });\n },\n\n fetchCaptureRequests() {\n this.isLoading = true;\n this.adyenService.getCaptureRequests(this.order.id).then((res) => {\n this.captureRequests = res;\n this.isCaptureAllowed();\n }).catch(() => {\n this.errorOccurred = true;\n this.captureRequests = [];\n }).finally(() => {\n this.isLoading = false;\n });\n },\n\n isManualCaptureEnabled() {\n this.isLoading = true;\n this.adyenService.isManualCaptureEnabled(this.order.id).then((res) => {\n this.captureEnabled = res;\n this.showWidget = this.adyenService.isAdyenOrder(this.order) && this.captureEnabled;\n }).catch(() => {\n this.errorOccurred = true;\n this.captureEnabled = false;\n }).finally(() => {\n this.isLoading = false;\n });\n },\n\n isCaptureAllowed() {\n this.isLoading = true;\n this.adyenService.isCaptureAllowed(this.order.id).then((res) => {\n this.allowCapture = res;\n }).catch(() => {\n this.errorOccurred = true;\n this.allowCapture = false;\n }).finally(() => {\n this.isLoading = false;\n });\n }\n },\n\n beforeMount() {\n this.isManualCaptureEnabled();\n this.fetchCaptureRequests();\n }\n})\n","/*\n * ######\n * ######\n * ############ ####( ###### #####. ###### ############ ############\n * ############# #####( ###### #####. ###### ############# #############\n * ###### #####( ###### #####. ###### ##### ###### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ######\n * ############# ############# ############# ############# ##### ######\n * ############ ############ ############# ############ ##### ######\n * ######\n * #############\n * ############\n *\n * Adyen plugin for Shopware 6\n *\n * Copyright (c) 2021 Adyen B.V.\n * This file is open source and available under the MIT license.\n * See the LICENSE file for more info.\n *\n */\n\nconst { Component, Mixin } = Shopware;\nimport template from './adyen-refund.html.twig';\nimport './adyen-refund.scss';\n\nComponent.register('adyen-refund', {\n template,\n\n inject: ['adyenService'],\n\n mixins: [\n Mixin.getByName('notification')\n ],\n\n props: {\n order: {\n type: Object,\n required: true\n },\n },\n\n data() {\n return {\n columns: [\n { property: 'pspReference', label: this.$tc('adyen.columnHeaders.pspReference') },\n { property: 'amount', label: this.$tc('adyen.columnHeaders.amount') },\n { property: 'status', label: this.$tc('adyen.columnHeaders.status') },\n { property: 'createdAt', label: this.$tc('adyen.columnHeaders.created') },\n { property: 'updatedAt', label: this.$tc('adyen.columnHeaders.updated') }\n ],\n refundAmount: 0,\n showModal: false,\n refunds: [],\n allowRefund: true,\n isLoadingTable: true,\n errorOccurred: false,\n isLoadingRefund: false,\n showWidget: false,\n };\n },\n\n methods: {\n openModal() {\n this.showModal = true;\n },\n\n onCloseModal() {\n this.showModal = false;\n },\n\n onRefund() {\n this.isLoadingRefund = true;\n this.adyenService.postRefund(this.order.id, this.refundAmount).then((res) => {\n if (res.success) {\n this.fetchRefunds();\n this.createNotificationSuccess({\n title: this.$tc('adyen.refundTitle'),\n message: this.$tc('adyen.refundSuccessful')\n });\n } else {\n this.createNotificationError({\n title: this.$tc('adyen.refundTitle'),\n message: this.$tc(res.message ? res.message : 'adyen.error')\n });\n }\n }).catch(() => {\n this.createNotificationError({\n title: this.$tc('adyen.refundTitle'),\n message: this.$tc('adyen.error')\n });\n }).finally(() => {\n this.isLoadingRefund = false;\n this.showModal = false;\n });\n },\n\n fetchRefunds() {\n this.isLoadingTable = true;\n this.adyenService.getRefunds(this.order.id).then((res) => {\n this.refunds = res;\n this.isRefundAllowed();\n }).catch(() => {\n this.errorOccurred = true;\n this.refunds = [];\n }).finally(() => {\n this.isLoadingTable = false;\n });\n },\n\n isRefundAllowed() {\n let refundedAmount = 0;\n for (const refund of this.refunds) {\n if (refund.status !== 'Failed') {\n refundedAmount += refund.rawAmount;\n }\n }\n\n this.allowRefund = this.order.amountTotal > (refundedAmount / 100);\n },\n\n isAdyenOrder() {\n const orderTransactions = this.order.transactions;\n let isAdyen = false;\n for (let i = 0; i < orderTransactions.length; i++) {\n if (orderTransactions[i].customFields !== undefined) {\n if (orderTransactions[i].customFields.originalPspReference !== undefined) {\n isAdyen = true;\n }\n }\n }\n\n this.showWidget = isAdyen;\n }\n },\n\n beforeMount() {\n this.isAdyenOrder();\n if (this.showWidget) {\n this.fetchRefunds();\n }\n }\n})\n","export default \"{% block adyen_refund %}\\n \\n
\\n
\\n
\\n {{ $tc('adyen.noRefundsCreated') }}\\n
\\n
\\n \\n {{ $tc('sw-order.documentCard.labelCreateNew') }}\\n \\n
\\n \\n
\\n \\n
\\n \\n
\\n
\\n \\n \\n
\\n
\\n {{ $tc('adyen.refundFetchError') }}\\n
\\n
\\n{% endblock %}\\n\";","export default \"{% block adyen_notifications %}\\n
\\n \\n \\n {% block sw_data_grid_body_columns %}\\n {% block sw_data_grid_column_actions %}\\n \\n {% endblock %}\\n {% endblock %}\\n \\n

{{ $tc('adyen.noNotificationsReceived') }}

\\n
\\n
\\n{% endblock %}\\n\";","/*\n * ######\n * ######\n * ############ ####( ###### #####. ###### ############ ############\n * ############# #####( ###### #####. ###### ############# #############\n * ###### #####( ###### #####. ###### ##### ###### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ######\n * ############# ############# ############# ############# ##### ######\n * ############ ############ ############# ############ ##### ######\n * ######\n * #############\n * ############\n *\n * Adyen plugin for Shopware 6\n *\n * Copyright (c) 2021 Adyen B.V.\n * This file is open source and available under the MIT license.\n * See the LICENSE file for more info.\n *\n */\n\nconst { Component, Mixin } = Shopware;\nimport template from './adyen-notifications.html.twig';\n\n\nComponent.register('adyen-notifications', {\n template,\n\n inject: ['adyenService'],\n\n mixins: [\n Mixin.getByName('notification')\n ],\n\n props: {\n order: {\n type: Object,\n required: true\n },\n },\n\n data() {\n return {\n notifications: [],\n columns: [\n { property: 'pspReference', label: this.$tc('adyen.columnHeaders.pspReference') },\n { property: 'eventCode', label: this.$tc('adyen.columnHeaders.event') },\n { property: 'success', label: this.$tc('adyen.columnHeaders.success') },\n { property: 'amount', label: this.$tc('adyen.columnHeaders.amount') },\n { property: 'status', label: this.$tc('adyen.columnHeaders.status') },\n { property: 'createdAt', label: this.$tc('adyen.columnHeaders.created') },\n { property: 'updatedAt', label: this.$tc('adyen.columnHeaders.updated') },\n { property: 'errorCount', label: this.$tc('adyen.columnHeaders.errorCount') },\n { property: 'errorMessage', label: this.$tc('adyen.columnHeaders.errorMessage') },\n ],\n showWidget: false,\n }\n },\n\n methods: {\n fetchNotifications() {\n this.adyenService.fetchNotifications(this.order.id).then((res) => {\n this.notifications = res;\n });\n },\n\n onReschedule(item) {\n this.adyenService.rescheduleNotification(item.notificationId).then((response) => {\n this.createNotificationSuccess({\n title: this.$tc('adyen.reprocessNotification'),\n message: this.$tc('adyen.notificationRescheduleSuccess')\n });\n\n this.fetchNotifications();\n });\n }\n },\n\n beforeMount() {\n this.showWidget = this.adyenService.isAdyenOrder(this.order);\n if (this.showWidget) {\n this.fetchNotifications();\n }\n }\n})\n","export default \"
\\n
    \\n
    {{ $tc('adyen.authorisedPayments') }}
    \\n
    \\n {{ payment.pspReference }} -\\n {{ payment.method }} -\\n {{ payment.amount }}\\n
    \\n
    {{ errorMessage }}
    \\n
\\n
    \\n \\n
    \\n
    \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
    \\n
    \\n PSP Reference\\n
    \\n
    \\n
    \\n Payment Method\\n
    \\n
    \\n
    \\n Amount\\n
    \\n
    \\n \\n \\n
    \\n {{ payment.method }}\\n
    \\n
    \\n
    \\n {{ payment.amount }}\\n
    \\n
    \\n
    \\n
    \\n {{ errorMessage }}\\n
\\n
\\n\";","/*\n * ######\n * ######\n * ############ ####( ###### #####. ###### ############ ############\n * ############# #####( ###### #####. ###### ############# #############\n * ###### #####( ###### #####. ###### ##### ###### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ######\n * ############# ############# ############# ############# ##### ######\n * ############ ############ ############# ############ ##### ######\n * ######\n * #############\n * ############\n *\n * Adyen plugin for Shopware 6\n *\n * Copyright (c) 2023 Adyen N.V.\n * This file is open source and available under the MIT license.\n * See the LICENSE file for more info.\n *\n */\nlet exports = {};\n\nexports.isVersionOlderThan65 = () => {\n function semverCompare(a, b) {\n if (a.startsWith(b + \"-\")) {\n return -1\n } else if (b.startsWith(a + \"-\")) {\n return 1\n }\n\n return a.localeCompare(b, undefined, { numeric: true, sensitivity: \"case\", caseFirst: \"upper\" })\n };\n\n const version = Shopware.Context.app.config.version;\n\n if (semverCompare(version, \"6.5.0.0\") === -1) {\n return true\n } else {\n return false;\n }\n};\n\nexport default exports;\n","/*\n * ######\n * ######\n * ############ ####( ###### #####. ###### ############ ############\n * ############# #####( ###### #####. ###### ############# #############\n * ###### #####( ###### #####. ###### ##### ###### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ######\n * ############# ############# ############# ############# ##### ######\n * ############ ############ ############# ############ ##### ######\n * ######\n * #############\n * ############\n *\n * Adyen plugin for Shopware 6\n *\n * Copyright (c) 2023 Adyen N.V.\n * This file is open source and available under the MIT license.\n * See the LICENSE file for more info.\n *\n */\n\nconst { Component } = Shopware;\nimport template from './adyen-partial-payments.html.twig';\nimport VersionHelper from '../../helper/versionHelper';\n\nComponent.register('adyen-partial-payments', {\n template,\n\n inject: ['adyenService'],\n\n props: {\n order: {\n type: Object,\n required: true\n },\n },\n\n methods: {\n fetchAdyenPartialPayments() {\n this.adyenService.fetchAdyenPartialPayments(this.order.id).then((res) => {\n if (res.length > 0) {\n this.partialPayments = res;\n } else {\n this.errorMessage = this.$tc('adyen.pendingWebhook')\n }\n });\n }\n },\n\n data() {\n return {\n errorMessage: \"\",\n partialPayments: [],\n showWidget: false,\n isVersionOlderThan65: false\n }\n },\n\n beforeMount() {\n this.isVersionOlderThan65 = VersionHelper.isVersionOlderThan65();\n this.showWidget = this.adyenService.isAdyenOrder(this.order);\n\n if (this.showWidget) {\n this.fetchAdyenPartialPayments();\n }\n }\n});\n","import template from './sw-order-detail-general.html.twig';\n\nShopware.Component.override('sw-order-detail-general', {\n template\n});\n","export default \"{% block sw_order_detail_general_line_items_card %}\\n {% parent %}\\n \\n \\n \\n{% endblock %}\\n\";","import template from './sw-order-detail-base.html.twig';\n\nShopware.Component.override('sw-order-detail-base', {\n template\n});\n","export default \"{% block sw_order_detail_base_custom_fields %}\\n {% parent %}\\n \\n \\n \\n{% endblock %}\\n\";","import template from './sw-order-user-card.html.twig';\n\nShopware.Component.override('sw-order-user-card', {\n template\n});\n","export default \"{% block sw_order_detail_base_secondary_info_payment %}\\n {% parent %}\\n\\n \\n{% endblock %}\\n\";","import template from './sw-order-detail-details.html.twig';\n\nShopware.Component.override('sw-order-detail-details', {\n template\n});\n","export default \"{% block sw_order_detail_details_payment_method_select %}\\n {% parent %}\\n\\n \\n{% endblock %}\\n\";","/*\n * ######\n * ######\n * ############ ####( ###### #####. ###### ############ ############\n * ############# #####( ###### #####. ###### ############# #############\n * ###### #####( ###### #####. ###### ##### ###### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ##### ######\n * ###### ###### #####( ###### #####. ###### ##### ##### ######\n * ############# ############# ############# ############# ##### ######\n * ############ ############ ############# ############ ##### ######\n * ######\n * #############\n * ############\n *\n * Adyen plugin for Shopware 6\n *\n * Copyright (c) 2021 Adyen B.V.\n * This file is open source and available under the MIT license.\n * See the LICENSE file for more info.\n *\n */\n\nimport './service/adyenService';\nimport './component/adyen-config-check-button';\nimport './component/adyen-payment-capture';\nimport './component/adyen-refund';\nimport './component/adyen-notifications';\nimport './component/adyen-partial-payments';\nimport './sw-order-detail-general-override/index';\nimport './sw-order-detail-base-override/index';\nimport './sw-order-user-card-override/index';\nimport './sw-order-detail-details-override/index';\nimport './component/entity/sw-entity-single-select-override';\n\nimport localeEnGb from './snippet/en_GB.json';\n\nShopware.Locale.extend('en-GB', localeEnGb);\n","// style-loader: Adds some css to the DOM by adding a