Skip to content

Commit

Permalink
feat: terminal selection with store filtering from storefront
Browse files Browse the repository at this point in the history
  • Loading branch information
zenit2001 committed Jan 17, 2025
1 parent 0876ed5 commit d20b905
Show file tree
Hide file tree
Showing 16 changed files with 130 additions and 49 deletions.
7 changes: 7 additions & 0 deletions jest/sfccPathSetup.js
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,13 @@ jest.mock(
{ virtual: true },
);

jest.mock(
'*/cartridge/adyen/scripts/payments/getConnectedTerminals',
() =>
require('../src/cartridges/int_adyen_SFRA/cartridge/adyen/scripts/payments/getConnectedTerminals'),
{ virtual: true },
);

jest.mock(
'*/cartridge/adyen/logs/adyenCustomLogs',
() =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ beforeEach(() => {
countryCode: 'mocked_countrycode',
};
getPaymentMethods.mockReturnValue({
adyenConnectedTerminals: { uniqueTerminalIds: ['mocked_id'] },
imagePath: 'example.com',
adyenDescriptions: {},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ const store = require('../../../../store');
const { renderPaymentMethod } = require('./renderPaymentMethod');
const helpers = require('./helpers');
const { installmentLocales } = require('./localesUsingInstallments');
const { getPaymentMethods, fetchGiftCards } = require('../commons');
const {
getPaymentMethods,
fetchGiftCards,
getConnectedTerminals,
} = require('../commons');
const constants = require('../constants');
const {
createElementsToShowRemainingGiftCardAmount,
Expand Down Expand Up @@ -138,11 +142,53 @@ function renderPosTerminals(adyenConnectedTerminals) {
posTerminals.removeChild(posTerminals.firstChild);
}
};

if (adyenConnectedTerminals?.uniqueTerminalIds?.length) {
if (adyenConnectedTerminals) {
removeChilds();
addPosTerminals(adyenConnectedTerminals.uniqueTerminalIds);
addPosTerminals(adyenConnectedTerminals);
}
}

async function addStores(stores) {
const storeDropdown = document.createElement('select');
storeDropdown.id = 'storeList';

const placeholderOption = document.createElement('option');
placeholderOption.value = '';
placeholderOption.text = 'Select a store';
placeholderOption.disabled = true;
placeholderOption.selected = true;
storeDropdown.appendChild(placeholderOption);

const storeArray = typeof stores === 'string' ? stores.split(',') : stores;

storeArray.forEach((terminalStore) => {
const option = document.createElement('option');
option.value = terminalStore.trim();
option.text = terminalStore.trim();
storeDropdown.appendChild(option);
});
const storeDropdownContainer = document.querySelector('#adyenPosStores');
const existingDropdown = storeDropdownContainer.querySelector('#storeList');
if (existingDropdown) {
storeDropdownContainer.removeChild(existingDropdown);
}
storeDropdownContainer.append(storeDropdown);
storeDropdown.addEventListener('change', async () => {
const terminalDropdownContainer =
document.querySelector('#adyenPosTerminals');
const existingTerminalDropdown =
terminalDropdownContainer.querySelector('#terminalList');
if (existingTerminalDropdown) {
terminalDropdownContainer.removeChild(existingTerminalDropdown); // Clear old terminal list
}
const data = await getConnectedTerminals();
const parsedResponse = JSON.parse(data.response);
const { uniqueTerminalIds } = parsedResponse;
if (uniqueTerminalIds) {
renderPosTerminals(uniqueTerminalIds);
document.querySelector('button[value="submit-payment"]').disabled = false;
}
});
}

function setAmazonPayConfig(adyenPaymentMethods) {
Expand Down Expand Up @@ -219,7 +265,6 @@ function setGiftCardContainerVisibility() {
export async function initializeCheckout() {
const paymentMethodsResponse = await getPaymentMethods();
const giftCardsData = await fetchGiftCards();

setCheckoutConfiguration(paymentMethodsResponse);

store.checkoutConfiguration.paymentMethodsResponse = {
Expand Down Expand Up @@ -273,9 +318,8 @@ export async function initializeCheckout() {
helpers.displaySelectedMethod(firstPaymentMethod.value);
}

if (paymentMethodsResponse.adyenConnectedTerminals) {
renderPosTerminals(paymentMethodsResponse.adyenConnectedTerminals);
document.querySelector('button[value="submit-payment"]').disabled = false;
if (window.activeTerminalApiStores) {
addStores(window.activeTerminalApiStores);
}

helpers.createShowConfirmationForm(
Expand Down Expand Up @@ -337,5 +381,6 @@ module.exports = {
renderGiftCardLogo,
setGiftCardContainerVisibility,
applyGiftCards,
addStores,
INIT_CHECKOUT_EVENT,
};
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,19 @@ module.exports.getPaymentMethods = async function getPaymentMethods() {
});
};

module.exports.getConnectedTerminals = async function getConnectedTerminals() {
return $.ajax({
url: window.getConnectedTerminalsURL,
type: 'post',
data: {
csrf_token: $('#adyen-token').val(),
data: JSON.stringify({
storeId: $('#storeList').val(),
}),
},
});
};

/**
* Makes an ajax call to the controller function createTemporaryBasket
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

<!--POS terminal-->
<field formid="terminalId" type="string" mandatory="false" />
<field formid="storeId" type="string" mandatory="false" />

<!--Adyen Component-->
<field formid="adyenStateData" type="string" mandatory="false" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@
window.klarnaWidgetEnabled = ${adyenKlarnaWidgetEnabled};
window.adyenRecurringPaymentsEnabled = ${adyenRecurringPaymentsEnabled};
window.getPaymentMethodsURL = "${URLUtils.https('Adyen-GetPaymentMethods')}";
window.getConnectedTerminalsURL = "${URLUtils.https('Adyen-GetConnectedTerminals')}";
window.checkBalanceUrl = "${URLUtils.https('Adyen-CheckBalance')}";
window.partialPaymentsOrderUrl = "${URLUtils.https('Adyen-PartialPaymentsOrder')}";
window.partialPaymentUrl = "${URLUtils.https('Adyen-partialPayment')}";
window.cancelPartialPaymentOrderUrl = "${URLUtils.https('Adyen-CancelPartialPaymentOrder')}";
window.fetchGiftCardsUrl = "${URLUtils.https('Adyen-fetchGiftCards')}";
window.activeTerminalApiStores = '${pdict.AdyenConfigs.getAdyenActiveStoreId()}';

window.remainingAmountGiftCardResource = "${Resource.msg('remainingAmount.giftCard', 'adyen', null)}";
window.discountedAmountGiftCardResource = "${Resource.msg('discountedAmount.giftCard', 'adyen', null)}";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
<script src="${pdict.AdyenHelper.getCheckoutUrl()}" type="text/javascript"></script>
<input id="terminalId" type="hidden" name="${adyenPaymentFields.terminalId.htmlName}"/>
<input id="storeId" type="hidden" name="${adyenPaymentFields.storeId.htmlName}"/>


<h3>${Resource.msg('terminal.selectStore', 'terminal', null)}</h3>
<div id="adyenPosStores"></div>
<h3>${Resource.msg('terminal.selectTerminal', 'terminal', null)}</h3>
<div id="adyenPosTerminals">
<span>${Resource.msg('terminal.noTerminals', 'terminal', null)}</span>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
terminal.selectStore=Please select your store
terminal.selectTerminal=Please select your terminal
terminal.noTerminals=There are no terminals connected
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ server.get('GetStores', server.middleware.https, (req, res, next) => {
const response = JSON.parse(resultObject.getText());
const mappedData = response.data.map((store) => ({
id: store.id,
description: store.description,
reference: store.reference,
}));

bmHelper.saveMetadataField('Adyen_StoreId', mappedData);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,10 +111,10 @@ document.addEventListener('DOMContentLoaded', () => {
const stores = JSON.parse(availableStores);
stores.forEach((store) => {
const option = document.createElement('option');
option.value = store.id;
option.textContent = `${store.description} (${store.id})`;
option.value = store.reference;
option.textContent = `${store.reference} (${store.id})`;
terminalDropdown.appendChild(option);
if (activeSelectedStores.includes(store.id)) {
if (activeSelectedStores.includes(store.reference)) {
option.selected = true;
}
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const getCheckoutPaymentMethods = require('*/cartridge/adyen/scripts/payments/getCheckoutPaymentMethods');
const getConnectedTerminals = require('*/cartridge/adyen/scripts/payments/getConnectedTerminals');
const paymentFromComponent = require('*/cartridge/adyen/scripts/payments/paymentFromComponent');
const paymentsDetails = require('*/cartridge/adyen/scripts/payments/paymentsDetails');
const redirect3ds1Response = require('*/cartridge/adyen/scripts/payments/redirect3ds1Response');
Expand Down Expand Up @@ -40,4 +41,5 @@ module.exports = {
saveShopperData,
handleCheckoutReview,
createTemporaryBasket,
getConnectedTerminals,
};
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,6 @@ describe('getCheckoutPaymentMethods', () => {
currency: "EUR",
value: 1000,
},
adyenConnectedTerminals: {
"foo": "bar",
},
adyenDescriptions: {
"ideal": "Dutch payment method example description",
"paypal": "PayPal example description",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,26 +27,6 @@ const Order = require('dw/order/Order');
const AdyenHelper = require('*/cartridge/adyen/utils/adyenHelper');
const AdyenConfigs = require('*/cartridge/adyen/utils/adyenConfigs');
const constants = require('*/cartridge/adyen/config/constants');
const AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');

function getTerminals() {
try {
const requestObject = {};
const getTerminalRequest = {};
getTerminalRequest.merchantAccount = AdyenConfigs.getAdyenMerchantAccount();

// storeId is optional
if (AdyenConfigs.getAdyenStoreId() !== null) {
getTerminalRequest.store = AdyenConfigs.getAdyenStoreId();
}

requestObject.request = getTerminalRequest;
return executeCall(constants.SERVICE.CONNECTEDTERMINALS, requestObject);
} catch (error) {
AdyenLogs.fatal_log('/getTerminals call failed', error);
return { error: true, response: '{}' };
}
}

function createTerminalPayment(order, paymentInstrument, terminalId) {
try {
Expand Down Expand Up @@ -238,6 +218,6 @@ function executeCall(serviceType, requestObject) {
}

module.exports = {
getTerminals,
createTerminalPayment,
executeCall,
};
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
const BasketMgr = require('dw/order/BasketMgr');
const Locale = require('dw/util/Locale');
const PaymentMgr = require('dw/order/PaymentMgr');
const AdyenHelper = require('*/cartridge/adyen/utils/adyenHelper');
const adyenTerminalApi = require('*/cartridge/adyen/scripts/payments/adyenTerminalApi');
const paymentMethodDescriptions = require('*/cartridge/adyen/config/paymentMethodDescriptions');
const constants = require('*/cartridge/adyen/config/constants');
const getPaymentMethods = require('*/cartridge/adyen/scripts/payments/adyenGetPaymentMethods');
const AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');

Expand All @@ -19,13 +16,6 @@ function getCountryCode(currentBasket, locale) {
return countryCode || Locale.getLocale(locale.id).country;
}

function getConnectedTerminals() {
if (PaymentMgr.getPaymentMethod(constants.METHOD_ADYEN_POS).isActive()) {
return adyenTerminalApi.getTerminals().response;
}
return '{}';
}

const getRemainingAmount = (giftCardResponse, currency, currentBasket) => {
if (giftCardResponse && JSON.parse(giftCardResponse).remainingAmount) {
const { value = 1000 } = JSON.parse(giftCardResponse).remainingAmount;
Expand All @@ -41,7 +31,6 @@ function getCheckoutPaymentMethods(req, res, next) {
const currentBasket = BasketMgr.getCurrentBasket();
const countryCode = getCountryCode(currentBasket, req.locale);
const adyenURL = `${AdyenHelper.getLoadingContext()}images/logos/medium/`;
const connectedTerminals = JSON.parse(getConnectedTerminals());
const currency = currentBasket
? currentBasket.getTotalGrossPrice().currencyCode
: session.currency.currencyCode;
Expand All @@ -60,7 +49,6 @@ function getCheckoutPaymentMethods(req, res, next) {
AdyenPaymentMethods: paymentMethods,
imagePath: adyenURL,
adyenDescriptions: paymentMethodDescriptions,
adyenConnectedTerminals: connectedTerminals,
amount: { value: paymentAmount.value, currency },
countryCode,
applicationInfo: AdyenHelper.getApplicationInfo(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const PaymentMgr = require('dw/order/PaymentMgr');
const adyenTerminalApi = require('*/cartridge/adyen/scripts/payments/adyenTerminalApi');
const constants = require('*/cartridge/adyen/config/constants');
const AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');
const AdyenConfigs = require('*/cartridge/adyen/utils/adyenConfigs');

function getConnectedTerminals(req, res, next) {
try {
const requestObject = {};
const getTerminalRequest = {};
const { storeId } = JSON.parse(req.form.data);
const activatedStores = AdyenConfigs.getAdyenActiveStoreId();
getTerminalRequest.merchantAccount = AdyenConfigs.getAdyenMerchantAccount();
getTerminalRequest.store = storeId;
requestObject.request = getTerminalRequest;

if (
PaymentMgr.getPaymentMethod(constants.METHOD_ADYEN_POS).isActive() &&
activatedStores.includes(storeId)
) {
const response = adyenTerminalApi.executeCall(
constants.SERVICE.CONNECTEDTERMINALS,
requestObject,
);
res.json({ ...response });
}
} catch (error) {
AdyenLogs.fatal_log('/getConnectedTerminals call failed', error);
res.json({
error: true,
});
}
return next();
}

module.exports = getConnectedTerminals;
6 changes: 6 additions & 0 deletions src/cartridges/int_adyen_SFRA/cartridge/controllers/Adyen.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,12 @@ server.post(
adyen.getCheckoutPaymentMethods,
);

server.post(
'GetConnectedTerminals',
server.middleware.https,
adyen.getConnectedTerminals,
);

/**
* Show the review page template.
*/
Expand Down

0 comments on commit d20b905

Please sign in to comment.