How to Block Creting Transfer Order when the items are already used in Sales Order

Scenario

How to block the creation of Transfer orders if the items are already used to create a sales order and these items are not committed

Solution

/**
 * @NApiVersion 2.1
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */
/*************************************************************************************************************************
 * CLIENTNAME:Airport Home Appliance
 * AHAP-1505 Blocking Decommit in Transfer Orders
 
 * **********************************************************************************************************************
 * Author: Aswathy, Jobin & Jismi IT Services LLP
 * Date created : 06/09/2023
 * Script Description : This Script used to block the creation of transfer order if there is no enough quantities.
 *
 * REVISION HISTORY
 *
 * Revision 1.0 ${06/09/2023} created
 * 
 *
 **************************************************************************************************************************/
define(['N/search'],
    /**
     * @param{search} search
     */
    function (search) {

        /**
         * Function for check for parameters
         * @param {} parameter 
         * @returns {boolean}
         */
        const checkForParameter = function checkForParameter(parameter) {

            try {
                if (parameter !== "" && parameter !== null && parameter !== undefined && parameter !== false && parameter !== "null" && parameter !== "undefined" && parameter !== " " && parameter !== 'false') {
                    return true;
                }
                else {
                    return false;
                }
            }
            catch (err) {
                console.log("error@checkForParameter", err)
                return false;
            }
        }

        /**
         * Function to get the Quantity data from the item record.
         * @param {*} fromLocation 
         * @param {*} lineItem 
         * @returns [{*}]
         */
        function searchQuantityDetails(fromLocation, lineItem) {
            try {
                let inventoryitemSearchObj = search.create({
                    type: "inventoryitem",
                    filters:
                        [
                            ["type", "anyof", "InvtPart"],
                            "AND",
                            ["internalid", "anyof", lineItem],
                            "AND",
                            ["inventorylocation", "anyof", fromLocation]
                        ],
                    columns:
                        [
                            search.createColumn({ name: "inventorylocation", label: "Inventory Location" }),
                            search.createColumn({ name: "locationquantitycommitted", label: "Location Committed" }),
                            search.createColumn({ name: "locationquantityavailable", label: "Location Available" }),
                            search.createColumn({ name: "locationquantitybackordered", label: "Location Back Ordered" }),
                            search.createColumn({ name: "internalid", label: "Internal ID" }),
                            search.createColumn({
                                name: "itemid",
                                sort: search.Sort.ASC,
                                label: "Name"
                            })
                        ]
                });
                let searchResultCount = inventoryitemSearchObj.runPaged().count;
                let itemDataArray = [];
                if (searchResultCount > 0) {
                    inventoryitemSearchObj.run().each(function (result) {
                        let itemObj = {};
                        itemObj.itemId = result.getValue({
                            name: "internalid", label: "Internal ID"
                        });
                        itemObj.location = result.getValue({
                            name: "inventorylocation", label: "Inventory Location"
                        });
                        itemObj.commitedQuantity = result.getValue({
                            name: "locationquantitycommitted", label: "Location Committed"
                        });
                        itemObj.availableQuantity = result.getValue({
                            name: "locationquantityavailable", label: "Location Available"
                        });
                        itemObj.backorderdQuantity = result.getValue({
                            name: "locationquantitybackordered", label: "Location Back Ordered"
                        });
                        itemObj.itemName = result.getValue({
                            name: "itemid",
                            sort: search.Sort.ASC,
                            label: "Name"
                        });
                        itemDataArray.push(itemObj);
                        return true;
                    });

                    return itemDataArray;
                }
                else {
                    return [];
                }

            }
            catch (err) {
                console.log("error@searchQuantityDetails", err)
                return [];
            }
        }

        /**
         * Validation function to be executed when sublist line is committed.
         *
         * @param {Object} scriptContext
         * @param {Record} scriptContext.currentRecord - Current form record
         * @param {string} scriptContext.sublistId - Sublist name
         *
         * @returns {boolean} Return true if sublist line is valid
         *
         * @since 2015.2
         */
        function validateLine(scriptContext) {

            try {
                let currentRec = scriptContext.currentRecord;
                let status = currentRec.getValue({
                    fieldId: 'orderstatus'
                });
                if (status == "B" || status == "A") {

                    let fromLocation = currentRec.getValue({
                        fieldId: 'location'
                    });
                    if (scriptContext.sublistId === 'item') {
                        let lineItem = currentRec.getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'item'
                        });
                        let lineQuantity = currentRec.getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantity'
                        });

                        if (checkForParameter(lineItem) && checkForParameter(fromLocation)) {

                            let itemData = searchQuantityDetails(fromLocation, lineItem);
                            let quntityBackorderd = Number(itemData[0].backorderdQuantity);
                            let quantityAvailable = Number(itemData[0].availableQuantity);
                            let quantityRemaining = quantityAvailable - quntityBackorderd;
                            if (quantityAvailable == 0) {
                                let message = "You do not have the permission to add the items since there are only " + quantityAvailable + " available quantities in the selected location.";
                                alert(message);
                                return false;
                            }
                            if (checkForParameter(quantityAvailable) && checkForParameter(quantityRemaining)) {
                                if (quantityAvailable > 0 && (lineQuantity > quantityRemaining)) {
                                    let message = "You do not have the permission to add the items since there are only " + quantityRemaining + " available quantities in the selected location.";
                                    alert(message);
                                    return false;
                                }


                            }

                        }

                    }
                }

                return true;
            }
            catch (err) {
                console.log("error@ValidateLine", err)
                return true;
            }

        }

        /**
         * Validation function to be executed when record is saved.
         *
         * @param {Object} scriptContext
         * @param {Record} scriptContext.currentRecord - Current form record
         * @returns {boolean} Return true if record is valid
         *
         * @since 2015.2
         */
        function saveRecord(scriptContext) {

            try {
                let currentRec = scriptContext.currentRecord;
                let status = currentRec.getValue({
                    fieldId: 'orderstatus'
                });
                if (status == "B" || status == "A") {
                    let fromLocation = currentRec.getValue({
                        fieldId: 'location'
                    });
                    let lineCount = currentRec.getLineCount({
                        sublistId: 'item'
                    });

                    let newFlag = 0;
                    let itemArray = [];
                    for (let i = 0; i < lineCount; i++) {
                        let items = currentRec.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'item',
                            line: i
                        });
                        itemArray.push(items);
                    }
                    let quantityObject = {};
                    let messageObj = {};
                    if (itemArray.length > 0) {
                        let itemData = searchQuantityDetails(fromLocation, itemArray);
                        if (itemData.length > 0) {
                            for (let i = 0; i < lineCount; i++) {

                                let lineItem = currentRec.getSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'item',
                                    line: i
                                });
                                let quantity = currentRec.getSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'quantity',
                                    line: i
                                });

                                if (!quantityObject.hasOwnProperty(lineItem)) {
                                    quantityObject[lineItem] = Number(quantity);
                                }
                                else {
                                    let temp = Number(quantityObject[lineItem]) + Number(quantity)
                                    quantityObject[lineItem] = temp;
                                }

                                for (let j = 0; j < itemData.length; j++) {
                                    let quantityRemaining;
                                    if (lineItem == itemData[j].itemId) {
                                        let quntityBackorderd = Number(itemData[j].backorderdQuantity);
                                        let quantityAvailable = Number(itemData[j].availableQuantity);
                                        quantityRemaining = quantityAvailable - quntityBackorderd;
                                        if (quantityObject[itemData[j].itemId] > quantityRemaining) {
                                            newFlag = newFlag + 1;
                                            let msgObj = {};
                                            msgObj.itemName = itemData[j].itemName;
                                            msgObj.quantity = quantityRemaining;
                                            messageObj[lineItem] = msgObj;
                                        }

                                    }
                                }
                            }

                            if (newFlag > 0) {
                                let data = ""
                                let quantity
                                for (let key in messageObj) {
                                    if(messageObj[key].quantity < 0){
                                    quantity = 0 
                                    }
                                    else
                                    {
                                        quantity = messageObj[key].quantity
                                    }

                                    data = data + '\n' + "Item Name: " + messageObj[key].itemName + " Available Quantity: " + quantity
                                   
                                }
                                let message = "Please refer the available quantities to create the transfer order for the selected location. " + '\n' + data
                                alert(message)
                                return false
                            }

                        }

                    }

                }

                return true
            }
            catch (err) {
                console.log("error@saveRecord", err)
                return false
            }

        }

        return {

            validateLine: validateLine,
            saveRecord: saveRecord
        };

    });

Leave a comment

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