Skip to content

Commit

Permalink
feat: new version cartridges
Browse files Browse the repository at this point in the history
  • Loading branch information
amihajlovski committed Aug 22, 2023
1 parent 56c7b95 commit 6647a09
Show file tree
Hide file tree
Showing 840 changed files with 34,695 additions and 0 deletions.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
'use strict';

/**
* Controller that creates an order from the current basket. It's a pure processing controller and does
* no page rendering. The controller is used by checkout and is called upon the triggered place order action.
* It contains the actual logic to authorize the payment and create the order. The controller communicates the result
* of the order creation process and uses a status object PlaceOrderError to set proper error states.
* The calling controller is must handle the results of the order creation and evaluate any errors returned by it.
*
* @module controllers/COPlaceOrder
*/

/* API Includes */
var OrderMgr = require('dw/order/OrderMgr');
var PaymentMgr = require('dw/order/PaymentMgr');
var Status = require('dw/system/Status');
var Transaction = require('dw/system/Transaction');

/* Script Modules */
var app = require('~/cartridge/scripts/app');
var guard = require('~/cartridge/scripts/guard');
var Cart = app.getModel('Cart');
var Order = app.getModel('Order');
var PaymentProcessor = app.getModel('PaymentProcessor');

/**
* Responsible for payment handling. This function uses PaymentProcessorModel methods to
* handle payment processing specific to each payment instrument. It returns an
* error if any of the authorizations failed or a payment
* instrument is of an unknown payment method. If a payment method has no
* payment processor assigned, the payment is accepted as authorized.
*
* @transactional
* @param {dw.order.Order} order - the order to handle payments for.
* @return {Object} JSON object containing information about missing payments, errors, or an empty object if the function is successful.
*/
// ### Custom Adyen cartridge start ###
function handlePayments(order) {
if (order.getTotalNetPrice().value !== 0.00) {
var paymentInstruments = order.getPaymentInstruments();
if (paymentInstruments.length === 0) {
return {
missingPaymentInfo: true
};
}
/**
* Sets the transaction ID for the payment instrument.
*/
var handlePaymentTransaction = function () {
paymentInstrument.getPaymentTransaction().setTransactionID(order.getOrderNo());
};
for (var i = 0; i < paymentInstruments.length; i++) {
var paymentInstrument = paymentInstruments[i];
if (PaymentMgr.getPaymentMethod(paymentInstrument.getPaymentMethod()).getPaymentProcessor() === null) {
Transaction.wrap(handlePaymentTransaction);
} else {
var authorizationResult = PaymentProcessor.authorize(order, paymentInstrument);
if (authorizationResult.not_supported || authorizationResult.error) {
return {
error: true
};
}
if (authorizationResult.isAdyen) {
return authorizationResult;
}
}
}
}
return {};
}
// ### Custom Adyen cartridge end ###

/**
* The entry point for order creation. This function is not exported, as this controller must only
* be called by another controller.
*
* @transactional
* @return {Object} JSON object that is empty, contains error information, or PlaceOrderError status information.
*/
// ### Custom Adyen cartridge start ###
function start() {
var cart = Cart.get();
if (!cart) {
app.getController('Cart').Show();
return {};
}
var COShipping = app.getController('COShipping');

// Clean shipments.
COShipping.PrepareShipments(cart);

// Make sure there is a valid shipping address, accounting for gift certificates that do not have one.
if (cart.getProductLineItems().size() > 0 && cart.getDefaultShipment().getShippingAddress() === null) {
COShipping.Start();
return {};
}

// Make sure the billing step is fulfilled, otherwise restart checkout.
if (!session.forms.billing.fulfilled.value) {
app.getController('COCustomer').Start();
return {};
}
Transaction.wrap(function () {
cart.calculate();
});
var COBilling = app.getController('COBilling');
Transaction.wrap(function () {
if (!COBilling.ValidatePayment(cart)) {
COBilling.Start();
return {};
}
});

// Recalculate the payments. If there is only gift certificates, make sure it covers the order total, if not
// back to billing page.
Transaction.wrap(function () {
if (!cart.calculatePaymentTransactionTotal()) {
COBilling.Start();
return {};
}
});

// Handle used addresses and credit cards.
var saveCCResult = COBilling.SaveCreditCard();
if (!saveCCResult) {
return {
error: true,
PlaceOrderError: new Status(Status.ERROR, 'confirm.error.technical')
};
}

// Creates a new order. This will internally ReserveInventoryForOrder and will create a new Order with status
// 'Created'.
var order = cart.createOrder();
if (!order) {
// TODO - need to pass BasketStatus to Cart-Show ?
app.getController('Cart').Show();
return {};
}
var handlePaymentsResult = handlePayments(order);
var constants = require('*/cartridge/adyenConstants/constants');
var URLUtils = require('dw/web/URLUtils');

// Cache current order number in order to potentially restore cart.
session.privacy.currentOrderNumber = order.orderNo;
session.privacy.currentOrderToken = order.orderToken;
var submitOrder = handlePaymentsResult.isAdyen === false ||
//adyen is not the payment processor for this payment
handlePaymentsResult.isAdyen && !handlePaymentsResult.action ||
// isAdyen and no action
handlePaymentsResult.action && handlePaymentsResult.action.type === constants.ACTIONTYPES.VOUCHER ||
// action type is voucher
!handlePaymentsResult.action && !handlePaymentsResult.isFinal; // no action and payment is not final (SEPA)
if (handlePaymentsResult.error) {
return Transaction.wrap(function () {
OrderMgr.failOrder(order);
return {
continueUrl: URLUtils.url('Adyen-ShowConfirmation', 'error', 'true', 'errorStatus', 'confirm.error.technical').toString()
};
});
} else if (handlePaymentsResult.missingPaymentInfo) {
return Transaction.wrap(function () {
OrderMgr.failOrder(order);
return {
continueUrl: URLUtils.url('Adyen-ShowConfirmation', 'error', 'true', 'errorStatus', 'confirm.error.technical').toString()
};
});
} else {
if (submitOrder) {
var orderPlacementStatus = Order.submit(order);
if (!orderPlacementStatus.error) {
clearForms();
}
if (handlePaymentsResult.isAdyen) {
return {
continueUrl: URLUtils.url('Adyen-ShowConfirmation', 'authorized', 'true', 'merchantReference', order.orderNo, 'orderToken', order.orderToken).toString()
};
}
return orderPlacementStatus;
}
}
return handlePaymentsResult;
}
// ### Custom Adyen cartridge end ###

function clearForms() {
// Clears all forms used in the checkout process.
session.forms.singleshipping.clearFormElement();
session.forms.multishipping.clearFormElement();
session.forms.billing.clearFormElement();

// clear cached order number
session.privacy.currentOrderNumber = null;
session.privacy.currentOrderToken = null;
}

/**
* Asynchronous Callbacks for OCAPI. These functions result in a JSON response.
* Sets the payment instrument information in the form from values in the httpParameterMap.
* Checks that the payment instrument selected is valid and authorizes the payment. Renders error
* message information if the payment is not authorized.
*/
function submitPaymentJSON() {
var order = Order.get(request.httpParameterMap.order_id.stringValue);
if (!order.object || request.httpParameterMap.order_token.stringValue !== order.getOrderToken()) {
app.getView().render('checkout/components/faults');
return;
}
session.forms.billing.paymentMethods.clearFormElement();
var requestObject = JSON.parse(request.httpParameterMap.requestBodyAsString);
var form = session.forms.billing.paymentMethods;
for (var requestObjectItem in requestObject) {
var asyncPaymentMethodResponse = requestObject[requestObjectItem];
var terms = requestObjectItem.split('_');
if (terms[0] === 'creditCard') {
var value = terms[1] === 'month' || terms[1] === 'year' ? Number(asyncPaymentMethodResponse) : asyncPaymentMethodResponse;
form.creditCard[terms[1]].setValue(value);
} else if (terms[0] === 'selectedPaymentMethodID') {
form.selectedPaymentMethodID.setValue(asyncPaymentMethodResponse);
}
}
if (app.getController('COBilling').HandlePaymentSelection('cart').error || handlePayments().error) {
app.getView().render('checkout/components/faults');
return;
}
app.getView().render('checkout/components/payment_methods_success');
}

/*
* Asynchronous Callbacks for SiteGenesis.
* Identifies if an order exists, submits the order, and shows a confirmation message.
*/
function submit() {
var order = Order.get(request.httpParameterMap.order_id.stringValue);
var orderPlacementStatus;
if (order.object && request.httpParameterMap.order_token.stringValue === order.getOrderToken()) {
orderPlacementStatus = Order.submit(order.object);
if (!orderPlacementStatus.error) {
clearForms();
return app.getController('COSummary').ShowConfirmation(order.object);
}
}
app.getController('COSummary').Start();
}

/*
* Module exports
*/

/*
* Web exposed methods
*/
/** @see module:controllers/COPlaceOrder~submitPaymentJSON */
exports.SubmitPaymentJSON = guard.ensure(['https'], submitPaymentJSON);
/** @see module:controllers/COPlaceOrder~submitPaymentJSON */
exports.Submit = guard.ensure(['https'], submit);

/*
* Local methods
*/
exports.Start = start;
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
'use strict';

/**
* This controller implements the last step of the checkout. A successful handling
* of billing address and payment method selection leads to this controller. It
* provides the customer with a last overview of the basket prior to confirm the
* final order creation.
*
* @module controllers/COSummary
*/

/* API Includes */
var Resource = require('dw/web/Resource');
var Transaction = require('dw/system/Transaction');
var URLUtils = require('dw/web/URLUtils');
/* Script Modules */
var app = require('~/cartridge/scripts/app');
var guard = require('~/cartridge/scripts/guard');
var Cart = app.getModel('Cart');
// ### Custom Adyen cartridge start ###
var AdyenController = require("int_adyen_controllers/cartridge/controllers/Adyen");
// ### Custom Adyen cartridge end ###

/**
* Renders the summary page prior to order creation.
* @param {Object} context context object used for the view
*/
function start(context) {
var cart = Cart.get();

// Checks whether all payment methods are still applicable. Recalculates all existing non-gift certificate payment
// instrument totals according to redeemed gift certificates or additional discounts granted through coupon
// redemptions on this page.
var COBilling = app.getController('COBilling');
if (!COBilling.ValidatePayment(cart)) {
COBilling.Start();
return;
} else {
Transaction.wrap(function () {
cart.calculate();
});
Transaction.wrap(function () {
if (!cart.calculatePaymentTransactionTotal()) {
COBilling.Start();
}
});
var pageMeta = require('~/cartridge/scripts/meta');
var viewContext = require('app_storefront_core/cartridge/scripts/common/extend').immutable(context, {
Basket: cart.object
});
pageMeta.update({
pageTitle: Resource.msg('summary.meta.pagetitle', 'checkout', 'SiteGenesis Checkout')
});
app.getView(viewContext).render('checkout/summary/summary');
}
}

/**
* This function is called when the "Place Order" action is triggered by the
* customer.
*/
// ### Custom Adyen cartridge start ###
function submit() {
// Calls the COPlaceOrder controller that does the place order action and any payment authorization.
// If the order creation failed, it returns a JSON object with an error key and a boolean value.
var placeOrderResult = app.getController('COPlaceOrder').Start();
if (Object.keys(placeOrderResult).length === 0 || placeOrderResult.error) {
start({
PlaceOrderError: placeOrderResult.PlaceOrderError
});
} else {
if (placeOrderResult.isAdyen || placeOrderResult.continueUrl) {
const responseUtils = require('*/cartridge/scripts/util/Response');
responseUtils.renderJSON(placeOrderResult);
} else {
showConfirmation(placeOrderResult.Order);
}
}
}
// ### Custom Adyen cartridge end ##

/**
* Renders the order confirmation page after successful order
* creation. If a nonregistered customer has checked out, the confirmation page
* provides a "Create Account" form. This function handles the
* account creation.
*/
// ### Custom Adyen cartridge start ###
function showConfirmation(order) {
var AdyenHelper = require('*/cartridge/scripts/util/adyenHelper');
var adyenGivingConfig = AdyenHelper.getAdyenGivingConfig(order);
if (!customer.authenticated) {
// Initializes the account creation form for guest checkouts by populating the first and last name with the
// used billing address.
var customerForm = app.getForm('profile.customer');
customerForm.setValue('firstname', order.billingAddress.firstName);
customerForm.setValue('lastname', order.billingAddress.lastName);
customerForm.setValue('email', order.customerEmail);
customerForm.setValue('orderNo', order.orderNo);
}
app.getForm('profile.login.passwordconfirm').clear();
app.getForm('profile.login.password').clear();
var pageMeta = require('~/cartridge/scripts/meta');
pageMeta.update({
pageTitle: Resource.msg('confirmation.meta.pagetitle', 'checkout', 'SiteGenesis Checkout Confirmation')
});
app.getView({
Order: order,
AdyenGivingConfig: adyenGivingConfig,
ContinueURL: URLUtils.https('Account-RegistrationForm') // needed by registration form after anonymous checkouts
}).render('checkout/confirmation/confirmation');
}
// ### Custom Adyen cartridge end ###

/*
* Module exports
*/

/*
* Web exposed methods
*/
/** @see module:controllers/COSummary~Start */
exports.Start = guard.ensure(['https'], start);
/** @see module:controllers/COSummary~Submit */
exports.Submit = guard.ensure(['https', 'post', 'csrf'], submit);

/*
* Local method
*/
exports.ShowConfirmation = showConfirmation;
Loading

0 comments on commit 6647a09

Please sign in to comment.