Skip to content

Commit

Permalink
Improve response body (#1239)
Browse files Browse the repository at this point in the history
* chore: remove basket id from response

* chore: clean session attribute in case of error
  • Loading branch information
amihajlovski authored Jan 23, 2025
1 parent d3d6f1e commit 4ea737a
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ describe('getShippingMethod', () => {
it('should handle fetch rejection', async () => {
fetch.mockRejectedValue(new Error('Fetch failed'));
try {
await getShippingMethod(null, mockBasketId);
await getShippingMethod(null);
} catch (error) {
expect(error.message).toBe('Fetch failed');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ const { APPLE_PAY } = require('./constants');

let checkout;
let shippingMethodsData;
let temporaryBasketId;

function formatCustomerObject(customerData, billingData) {
return {
Expand Down Expand Up @@ -110,12 +109,12 @@ function callPaymentFromComponent(data, resolveApplePay, rejectApplePay) {
});
}

async function selectShippingMethod({ shipmentUUID, ID }, basketId, reject) {
async function selectShippingMethod({ shipmentUUID, ID }, reject) {
const requestBody = {
paymentMethodType: APPLE_PAY,
shipmentUUID,
methodID: ID,
basketId,
isExpressPdp: true,
};
return $.ajax({
type: 'POST',
Expand All @@ -130,10 +129,10 @@ async function selectShippingMethod({ shipmentUUID, ID }, basketId, reject) {
}).fail(() => reject());
}

function getShippingMethod(shippingContact, basketId, reject) {
function getShippingMethod(shippingContact, reject) {
const requestBody = {
paymentMethodType: APPLE_PAY,
basketId,
isExpressPdp: true,
};
if (shippingContact) {
requestBody.address = {
Expand Down Expand Up @@ -204,7 +203,7 @@ async function onAuthorized(resolve, reject, event, amountValue, merchantName) {
};

await callPaymentFromComponent(
{ ...stateData, customer, basketId: temporaryBasketId },
{ ...stateData, customer, isExpressPdp: true },
resolveApplePay,
reject,
);
Expand All @@ -229,7 +228,6 @@ async function onShippingMethodSelected(
);
const calculationResponse = await selectShippingMethod(
matchingShippingMethod,
temporaryBasketId,
reject,
);
if (calculationResponse?.grandTotalAmount) {
Expand All @@ -252,16 +250,11 @@ async function onShippingMethodSelected(

async function onShippingContactSelected(resolve, reject, event, merchantName) {
const { shippingContact } = event;
shippingMethodsData = await getShippingMethod(
shippingContact,
temporaryBasketId,
reject,
);
shippingMethodsData = await getShippingMethod(shippingContact, reject);
if (shippingMethodsData?.shippingMethods?.length) {
const selectedShippingMethod = shippingMethodsData.shippingMethods[0];
const newCalculation = await selectShippingMethod(
selectedShippingMethod,
temporaryBasketId,
reject,
);
if (newCalculation?.grandTotalAmount) {
Expand Down Expand Up @@ -327,8 +320,7 @@ async function init(paymentMethodsResponse) {
onClick: async (resolve, reject) => {
if (window.isExpressPdp) {
const tempBasketResponse = await createTemporaryBasket();
if (tempBasketResponse?.basketId) {
temporaryBasketId = tempBasketResponse.basketId;
if (tempBasketResponse?.temporaryBasketCreated) {
applePayButtonConfig.amount = {
value: tempBasketResponse.amount.value,
currency: tempBasketResponse.amount.currency,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,29 @@ module.exports.getPaymentMethods = async function getPaymentMethods() {
});
};

/**
* Makes an ajax call to the controller function createTemporaryBasket
*/
module.exports.createTemporaryBasket = async function createTemporaryBasket() {
const productForm = document.getElementById('express-product-form');
const data = new FormData(productForm);
const dataFromEntries = Object.fromEntries(data.entries());
const parsedData = JSON.parse(dataFromEntries['selected-express-product']);
return $.ajax({
url: window.createTemporaryBasketUrl,
type: 'post',
data: {
csrf_token: $('#adyen-token').val(),
data: JSON.stringify({
id: parsedData.id,
bundledProducts: parsedData.bundledProducts,
options: parsedData.options,
selectedQuantity: parsedData.selectedQuantity,
}),
},
});
};

module.exports.checkIfExpressMethodsAreReady =
function checkIfExpressMethodsAreReady() {
const expressMethodsConfig = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@
window.fractionDigits = "${AdyenHelper.getFractionDigits()}"
</script>

<input type="hidden" id="adyen-token" name="${pdict.csrf.tokenName}" value="${pdict.csrf.token}"/>
<div id="express-payment-buttons"></div>
<input type="hidden" id="adyen-token" name="${pdict.csrf.tokenName}" value="${pdict.csrf.token}"/>
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ function createTemporaryBasket(req, res, next) {
try {
// Delete any existing open temporary baskets
Transaction.wrap(() => {
session.privacy.temporaryBasketId = null;
BasketMgr.getTemporaryBaskets()
.toArray()
.forEach((basket) => {
Expand All @@ -56,11 +57,12 @@ function createTemporaryBasket(req, res, next) {
if (!tempBasket) {
throw new Error('Temporary basket not created');
}
const { id, bundledProducts, options, selectedQuantity } = req.form[
'selected-express-product'
]
? JSON.parse(req.form['selected-express-product'])
: {};
session.privacy.temporaryBasketId = tempBasket.UUID;

const { id, bundledProducts, options, selectedQuantity } = JSON.parse(
req.form.data,
);

addProductToBasket(
tempBasket,
id,
Expand All @@ -73,11 +75,12 @@ function createTemporaryBasket(req, res, next) {
currency: tempBasket.getTotalGrossPrice().currencyCode,
};
res.json({
basketId: tempBasket.UUID,
temporaryBasketCreated: true,
amount,
});
} catch (error) {
AdyenLogs.error_log('Failed to create temporary basket', error);
session.privacy.temporaryBasketId = null;
res.setStatusCode(500);
res.json({
errorMessage: Resource.msg(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@ const paypalHelper = require('*/cartridge/adyen/utils/paypalHelper');
// eslint-disable-next-line complexity
function callSelectShippingMethod(req, res, next) {
const {
basketId,
isExpressPdp,
shipmentUUID,
methodID,
currentPaymentData,
paymentMethodType,
} = JSON.parse(req.form.data);
const currentBasket = basketId
? BasketMgr.getTemporaryBasket(basketId)
const currentBasket = isExpressPdp
? BasketMgr.getTemporaryBasket(session.privacy.temporaryBasketId)
: BasketMgr.getCurrentBasket();

if (!currentBasket) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,19 @@ function updateShippingAddress(currentBasket, address) {
}
}

function getBasket(basketId) {
return basketId
? BasketMgr.getTemporaryBasket(basketId)
function getBasket(isExpressPdp) {
return isExpressPdp
? BasketMgr.getTemporaryBasket(session.privacy.temporaryBasketId)
: BasketMgr.getCurrentBasket();
}
/**
* Make a request to Adyen to get shipping methods
*/
function callGetShippingMethods(req, res, next) {
try {
const { address, currentPaymentData, paymentMethodType, basketId } =
const { address, currentPaymentData, paymentMethodType, isExpressPdp } =
JSON.parse(req.form.data);
const currentBasket = getBasket(basketId);
const currentBasket = getBasket(isExpressPdp);
if (!currentBasket) {
res.json({
error: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,12 @@ function canSkipSummaryPage(reqDataObj) {
* Make a payment from inside a component, skipping the summary page. (paypal, QRcodes, MBWay)
*/
function paymentFromComponent(req, res, next) {
const { basketId, ...reqDataObj } = JSON.parse(req.form.data);
const { isExpressPdp, ...reqDataObj } = JSON.parse(req.form.data);
if (reqDataObj.cancelTransaction) {
return handleCancellation(res, next, reqDataObj);
}
const currentBasket = basketId
? BasketMgr.getTemporaryBasket(basketId)
const currentBasket = isExpressPdp
? BasketMgr.getTemporaryBasket(session.privacy.temporaryBasketId)
: BasketMgr.getCurrentBasket();
let paymentInstrument;
Transaction.wrap(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ function clearCustomSessionFields() {
session.privacy.partialPaymentData = null;
session.privacy.amazonExpressShopperDetail = null;
session.privacy.giftCardBalance = null;
session.privacy.temporaryBasketId = null;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ function validateBasketAmount(currentBasket) {

function validatePaymentDataFromRequest(req, res, next) {
try {
const currentBasket = BasketMgr.getCurrentBasket();
const { isExpressPdp } = req.form?.data ? JSON.parse(req.form.data) : null;
const currentBasket = isExpressPdp
? BasketMgr.getTemporaryBasket(session.privacy.temporaryBasketId)
: BasketMgr.getCurrentBasket();
validateBasketAmount(currentBasket);
} catch (e) {
AdyenLogs.fatal_log(`Error occurred: ${e.message}`);
Expand Down

0 comments on commit 4ea737a

Please sign in to comment.