Skip to content

Commit

Permalink
NTR: refactored JS
Browse files Browse the repository at this point in the history
  • Loading branch information
Vitalij Mik committed Oct 21, 2024
1 parent 6673e0e commit 38e1cf6
Show file tree
Hide file tree
Showing 26 changed files with 320 additions and 51 deletions.
6 changes: 3 additions & 3 deletions src/Components/ApplePayDirect/ApplePayDirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ public function restoreCart(SalesChannelContext $context): void
* @throws \Exception
* @return SalesChannelContext
*/
public function prepareCustomer(string $firstname, string $lastname, string $email, string $street, string $zipcode, string $city, string $countryCode, string $phone, string $paymentToken, int $acceptedDataProtection, SalesChannelContext $context): SalesChannelContext
public function prepareCustomer(string $firstname, string $lastname, string $email, string $street, string $zipcode, string $city, string $countryCode, string $phone, string $paymentToken, ?int $acceptedDataProtection, SalesChannelContext $context): SalesChannelContext
{
if (empty($paymentToken)) {
throw new \Exception('PaymentToken not found!');
Expand All @@ -366,8 +366,8 @@ public function prepareCustomer(string $firstname, string $lastname, string $ema
$customer = $this->customerService->createGuestAccount(
$address,
$applePayID,
$acceptedDataProtection,
$context
$context,
$acceptedDataProtection
);

if (! $customer instanceof CustomerEntity) {
Expand Down
4 changes: 2 additions & 2 deletions src/Components/PaypalExpress/PayPalExpress.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ public function loadSession(string $sessionId, SalesChannelContext $context): Se
* @throws \Exception
* @return SalesChannelContext
*/
public function prepareCustomer(AddressStruct $shippingAddress, int $acceptedDataProtection, SalesChannelContext $context, ?AddressStruct $billingAddress = null): SalesChannelContext
public function prepareCustomer(AddressStruct $shippingAddress, SalesChannelContext $context, ?int $acceptedDataProtection, ?AddressStruct $billingAddress = null): SalesChannelContext
{
$updateShippingAddress = true;
$paypalExpressId = $this->getActivePaypalExpressID($context);
Expand All @@ -176,8 +176,8 @@ public function prepareCustomer(AddressStruct $shippingAddress, int $acceptedDat
$customer = $this->customerService->createGuestAccount(
$shippingAddress,
$paypalExpressId,
$acceptedDataProtection,
$context,
$acceptedDataProtection,
$billingAddress
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Kiener\MolliePayments\Components\PaypalExpress\PayPalExpress;
use Kiener\MolliePayments\Service\CartService;
use Kiener\MolliePayments\Service\CustomFieldsInterface;
use Kiener\MolliePayments\Service\SettingsService;
use Kiener\MolliePayments\Struct\Address\AddressStruct;
use Kiener\MolliePayments\Traits\Storefront\RedirectTrait;
use Mollie\Api\Exceptions\ApiException;
Expand Down Expand Up @@ -40,6 +41,7 @@ class PaypalExpressControllerBase extends StorefrontController
* @var LoggerInterface
*/
private $logger;
private SettingsService $settingsService;


/**
Expand All @@ -48,12 +50,13 @@ class PaypalExpressControllerBase extends StorefrontController
* @param RouterInterface $router
* @param LoggerInterface $logger
*/
public function __construct(PayPalExpress $paypalExpress, CartService $cartService, RouterInterface $router, LoggerInterface $logger)
public function __construct(PayPalExpress $paypalExpress, CartService $cartService, RouterInterface $router, SettingsService $settingsService, LoggerInterface $logger)
{
$this->paypalExpress = $paypalExpress;
$this->cartService = $cartService;
$this->router = $router;
$this->logger = $logger;
$this->settingsService = $settingsService;
}

/**
Expand All @@ -64,16 +67,21 @@ public function __construct(PayPalExpress $paypalExpress, CartService $cartServi
*/
public function startCheckout(Request $request, SalesChannelContext $context): Response
{
$productId = $request->get('productId');
$quantity = (int)$request->get('quantity', 1);
if ($request->isMethod(Request::METHOD_POST) && $productId !== null) {
$this->cartService->addProduct($productId, $quantity, $context);
$redirectUrl = $this->getCheckoutCartPage($this->router);

$settings = $this->settingsService->getSettings($context->getSalesChannelId());

if ($settings->isPaypalExpressEnabled() === false) {
$this->logger->error('Paypal Express is disabled');
return new RedirectResponse($redirectUrl);
}

$cart = $this->cartService->getCalculatedMainCart($context);


$cartExtension = $cart->getExtension(CustomFieldsInterface::MOLLIE_KEY);
$oldSessionId = null;

if ($cartExtension instanceof ArrayStruct) {
$oldSessionId = $cartExtension[CustomFieldsInterface::PAYPAL_EXPRESS_SESSION_ID_KEY] ?? null;
}
Expand All @@ -83,18 +91,25 @@ public function startCheckout(Request $request, SalesChannelContext $context): R
} else {
$session = $this->paypalExpress->startSession($cart, $context);

$cartExtension = new ArrayStruct([
$cartExtension = [
CustomFieldsInterface::PAYPAL_EXPRESS_SESSION_ID_KEY => $session->id
]);
$cart->addExtension(CustomFieldsInterface::MOLLIE_KEY, $cartExtension);
];

if ($settings->isRequireDataProtectionCheckbox()) {
$cartExtension[CustomFieldsInterface::ACCEPTED_DATA_PROTECTION] = (bool)$request->get(CustomFieldsInterface::ACCEPTED_DATA_PROTECTION, false);
}

$cart->addExtension(CustomFieldsInterface::MOLLIE_KEY, new ArrayStruct($cartExtension));

$this->cartService->persistCart($cart, $context);
}

$redirectUrl = $session->getRedirectUrl();
if ($redirectUrl === null) {
$redirectUrl = $this->getCheckoutCartPage($this->router);
$sessionRedirect = $session->getRedirectUrl();
if ($sessionRedirect !== null) {
$this->logger->error('Paypal Express redirect URL is empty', [
'sessionId' => $session->id,
]);
$redirectUrl = $sessionRedirect;
}

return new RedirectResponse($redirectUrl);
Expand All @@ -106,17 +121,30 @@ public function startCheckout(Request $request, SalesChannelContext $context): R
*/
public function finishCheckout(SalesChannelContext $context): Response
{
$returnUrl = $this->getCheckoutCartPage($this->router);

$settings = $this->settingsService->getSettings($context->getSalesChannelId());

if ($settings->isPaypalExpressEnabled() === false) {
$this->logger->error('Paypal Express is disabled');
return new RedirectResponse($returnUrl);
}

$cart = $this->cartService->getCalculatedMainCart($context);
$cartExtension = $cart->getExtension(CustomFieldsInterface::MOLLIE_KEY);

$payPalExpressSessionId = null;
$acceptedDataProtection = null;

if ($cartExtension instanceof ArrayStruct) {
$payPalExpressSessionId = $cartExtension[CustomFieldsInterface::PAYPAL_EXPRESS_SESSION_ID_KEY] ?? null;
if ($settings->isRequireDataProtectionCheckbox()) {
$acceptedDataProtection = $cartExtension[CustomFieldsInterface::ACCEPTED_DATA_PROTECTION] ?? false;
}
}


$returnUrl = $this->getCheckoutCartPage($this->router);



if ($payPalExpressSessionId === null) {
Expand All @@ -136,7 +164,6 @@ public function finishCheckout(SalesChannelContext $context): Response
}



$methodDetails = $payPalExpressSession->methodDetails;


Expand Down Expand Up @@ -195,7 +222,6 @@ public function finishCheckout(SalesChannelContext $context): Response
}



try {
# we have to update the cart extension before a new user is created and logged in, otherwise the extension is not saved
$cartExtension = new ArrayStruct([
Expand All @@ -209,7 +235,7 @@ public function finishCheckout(SalesChannelContext $context): Response


# create new account or find existing and login
$this->paypalExpress->prepareCustomer($shippingAddress, 1, $context, $billingAddress);
$this->paypalExpress->prepareCustomer($shippingAddress, $context, $acceptedDataProtection, $billingAddress);
} catch (\Throwable $e) {
$this->logger->error('Failed to create customer or cart', [
'message' => $e->getMessage(),
Expand All @@ -218,7 +244,6 @@ public function finishCheckout(SalesChannelContext $context): Response
}



$returnUrl = $this->getCheckoutConfirmPage($this->router);
return new RedirectResponse($returnUrl);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,12 +228,12 @@ Component.override('sw-order-detail-general', {
*
*/
copyPaymentUrlToClipboard() {
let fallback = async function(e) {
const fallback = async function(e) {
await navigator.clipboard.writeText(e)
};

// eslint-disable-next-line no-undef
let clipboard = typeof Shopware.Utils.dom.copyToClipboard === 'function' ? Shopware.Utils.dom.copyToClipboard : fallback;
const clipboard = typeof Shopware.Utils.dom.copyToClipboard === 'function' ? Shopware.Utils.dom.copyToClipboard : fallback;
// eslint-disable-next-line no-undef
clipboard(this.molliePaymentUrl);
this.molliePaymentUrlCopied = true;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import HttpClient from '../services/HttpClient';
import Plugin from "../Plugin";
import Plugin from '../Plugin';

/**
* This plugin manage the credit card mandate of the customer
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import HttpClient from '../services/HttpClient';
import Plugin from "../Plugin";
import ApplePaySessionFactory from "../services/ApplePaySessionFactory";
import Plugin from '../Plugin';
import ApplePaySessionFactory from '../services/ApplePaySessionFactory';

export default class MollieApplePayDirect extends Plugin {

Expand All @@ -23,7 +23,7 @@ export default class MollieApplePayDirect extends Plugin {
// we need to re-init all apple pay button
// once the offcanvas is loaded (lazy) into the DOM

const pluginOffCanvasInstances = window.PluginManager.getPluginList().OffCanvasCart.get("instances");
const pluginOffCanvasInstances = window.PluginManager.getPluginList().OffCanvasCart.get('instances');
if (pluginOffCanvasInstances.length > 0) {
const pluginOffCanvas = pluginOffCanvasInstances[0];
pluginOffCanvas.$emitter.subscribe('offCanvasOpened', me.initCurrentPage.bind(me));
Expand Down Expand Up @@ -192,8 +192,8 @@ export default class MollieApplePayDirect extends Plugin {


const formData = new FormData(productForm);
formData.delete("redirectTo");
formData.append("isExpressCheckout", "1");
formData.delete('redirectTo');
formData.append('isExpressCheckout', '1');


fetch(productForm.action, {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import HttpClient from '../services/HttpClient';
import Plugin from "../Plugin";
import Plugin from '../Plugin';

export default class MollieApplePayPaymentMethod extends Plugin {

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Plugin from "../Plugin";
import Plugin from '../Plugin';

export default class MollieBancomatPlugin extends Plugin {

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import HttpClient from '../services/HttpClient';
import Plugin from "../Plugin";
import Plugin from '../Plugin';

/**
* This plugin manage the credit card mandate of customer
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import Plugin from '../Plugin';
import PrivacyNoteElement from '../repository/PrivacyNoteElement';
import BuyButtonRepository from '../repository/BuyButtonRepository';
import ExpressButtonsRepository from '../repository/ExpressButtonsRepository';
import ExpressAddToCart from '../services/ExpressAddToCart';

export const MOLLIE_EXPRESS_CHECKOUT_EVENT = 'MollieStartExpressCheckout';

export class MollieExpressActions extends Plugin {


init() {

const pluginOffCanvasInstances = window.PluginManager.getPluginList().OffCanvasCart.get('instances');
if (pluginOffCanvasInstances.length > 0) {
pluginOffCanvasInstances.forEach((pluginOffCanvas) => {
pluginOffCanvas.$emitter.subscribe('offCanvasOpened', this.bindEvents.bind(this));
});
}

this.bindEvents();

}

bindEvents() {
const expressButtonsRepository = new ExpressButtonsRepository();
const expressButtons = expressButtonsRepository.findAll();

if (expressButtons.length === 0) {
return;
}

const buyButtonRepository = new BuyButtonRepository();

expressButtons.forEach((button) => {


button.classList.remove('d-none');
button.addEventListener('click', this.onButtonClick)

const buyButton = buyButtonRepository.find(button);
if (!(buyButton instanceof HTMLButtonElement)) {
return;
}

if (buyButton.hasAttribute('disabled')) {
button.classList.add('d-none');
button.removeEventListener('click', this.onButtonClick)
}

const buyButtonForm = buyButton.closest('form');
if (!(buyButtonForm instanceof HTMLFormElement)) {
return;
}

buyButtonForm.addEventListener('change', () => {

button.classList.remove('d-none');
button.addEventListener('click', this.onButtonClick)

if (buyButton.hasAttribute('disabled')) {

button.classList.add('d-none');
button.removeEventListener('click', this.onButtonClick)
}
})

});
}

async onButtonClick(event) {
let target = event.target;
if (!(target instanceof HTMLButtonElement)) {
target = target.closest('button');
}

const privacyNote = new PrivacyNoteElement();

const privacyNoteElement = privacyNote.find(target);

if (privacyNoteElement instanceof HTMLDivElement) {
privacyNoteElement.classList.add('was-validated');
const isValid = privacyNote.validate(privacyNoteElement);
if (isValid === false) {
return;
}
}
const mollieEvent = new Event(MOLLIE_EXPRESS_CHECKOUT_EVENT);

const expressAddToCart = new ExpressAddToCart();
await expressAddToCart.addItemToCart(target).then(() => {
target.dispatchEvent(mollieEvent);
});
}
}
Loading

0 comments on commit 38e1cf6

Please sign in to comment.