Ensuring Stock Availability During Sales Order Creation in NetSuite

In NetSuite, ensuring stock availability before creating a Sales Order (SO) is essential for smooth operations and effective inventory management. A dynamic solution is a Client Script that validates item stock levels during SO creation. The script runs a check each time an item is added to the SO, comparing the ordered quantity with the available stock at the selected location. If there is insufficient stock, the script alerts the user with a custom message, such as, “Insufficient stock for Widget A. Please adjust the quantity or remove the item,” and prevents the SO from being created. This real-time validation enhances user experience by reducing stock errors and aligns order commitments with inventory.

/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 */
define(['N/record', 'N/search', 'N/ui/dialog'], function(record, search, dialog) {


    function validateLine(context) {
        if (context.sublistId === 'item') {
            var currentRecord = context.currentRecord;
            var itemId = currentRecord.getCurrentSublistValue({
                sublistId: 'item',
                fieldId: 'item'
            });
            var locationId = currentRecord.getValue('location');
            var orderedQty = currentRecord.getCurrentSublistValue({
                sublistId: 'item',
                fieldId: 'quantity'
            });


            if (!locationId || !itemId) return true;


            var stockAvailable = checkStockAvailability(itemId, locationId);


            if (stockAvailable < orderedQty) {
                dialog.alert({
                    title: 'Insufficient Stock',
                    message: `Insufficient stock for this item. Available: ${stockAvailable}, Ordered: ${orderedQty}. Please adjust the quantity or remove the item.`
                });
                return false;
            }
        }
        return true;
    }


    function checkStockAvailability(itemId, locationId) {
        var itemSearch = search.create({
            type: 'item',
            filters: [
                ['internalid', 'is', itemId],
                'AND',
                ['inventorylocation', 'is', locationId]
            ],
            columns: ['locationquantityavailable']
        });


        var availableQty = 0;
        itemSearch.run().each(function(result) {
            availableQty = parseInt(result.getValue('locationquantityavailable'), 10) || 0;
            return true;
        });


        return availableQty;
    }


    return {
        validateLine: validateLine
    };
});


Leave a comment

Your email address will not be published. Required fields are marked *