order item x when item y is added to the shopping cart

James Behrens
Giga Guru

We have an ask that if item x is ordered, a laptop for example, that item y (an asset tag) is also automatically added to the shopping cart.

 

I am certain I could do that via CartJS and a business rule but I suspect there is a solution that is far more out of box. I am hoping you can point me in that direction.

6 REPLIES 6

Community Alums
Not applicable

Hi @James Behrens ,

The Approach you mentioned is in the right direction if you want to meet your requirement .

As the details will be stored in table "sc_cart_item" & "sc_cart", whenever user adds item in cart. So you can write business rule to add automatically another item in cart using CartJS API

 

I'm currently using the CartJS API in a similar solution. In that ask, they wanted like catalog items combined so that they create only one line item. It works rather well but I am hoping, in this case, to implement a solution that the RUN side can support. Thanks so much for your quick response!

The combining script if you are interested...

/////////////////////////////////////////////////////////////////////////
//     Business Rule: (TH) Combine like cart items
//                                                                				      
//     Description: This script groups like cart items
//                                                                     
//     History:                                               
//      04/17/2024 -- JMB -- Initial development 
//      05/31/2024 -- JMB -- remove parethesis from quanitity value
////////////////////////////////////////////////////////////////////////
(function executeRule(current, previous /*null when async*/ ) {

    try {
        var cart = new sn_sc.CartJS();
        var cartId = cart.getCartID();
        var cartItems = cart.getCartItems();
        var groupedCartItems = {};

        //loop through the cart items and group them by catalog item
        while (cartItems.next()) {

            var catItem = cartItems.getElement('cat_item.sys_id').getDisplayValue();
            var qty = cartItems.getElement('quantity').getDisplayValue();
			//quantities beyond the values defined in the dropdown are parenthasized
			qty = qty.replace('(','').replace(')','');
            var cartItemId = cartItems.getElement('sys_id').getDisplayValue();

            //group cartItems by the ordered catalog item
            if (groupedCartItems.hasOwnProperty(catItem)) {
                //if exists, update the quantity and track the ones to be deleted
                groupedCartItems[catItem].qty += parseInt(qty);
                groupedCartItems[catItem].otherCartItems.push(cartItemId);
            } else {
                //if it does not exist, create the object
                groupedCartItems[catItem] = {
                    qty: parseInt(qty),
                    firstCartItem: cartItemId,
                    otherCartItems: []
                };
            }
        }

        var currentCatItemId = current.cat_item.getValue();
        if (groupedCartItems.hasOwnProperty(currentCatItemId)) {
            //if exists, update the quantity and stop the insert
            var currentItemId = groupedCartItems[currentCatItemId].firstCartItem;
            var currentQty = groupedCartItems[currentCatItemId].qty + parseInt(current.quantity);

            //update qty on the existing cat item in the cart
            _updateCurrentCount(currentItemId, currentQty, currentCatItemId);

            //don't insert
            current.setAbortAction(true);
        }
    } catch (e) {
        gs.error('(TH) Combine like cart items - evaluate cart  ' + error.message);
    }

    function _updateCurrentCount(itemId, newQty, catItemId) { // function to update the quantity of the first tag

        //build the request object for updateItem
        var request = {
            'sysparm_quantity': newQty.toString()
        };
        request.sysparm_id = catItemId; //'797482b61ba18614349aca292a4bcb03';
        request.variables = {};

        //get the variables from the firstCartItem for this catalog item
        var grCartItem = new GlideRecord('sc_cart_item');
        if (grCartItem.get(itemId)) {
            for (var i in grCartItem.variables) {
                request.variables[i] = grCartItem.variables[i].getDisplayValue();
            }
        }

        //update the cart
        try {
            var cartDetails = cart.updateItem(request, itemId);
        } catch (error) {
            gs.error('(TH) Combine like cart items - update count ' + error.message);
        }

        return;
    }


})(current, previous);

 

@Community Alums you may be right.. I am struggling to get the bundled model to work for me. I am putting this together as a fallback. I would still like something that RUN can maintain but this is super simple. Bonus, it seems to work well with the combining script I have below!

(function executeRule(current, previous /*null when async*/) {
    // Define the Sys ID for asset tag catalog items.. I used the logitec mouse to test
    var assetTagSysId = '89b75085c3ea02104de6bdbc05013131'; // Replace with your Asset Tag catalog item Sys ID
    
    // Check to make sure the added item is not the asset tag
    if (current.cat_item != assetTagSysId) {
        // Create a GlideRecord object for the cart item
        var cartItem = new GlideRecord('sc_cart_item');
        cartItem.initialize();
        cartItem.cart = current.cart; // Use the same cart as the added item
        cartItem.cat_item = assetTagSysId; // Set the catalog item to the asset tag
        cartItem.quantity = current.quantity; // Set quantity to current qty or as needed

        // Insert the asset tag item into the cart
        cartItem.insert();
    }
})(current, previous);

 

Anurag Tripathi
Mega Patron
Mega Patron

Hi,

I believe you can bundle catlaog items, that might work for you

Publish bundled models to product catalog (servicenow.com)

-Anurag