Skip to content

Commit

Permalink
feat: added /getStores for fetching available stores and listing them…
Browse files Browse the repository at this point in the history
… in BM
  • Loading branch information
zenit2001 committed Dec 19, 2024
1 parent cf5ccd5 commit 291dbb7
Show file tree
Hide file tree
Showing 9 changed files with 159 additions and 19 deletions.
10 changes: 10 additions & 0 deletions metadata/site_import/meta/system-objecttype-extensions.xml
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,15 @@
<min-length>0</min-length>
<field-length>0</field-length>
</attribute-definition>
<attribute-definition attribute-id="Adyen_SelectedStoreID">
<display-name xml:lang="x-default">Selected StoreId for Terminal API</display-name>
<description xml:lang="x-default">Selected StoreId for Terminal API</description>
<type>string</type>
<mandatory-flag>false</mandatory-flag>
<externally-managed-flag>false</externally-managed-flag>
<min-length>0</min-length>
<field-length>0</field-length>
</attribute-definition>
<attribute-definition attribute-id="Adyen_API_Key">
<display-name xml:lang="x-default">X-API-KEY of Web service</display-name>
<description xml:lang="x-default">X-API-KEY of Web service</description>
Expand Down Expand Up @@ -713,6 +722,7 @@
<attribute attribute-id="AdyenRatePayID"/>
<attribute attribute-id="Adyen_IntegratorName"/>
<attribute attribute-id="Adyen_StoreId"/>
<attribute attribute-id="Adyen_SelectedStoreID"/>
<attribute attribute-id="AdyenOneClickEnabled"/>
<attribute attribute-id="AdyenTokenisationEnabled"/>
<attribute attribute-id="AdyenCreditCardInstallments"/>
Expand Down
19 changes: 19 additions & 0 deletions metadata/site_import/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,16 @@
<user-id></user-id>
<password/>
</service-credential>
<service-credential service-credential-id="AdyenManagementApiGetStores">
<url>https://management-test.adyen.com/v3/stores</url>
<user-id></user-id>
<password/>
</service-credential>
<service-credential service-credential-id="AdyenManagementApiGetStoresLive">
<url>https://management-live.adyen.com/v3/stores</url>
<user-id></user-id>
<password/>
</service-credential>

<service-profile service-profile-id="Adyen">
<timeout-millis>30000</timeout-millis>
Expand Down Expand Up @@ -228,4 +238,13 @@
<profile-id>Adyen</profile-id>
<credential-id>AdyenPaypalUpdateOrder</credential-id>
</service>
<service service-id="AdyenManagementApiGetStores">
<service-type>HTTP</service-type>
<enabled>true</enabled>
<log-prefix>adyen</log-prefix>
<comm-log-enabled>true</comm-log-enabled>
<mock-mode-enabled>false</mock-mode-enabled>
<profile-id>Adyen</profile-id>
<credential-id>AdyenManagementApiGetStores</credential-id>
</service>
</services>
29 changes: 29 additions & 0 deletions src/cartridges/bm_adyen/cartridge/controllers/AdyenSettings.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const AdyenConfigs = require('*/cartridge/adyen/utils/adyenConfigs');
const AdyenHelper = require('*/cartridge/adyen/utils/adyenHelper');
const constants = require('*/cartridge/adyen/config/constants');
const AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');
const bmHelper = require('*/cartridge/utils/helper');

server.get('Start', (_req, res, next) => {
if (!csrfProtection.validateRequest()) {
Expand Down Expand Up @@ -84,4 +85,32 @@ server.post('TestConnection', server.middleware.https, (req, res, next) => {
return next();
});

server.get('GetStores', server.middleware.https, (req, res, next) => {
try {
const service = bmHelper.initializeAdyenService(
constants.SERVICE.GETSTORES,
'GET',
);
const merchantAccount = AdyenConfigs.getAdyenMerchantAccount();
const callResult = service.call(JSON.stringify({ merchantAccount }));

if (!callResult.isOk()) {
throw new Error('/getStores call failed');
}
const resultObject = callResult.object;
const response = JSON.parse(resultObject.getText());
const mappedData = response.data.map((store) => ({
id: store.id,
description: store.description,
}));

bmHelper.saveMetadataField('Adyen_StoreId', mappedData);
res.json({ success: true, stores: mappedData });
} catch (error) {
AdyenLogs.error_log('Error while fetching stores:', error);
res.json({ success: false });
}
return next();
});

module.exports = server.exports();
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ const expressPaymentMethods = [
},
];

document.addEventListener('DOMContentLoaded', async () => {
const response = await fetch('AdyenSettings-GetStores', {
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
method: 'GET',
});
const result = await response.json();
return result;
});

document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector('#settingsForm');
const troubleshootingForm = document.querySelector('#troubleshootingForm');
Expand Down Expand Up @@ -89,12 +100,28 @@ document.addEventListener('DOMContentLoaded', () => {
const params = 'resizable=yes,width=1000,height=500,left=100,top=100';

const draggableList = document.getElementById('draggable-list');
const availableStores = document.getElementById('storeID').value;
const terminalDropdown = document.getElementById('terminalDropdown');
const activeSelectedStores = document.getElementById('selectedStoreID').value;

let ruleCounter = 0;
const installmentsResult = {};
const listItems = [];
let dragStartIndex;

function renderStores() {
const stores = JSON.parse(availableStores);
stores.forEach((store) => {
const option = document.createElement('option');
option.value = store.id;
option.textContent = `${store.description} (${store.id})`;
terminalDropdown.appendChild(option);
if (activeSelectedStores.includes(store.id)) {
option.selected = true;
}
});
}

function settingChanged(key, value) {
const settingIndex = changedSettings.findIndex(
(setting) => setting.key === key,
Expand Down Expand Up @@ -563,26 +590,40 @@ document.addEventListener('DOMContentLoaded', () => {
})();
});

// add event listener to maintain form updates
form.addEventListener('change', (event) => {
const { name } = event.target;
let { value } = event.target; // get checked boolean value for checkboxes

if (event.target.type === 'checkbox') {
value = event.target.checked;
}
function parseRadioValue(rawValue) {
if (rawValue === 'true') return true;
if (rawValue === 'false') return false;
return rawValue;
}

// convert radio button strings to boolean if values are 'true' or 'false'
if (event.target.type === 'radio') {
if (event.target.value === 'true') {
value = true;
}
function getMultipleSelectValues(selectedOptions) {
return Array.from(selectedOptions)
.map((option) => option.value)
.join(',');
}

if (event.target.value === 'false') {
value = false;
}
function getValueFromInput(type, rawValue, checked, selectedOptions) {
if (type === 'checkbox') {
return checked;
}
if (type === 'select-multiple') {
return getMultipleSelectValues(selectedOptions);
}
if (type === 'radio') {
return parseRadioValue(rawValue);
}
return rawValue;
}

form.addEventListener('change', (event) => {
const {
name,
type,
value: rawValue,
checked,
selectedOptions,
} = event.target;
const value = getValueFromInput(type, rawValue, checked, selectedOptions);
settingChanged(name, value);
});

Expand Down Expand Up @@ -648,5 +689,6 @@ document.addEventListener('DOMContentLoaded', () => {
window.location.reload();
});

renderStores();
createExpressPaymentsComponent(expressPaymentMethods, draggableList);
});
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@
<label class="form-title mb-0" for="storeID">StoreID for Terminal API <small class="text-secondary">(optional)</small></label>
<small id="storeIDHelp" class="form-text mb-1">If you want a POS in your physical store, enter the unique <a class="text-primary" href="https://docs.adyen.com/plugins/salesforce-commerce-cloud/sfra-and-sitegenesis/set-up-the-cartridge/#set-up-in-person-payments" target="_blank">store ID.</a> Keep in mind that you can only assign your POS to a single store. </small>
<div class="input-fields">
<input type="text" class="form-control" name="Adyen_StoreId" id="storeID" aria-describedby="storeIDHelp" value="${AdyenConfigs.getAdyenStoreId() || ''}"/>
<input type="hidden" class="form-control" name="Adyen_StoreId" id="storeID" aria-describedby="storeIDHelp" value="${AdyenConfigs.getAdyenStoreId() || ''}"/>
<input type="hidden" class="form-control" name="Adyen_SelectedStoreID" id="selectedStoreID" aria-describedby="selectedStoreIDHelp" value="${AdyenConfigs.getAdyenActiveStoreId() || ''}"/>
<select class="form-control" id="terminalDropdown" name="Adyen_SelectedStoreID" multiple>
<option value="">Select Store</option>
</select>
</div>
</div>
</div>
Expand Down
31 changes: 31 additions & 0 deletions src/cartridges/bm_adyen/cartridge/utils/helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const Site = require('dw/system/Site');
const Transaction = require('dw/system/Transaction');
const AdyenConfigs = require('*/cartridge/adyen/utils/adyenConfigs');
const AdyenHelper = require('*/cartridge/adyen/utils/adyenHelper');

// Helper function to save to metadata field
function saveMetadataField(field, data) {
const currentSite = Site.getCurrent();
Transaction.wrap(() => {
currentSite.setCustomPreferenceValue(field, JSON.stringify(data));
});
}

// Helper function to initialize a service
function initializeAdyenService(svc, reqMethod) {
const service = AdyenHelper.getService(svc, reqMethod);
const apiKey = AdyenConfigs.getAdyenApiKey();
const merchantAccount = AdyenConfigs.getAdyenMerchantAccount();

if (!service || !apiKey || !merchantAccount) {
throw new Error('Missing request parameters, could not perform the call');
}

service.addHeader('Content-type', 'application/json');
service.addHeader('charset', 'UTF-8');
service.addHeader('X-API-key', apiKey);

return service;
}

module.exports = { saveMetadataField, initializeAdyenService };
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ module.exports = {
CANCELPARTIALPAYMENTORDER: 'AdyenCancelPartialPaymentOrder',
PARTIALPAYMENTSORDER: 'AdyenPartialPaymentsOrder',
PAYPALUPDATEORDER: 'AdyenPaypalUpdateOrder',
GETSTORES: 'AdyenManagementApiGetStores',
},
CONTRACT: {
ONECLICK: 'ONECLICK',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ const adyenConfigsObj = {
return getCustomPreference('Adyen_StoreId');
},

getAdyenActiveStoreId() {
return getCustomPreference('Adyen_SelectedStoreID');
},

getAdyenApiKey() {
return getCustomPreference('Adyen_API_Key');
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ const AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');
/* eslint no-var: off */
let adyenHelperObj = {
// Create the service config used to make calls to the Adyen Checkout API (used for all services)
getService(service) {
getService(service, reqMethod = 'POST') {
let adyenService = null;

try {
adyenService = LocalServiceRegistry.createService(service, {
createRequest(svc, args) {
svc.setRequestMethod('POST');
svc.setRequestMethod(reqMethod);
if (args) {
return args;
}
Expand Down

0 comments on commit 291dbb7

Please sign in to comment.