The JavaScript code you write extends the CartViewModel
class by implementing a callback function that executes during prepricing. The following example shows sample JavaScript that implements a prepricing function:
define( ['jquery', 'knockout', 'ccLogger'], function($, ko, CCLogger) { 'use strict'; return { onLoad: function(widget) { CCLogger.info("Loading external pricing widget"); var callbackMap = new Object(); var performPrepricing = function() { // sample code to invoke external system $.ajax({ type: 'POST', dataType: 'json', url: EXTERNAL_SYSTEM_SERVICE_URL, data: widget.cart().items(), success: function(data) { // update the cart items with external price details, // assuming data has item details with external prices if (data.items && data.items.length > 0) { for (var i = 0; i < widget.cart().items().length; i++) { for (var j = 0; j < data.items.length; j++) { if (widget.cart().items()[i].productId == data.items[j].productId && widget.cart().items()[i].catRefId == data.items[j].catRefId && data.items[i].externalPrice && data.items[j].externalPriceQuantity) { widget.cart().items()[i].externalPrice (data.items[j].externalPrice); widget.cart().items()[i].externalPriceQuantity (data.items[j].externalPriceQuantity); } } } // invoke pricing in this success callback widget.cart().markDirty(); } }, error: function() {} }); }; callbackMap['prepricing'] = performPrepricing; widget.cart().setCallbackFunctions(callbackMap); } } } );
Note that because the asynchronous call to the external pricing system may complete after a pricing operation has already taken place on the Oracle Commerce Cloud server, the code explicitly marks the cart as having been modified after applying the external price information. This forces another pricing operation to be invoked using the external prices.
Some other considerations to take into account when you create your widget:
To avoid making unnecessary calls, it is a good idea for your code to check whether external prices have already been applied to the cart items, and if so, skip calling the external system.
If the external system does not impose a quantity limit on a specific product, your code should set
externalPriceQuantity
to -1, so that the external price is applied to all of the items of the product.