Limit Cart Quantity by Category in Service Catalog
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
3 weeks ago
I am working on a requirement where end users should only be able to order up to five items from a specific category in the Service Catalog. The category is Cloud Guardians.
The expected behavior is:
• When the user adds one to five items, the cart should allow ordering normally.
• When the user adds six items from this category, the cart should block the order and display a message that the limit has been exceeded.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
3 weeks ago
This can be acheived though Business Rule on sc_cart_item.
The following script will intercept the action of adding an item to the cart. It calculates the total quantity of items in the user's cart that belong to the "Cloud Guardians" category and aborts the action if the limit is exceeded.
(function executeRule(current, previous /*null when async*/) {
// 1. CONFIGURATION
// Best practice: Store this limit and category name in System Properties
var limit = 5;
var targetCategoryName = 'Cloud Guardians';
// 2. CHECK CURRENT ITEM
// If the item being added isn't in the target category, exit the script immediately
if (current.cat_item.category.title != targetCategoryName) {
return;
}
// 3. CALCULATE EXISTING CART QUANTITY
// We need to sum the quantity of ALL items currently in this user's cart
// that share the same category.
var agg = new GlideAggregate('sc_cart_item');
agg.addQuery('cart', current.cart); // Filter by the user's current cart
agg.addQuery('cat_item.category.title', targetCategoryName); // Filter by category
// EXCLUDE CURRENT RECORD:
// If this is an 'Update' (user changing qty in cart), we don't want to
// count the old version of this record, or we will double count.
if (!current.isNewRecord()) {
agg.addQuery('sys_id', '!=', current.sys_id);
}
agg.addAggregate('SUM', 'quantity');
agg.query();
var existingQty = 0;
if (agg.next()) {
existingQty = parseInt(agg.getAggregate('SUM', 'quantity'), 10);
}
// 4. VALIDATE TOTAL
// Add existing cart quantity + the new quantity attempting to be added
var totalQty = existingQty + parseInt(current.quantity, 10);
if (totalQty > limit) {
// 5. ABORT ACTION
gs.addErrorMessage('You are limited to ' + limit + ' items from the ' + targetCategoryName + ' category. Your cart currently contains ' + existingQty + ' and you are trying to add ' + current.quantity + '.');
current.setAbortAction(true);
}
})(current, previous);
ɪꜰ ᴍʏ ᴀɴꜱᴡᴇʀ ʜᴀꜱ ʜᴇʟᴘᴇᴅ ᴡɪᴛʜ ʏᴏᴜʀ Qᴜᴇꜱᴛɪᴏɴ, ᴘʟᴇᴀꜱᴇ ᴍᴀʀᴋ ᴍʏ ᴀɴꜱᴡᴇʀ ᴀꜱ ᴛʜᴇ ᴀᴄᴄᴇᴘᴛᴇᴅ ꜱᴏʟᴜᴛɪᴏɴ ᴀɴᴅ ɢɪᴠᴇ ᴀ ᴛʜᴜᴍʙꜱ ᴜᴘ.
ʙᴇꜱᴛ ʀᴇɢᴀʀᴅꜱ
ꜱʀᴇᴇʀᴀᴍ