Skip to content

Commit

Permalink
Moving the place order logic into webhook processing part (#1255)
Browse files Browse the repository at this point in the history
* fix: moving the place order logic into webhook processing part

* chore: linting

* fix: not updating statuses for a failed order

* chore: returning for place order function in case it doesn't enter if
  • Loading branch information
zenit2001 authored Feb 14, 2025
1 parent 4df9fce commit a963908
Show file tree
Hide file tree
Showing 11 changed files with 71 additions and 183 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const Transaction = require('dw/system/Transaction');
const BasketMgr = require('dw/order/BasketMgr');
const adyenCheckout = require('*/cartridge/adyen/scripts/payments/adyenCheckout');
const AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');
const COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
const AdyenHelper = require('*/cartridge/adyen/utils/adyenHelper');
const paypalHelper = require('*/cartridge/adyen/utils/paypalHelper');
const constants = require('*/cartridge/adyen/config/constants');
Expand Down Expand Up @@ -50,11 +49,6 @@ function makeExpressPaymentDetailsCall(req, res, next) {
currentBasket,
session.privacy.paypalExpressOrderNo,
);
const fraudDetectionStatus = { status: 'success' };
const placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus);
if (placeOrderResult.error) {
throw new Error('Failed to place the PayPal express order');
}

response.orderNo = order.orderNo;
response.orderToken = order.orderToken;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Show Confirmation Payment From Component should redirect on placeOrder error 1`] = `
[
[
"Checkout-Begin",
"stage",
"payment",
"paymentError",
"mocked_error.payment.not.valid",
],
]
`;

exports[`Show Confirmation Payment From Component should redirect on unsuccessful payment 1`] = `
[
[
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,6 @@ describe('Show Confirmation Payment From Component', () => {
expect(URLUtils.url.mock.calls[0][0]).toBe('Order-Confirm');
},
);
it('should redirect on placeOrder error', () => {
const adyenCheckout = require('*/cartridge/adyen/scripts/payments/adyenCheckout');
const URLUtils = require('dw/web/URLUtils');
const COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
adyenCheckout.doPaymentsDetailsCall.mockImplementation(() => ({
resultCode: 'Authorised',
}));
COHelpers.placeOrder.mockImplementation(() => ({ error: true }));
showConfirmationPaymentFromComponent(req, res, jest.fn());
expect(URLUtils.url.mock.calls).toMatchSnapshot();
});
it('should redirect on unsuccessful payment', () => {
const adyenCheckout = require('*/cartridge/adyen/scripts/payments/adyenCheckout');
const URLUtils = require('dw/web/URLUtils');
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ const Transaction = require('dw/system/Transaction');
const URLUtils = require('dw/web/URLUtils');
const Resource = require('dw/web/Resource');
const adyenCheckout = require('*/cartridge/adyen/scripts/payments/adyenCheckout');
const COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
const AdyenHelper = require('*/cartridge/adyen/utils/adyenHelper');
const AdyenConfigs = require('*/cartridge/adyen/utils/adyenConfigs');
const constants = require('*/cartridge/adyen/config/constants');
Expand Down Expand Up @@ -47,18 +46,6 @@ function handleAuthorisedPayment(
adyenPaymentInstrument,
{ res, next },
) {
// custom fraudDetection
const fraudDetectionStatus = { status: 'success' };
const isPayPalExpress = order.custom.Adyen_paypalExpressResponse;

// Places the order, for PayPal express the order is placed from makeExpressPaymentDetailsCall.js
if (!isPayPalExpress) {
const placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus);
if (placeOrderResult.error) {
return handlePaymentError(order, adyenPaymentInstrument, { res, next });
}
}

Transaction.wrap(() => {
AdyenHelper.savePaymentDetails(adyenPaymentInstrument, order, result);
});
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ const adyenCheckout = require('*/cartridge/adyen/scripts/payments/adyenCheckout'
const constants = require('*/cartridge/adyen/config/constants');
const payment = require('*/cartridge/adyen/scripts/showConfirmation/handlePayment');
const clearForms = require('*/cartridge/adyen/utils/clearForms');
const handleAuthorised = require('*/cartridge/adyen/scripts/showConfirmation/authorise');
const AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');
const AdyenHelper = require('*/cartridge/adyen/utils/adyenHelper');
const AdyenConfigs = require('*/cartridge/adyen/utils/adyenConfigs');

function getPaymentDetailsPayload(querystring) {
const details = querystring.redirectResult
Expand Down Expand Up @@ -38,6 +38,37 @@ function getPaymentsDetailsResult(
return result;
}

function handleOrderConfirm(
adyenPaymentInstrument,
result,
order,
{ res, next },
) {
Transaction.wrap(() => {
AdyenHelper.savePaymentDetails(adyenPaymentInstrument, order, result);
});

clearForms.clearForms();
// determines SFRA version for backwards compatibility
if (AdyenConfigs.getAdyenSFRA6Compatibility() === true) {
res.render('orderConfirmForm', {
orderID: order.orderNo,
orderToken: order.orderToken,
});
} else {
res.redirect(
URLUtils.url(
'Order-Confirm',
'ID',
order.orderNo,
'token',
order.orderToken,
).toString(),
);
}
return next();
}

function handlePaymentsDetailsResult(
adyenPaymentInstrument,
detailsResult,
Expand All @@ -51,7 +82,7 @@ function handlePaymentsDetailsResult(
constants.RESULTCODES.RECEIVED,
].indexOf(detailsResult.resultCode) > -1
) {
return handleAuthorised(
return handleOrderConfirm(
adyenPaymentInstrument,
detailsResult,
order,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ const HashMap = require('dw/util/HashMap');
const Mail = require('dw/net/Mail');
const Template = require('dw/util/Template');
const Transaction = require('dw/system/Transaction');
const Order = require('dw/order/Order');
const COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
const OrderModel = require('*/cartridge/models/order');

function sendEmail(order) {
Expand Down Expand Up @@ -37,19 +35,6 @@ function sendEmail(order) {
function submit(order) {
try {
Transaction.begin();
// Places the order if not placed yet
if (order.status.value === Order.ORDER_STATUS_CREATED) {
// custom fraudDetection
const fraudDetectionStatus = { status: 'success' };
const placeOrderResult = COHelpers.placeOrder(
order,
fraudDetectionStatus,
);
if (placeOrderResult.error) {
return placeOrderResult;
}
}

sendEmail(order);
Transaction.commit();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,23 @@

const PaymentMgr = require('dw/order/PaymentMgr');
const Order = require('dw/order/Order');
const COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');

// script includes
const constants = require('*/cartridge/adyen/config/constants');
const adyenHelper = require('*/cartridge/adyen/utils/adyenHelper');
const AdyenLogs = require('*/cartridge/adyen/logs/adyenCustomLogs');

function placeOrder(order) {
const fraudDetectionStatus = { status: 'success' };
// Only created orders can be placed
if (order.status.value === Order.ORDER_STATUS_CREATED) {
const placeOrder = COHelpers.placeOrder(order, fraudDetectionStatus);
return placeOrder;
}
return { error: true };
}

function execute(args) {
const result = handle(args.CustomObj);

Expand Down Expand Up @@ -104,12 +115,14 @@ function handle(customObj) {
`Order date ${orderCreateDate} , orderCreateDateDelay ${orderCreateDateDelay} , currentDate ${currentDate}`,
);
if (orderCreateDateDelay < currentDate) {
const totalAmount = adyenHelper.getCurrencyValueForApi(
order.getTotalGrossPrice(),
).value;
switch (customObj.custom.eventCode) {
case 'AUTHORISATION':
// Check if one of the adyen payment methods was used during payment
// Or if the payment method belongs to adyen payment processors
const paymentInstruments = order.getPaymentInstruments();
let adyenPaymentInstrument = null;
for (const pi in paymentInstruments) {
if (
[
Expand All @@ -132,16 +145,10 @@ function handle(customObj) {
// Move adyen log request to order payment transaction
paymentInstruments[pi].paymentTransaction.custom.Adyen_log =
customObj.custom.Adyen_log;
adyenPaymentInstrument = paymentInstruments[pi];
}
}
if (customObj.custom.success === 'true' && adyenPaymentInstrument) {
const amountPaid =
parseFloat(order.custom.Adyen_value) +
parseFloat(customObj.custom.value);
const totalAmount = adyenHelper.getCurrencyValueForApi(
adyenPaymentInstrument.getPaymentTransaction().getAmount(),
).value;
if (customObj.custom.success === 'true') {
const amountPaid = parseFloat(customObj.custom.value);
if (order.paymentStatus.value === Order.PAYMENT_STATUS_PAID) {
AdyenLogs.info_log(
`Duplicate callback received for order ${order.orderNo}.`,
Expand All @@ -152,13 +159,16 @@ function handle(customObj) {
`Partial amount ${customObj.custom.value} received for order number ${order.orderNo} with total amount ${totalAmount}`,
);
} else {
order.setPaymentStatus(Order.PAYMENT_STATUS_PAID);
order.setExportStatus(Order.EXPORT_STATUS_READY);
order.setConfirmationStatus(Order.CONFIRMATION_STATUS_CONFIRMED);
AdyenLogs.info_log(
`Order ${order.orderNo} updated to status PAID.`,
);
result.SubmitOrder = true;
const placeOrderResult = placeOrder(order);
if (!placeOrderResult.error) {
order.setPaymentStatus(Order.PAYMENT_STATUS_PAID);
order.setExportStatus(Order.EXPORT_STATUS_READY);
order.setConfirmationStatus(Order.CONFIRMATION_STATUS_CONFIRMED);
AdyenLogs.info_log(
`Order ${order.orderNo} updated to status PAID.`,
);
result.SubmitOrder = true;
}
}
order.custom.Adyen_eventCode = customObj.custom.eventCode;
order.custom.Adyen_value = amountPaid.toString();
Expand Down Expand Up @@ -221,9 +231,18 @@ function handle(customObj) {
}
break;
case 'ORDER_CLOSED':
if (customObj.custom.success === 'true') {
order.setExportStatus(Order.EXPORT_STATUS_READY);
AdyenLogs.info_log(`Order ${order.orderNo} closed`);
// Placing the order for partial paymetns once OFFER_CLOSED webhook came, and the total amount matches order amount
if (
customObj.custom.success === 'true' &&
parseFloat(customObj.custom.value) === parseFloat(totalAmount)
) {
const placeOrderResult = placeOrder(order);
if (!placeOrderResult.error) {
order.setPaymentStatus(Order.PAYMENT_STATUS_PAID);
order.setExportStatus(Order.EXPORT_STATUS_READY);
order.setConfirmationStatus(Order.CONFIRMATION_STATUS_CONFIRMED);
AdyenLogs.info_log(`Order ${order.orderNo} placed and closed`);
}
}
break;
case 'OFFER_CLOSED':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,17 +209,6 @@ function placeOrder(req, res, next) {
return next();
}

// Places the order
var placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus);

if (placeOrderResult.error) {
res.json({
error: true,
errorMessage: Resource.msg('error.technical', 'checkout', null)
});
return next();
}

if (req.currentCustomer.addressBook) {
// save all used shipping addresses to address book of the logged in customer
var allAddresses = addressHelpers.gatherShippingAddresses(order);
Expand Down

0 comments on commit a963908

Please sign in to comment.