Restricting IR Creation when there is overage for multiple IR’s for a single SO regarding MPQ or else with Tolerance Rate.

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 */

'use strict',
    define(['N/currentRecord', 'N/record', 'N/search', 'N/runtime', 'N/error'],
        /**
         * @param{currentRecord} currentRecord
         * @param{record} record
         */
        function (currentRecord, record, search, runtime, error) {
            /**
             * Function definition to be triggered before record is loaded.
             *
             * @param {Object} scriptContext
             * @param {Record} scriptContext.newRecord - New record
             * @param {Record} scriptContext.oldRecord - Old record
             * @param {string} scriptContext.type - Trigger type
             * @Since 2015.2
             */
            /**
             * @Description Declared Tolerance rate as Global Variable
             * @type {number}
             */
            var TOLERANCERATE = 0.05;
            function beforeSubmit(scriptContext) {
                /**
                 * @Description Create Mode Only.
                 */
                if (scriptContext.type == 'create') {
                    var irRec = scriptContext.newRecord;
                    var poInternalID = irRec.getValue({
                        fieldId: 'createdfrom'
                    })
                    log.debug("PO Int ID", poInternalID);
                    // checks created from any purchase order
                    if (poInternalID) {
                        //search.lookup.. des..getting po type
                        /**
                         * @Description Saved Search for Order Type
                         * @type {Search}
                         */
                        var transactionSearchObj = search.create({
                            type: "transaction",
                            filters:
                                [
                                    ["internalid", "anyof", poInternalID],
                                    "AND",
                                    ["mainline", "is", "T"]
                                ],
                            columns:
                                [
                                    search.createColumn({name: "type", label: "Type"})
                                ]
                        });
                        var searchResultCount = transactionSearchObj.runPaged().count;
                        log.debug("transactionSearchObj result count", searchResultCount);
                        var createdFrom;
                        transactionSearchObj.run().each(function (result) {
                            createdFrom = result.getValue({
                                name: "type",
                                label: "Type"
                            });
                            return true;
                        });
                        log.debug('created From', createdFrom)
                    }
                    /**
                     * @Description Saved Search for PO Details and should be from PO only
                     */
                    if (createdFrom == "PurchOrd") {
                        var purchaseorderSearchObj = search.create({
                            type: "purchaseorder",
                            filters:
                                [
                                    ["internalidnumber","equalto",poInternalID],
                                    "AND",
                                    ["taxline","is","F"],
                                    "AND",
                                    ["mainline","is","F"],
                                    "AND",
                                    ["shipping","is","F"],
                                    "AND",
                                    ["type","anyof","PurchOrd"],
                                    "AND",
                                    ["quantity","notlessthan","0"],
                                    "AND",
                                    ["amount","notlessthan","0.00"]
                                ],
                            columns:
                                [
                                    search.createColumn({
                                        name: "custitem15",
                                        join: "item",
                                        summary: "GROUP",
                                        label: "Minimum Purchase Quantity"
                                    }),
                                    search.createColumn({
                                        name: "quantity",
                                        summary: "GROUP",
                                        label: "Quantity"
                                    }),
                                    search.createColumn({
                                        name: "line",
                                        summary: "SUM",
                                        sort: search.Sort.ASC,
                                        label: "Line ID"
                                    }),
                                    search.createColumn({
                                        name: "quantityuom",
                                        summary: "GROUP",
                                        label: "Quantity in Transaction Units"
                                    }),
                                    search.createColumn({
                                        name: "quantityshiprecv",
                                        summary: "GROUP",
                                        label: "Quantity Fulfilled/Received"
                                    }),
                                    search.createColumn({
                                        name: "item",
                                        summary: "GROUP",
                                        label: "Item"
                                    })
                                ]
                        });
                        log.debug("purchaseorderSearchObj", purchaseorderSearchObj);
                        var srchRes = purchaseorderSearchObj.run().getRange(0, 1000);
                        log.debug("purchaseorderSearchObj result count", srchRes);
                        /**
                         * Description
                         * Declared two objects
                         * @type {{}}
                         */
                        var resultArray1 = {};
                        var resultArray2 = {};
                        /**
                         * @Description Looping MPQ Values if MPQ grater than Zero
                         */
                        for (var i = 0; i < srchRes.length; i++) {
                            var conMPQ = srchRes[i].getValue(srchRes[i].columns[0]);
                            log.debug("conMPQ", conMPQ);
                            if (conMPQ > 0) {
                                var poLineno = srchRes[i].getValue(srchRes[i].columns[2]);
                                log.debug("poLineno", poLineno);
                                var mpq = srchRes[i].getValue(srchRes[i].columns[0]);
                                log.debug("MPQ", mpq);
                                var qty = srchRes[i].getValue(srchRes[i].columns[1]);
                                log.debug("PO Qty", qty);
                                var qtyInTranUnit = srchRes[i].getValue(srchRes[i].columns[3]);
                                log.debug("qtyInTranUnit", qtyInTranUnit);
                                var qtyShipRecev = srchRes[i].getValue(srchRes[i].columns[4]);
                                log.debug("qtyShipRecev", qtyShipRecev);
                                var mulitiplier = Math.ceil(qtyInTranUnit / mpq);
                                log.debug("mulitiplier", mulitiplier);
                                var calMpqValue = (mulitiplier) * (mpq);
                                log.debug("calMpqValue", calMpqValue);
                                var tolerantQty = (calMpqValue) - (qtyShipRecev);
                                log.debug("Final MPQ Formula For Mult IRs", tolerantQty);
                                resultArray1[poLineno] = tolerantQty;
                                log.debug(" resultArray1[poLineno]", resultArray1[poLineno]);
                            } else {
                                /**
                                 * @Description Looping MPQ Values if Tolerance values
                                 */
                                var poLineno = srchRes[i].getValue(srchRes[i].columns[2]);
                                log.debug("poLineno", poLineno);
                                var qty = srchRes[i].getValue(srchRes[i].columns[1]);
                                log.debug("PO Qty", qty);
                                var qtyInTranUnit = srchRes[i].getValue(srchRes[i].columns[3]);
                                log.debug("qtyInTranUnit", qtyInTranUnit);
                                var qtyShipRecev = srchRes[i].getValue(srchRes[i].columns[4]);
                                log.debug("qtyShipRecev", qtyShipRecev);
                                var tolrance = (qtyInTranUnit) * (TOLERANCERATE);
                                log.debug("Tolerance", tolrance);
                                var calTol = Number(tolrance) + Number(qty);
                                log.debug("calTol", calTol);
                                var tolerantQty = Number(calTol) - Number(qtyShipRecev);
                                log.debug("Final Tolrance Formula For Mult IRs", tolerantQty);
                                resultArray2[poLineno] = tolerantQty;
                                log.debug(" resultArray2[poLineno]", resultArray2[poLineno]);
                            }
                        }
                        log.debug("resultArray1", resultArray1);
                        log.debug("resultArray2", resultArray2);
                        var irLineCount = irRec.getLineCount({
                            sublistId: 'item'
                        });
                        log.debug("irLineCount", irLineCount);
                        /**
                         * @Description resultArray1 works with MPQ value
                         */
                        for (var key in resultArray1) {
                            var valuesArr = resultArray1[key]
                            log.debug("valuesArr", valuesArr);
                            var flag = 0;
                            for (var x = 0; x < irLineCount; x++) {
                                var itemRecieve = irRec.getSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'itemreceive',
                                    line: x
                                });
                                if (itemRecieve == true) {
                                    var orderLine = irRec.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'orderline',
                                        line: x
                                    });
                                    log.debug("orderLine", orderLine)
                                    var Qty = irRec.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'quantity',
                                        line: x
                                    });
                                    log.debug("IF Qty", Qty)
                                    // for (var i = 0; i < valuesArr.length; i++) {
                                    var poLineID = key
                                    log.debug("poLineID", poLineID);
                                    log.debug("IF order line", orderLine);
                                    if (poLineID == orderLine) {
                                        var qtytolerance = resultArray1[key]
                                        log.debug("qtytolerance", qtytolerance);
                                        if (Number(Qty) > Number(qtytolerance)) {
                                            flag = 1;
                                            log.debug("enterd main condition");
                                            var UEcustom_error = error.create({
                                                name: 'ITEM QUANTITY REACHED ITS MAXIMUM LIMIT',
                                                message: 'ITEM QUANTITY REACHED ITS MAXIMUM LIMIT:<BR/> <BR/>Not allowed to receive items of quantity more than Minimum Purchase Quantity of the related Purchase order items and receiving is restricted to ordered quantity.',
                                                notifyOff: true
                                            });
                                            throw UEcustom_error.message;
                                            return false;
                                        }
                                    }
                                }
                            }
                        }
                        /**
                         * @Description resultArray2 works with Tolerance Rate
                         */
                        for (var key in resultArray2) {
                            var valuesArr = resultArray2[key]
                            log.debug("valuesArr", valuesArr);
                            var flag = 0;
                            for (var x = 0; x < irLineCount; x++) {
                                var itemRecieve = irRec.getSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'itemreceive',
                                    line: x
                                });
                                if (itemRecieve == true) {
                                    var orderLine = irRec.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'orderline',
                                        line: x
                                    });
                                    log.debug("orderLine", orderLine)
                                    var Qty = irRec.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'quantity',
                                        line: x
                                    });
                                    log.debug("IF Qty", Qty)
                                    // for (var i = 0; i < valuesArr.length; i++) {
                                    var poLineID = key
                                    log.debug("poLineID", poLineID);
                                    log.debug("IF order line", orderLine);
                                    if (poLineID == orderLine) {
                                        var qtytolerance = resultArray2[key]
                                        log.debug("qtytolerance", qtytolerance);
                                        if (Number(Qty) > Number(qtytolerance)) {
                                            flag = 1;
                                            log.debug("enterd main condition");
                                            var UEcustom_error = error.create({
                                                name: 'ITEM QUANTITY REACHED ITS MAXIMUM LIMIT',
                                                message: 'ITEM QUANTITY REACHED ITS MAXIMUM LIMIT:<BR/> <BR/>Not allowed to receive items of quantity more than 5% of the related Purchase order items and receiving is restricted to ordered quantity.',
                                                notifyOff: true
                                            });
                                            throw UEcustom_error.message;
                                            return false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                /**
                 * @Description Edit Mode Only
                 */
                if (scriptContext.type === 'edit') {
                    var irRec = scriptContext.newRecord;
                    var poInternalID = irRec.getValue({
                        fieldId: 'createdfrom'
                    })
                    log.debug("PO Int ID", poInternalID);
                    // checks created from any purchase order
                    if (poInternalID) {
                        //search.lookup.. des..getting po type
                        /**
                         * @Description Saved Search for Order Type
                         * @type {Search}
                         */
                        var transactionSearchObj = search.create({
                            type: "transaction",
                            filters:
                                [
                                    ["internalid", "anyof", poInternalID],
                                    "AND",
                                    ["mainline", "is", "T"]
                                ],
                            columns:
                                [
                                    search.createColumn({name: "type", label: "Type"})
                                ]
                        });
                        var searchResultCount = transactionSearchObj.runPaged().count;
                        log.debug("transactionSearchObj result count", searchResultCount);
                        var createdFrom;
                        transactionSearchObj.run().each(function (result) {
                            createdFrom = result.getValue({
                                name: "type",
                                label: "Type"
                            });
                            return true;
                        });
                        log.debug('created From', createdFrom)
                    }
                    /**
                     * @Description Saved Search for PO Details and should be from PO only
                     */
                    if (createdFrom == "PurchOrd") {
                        var purchaseorderSearchObj = search.create({
                            type: "purchaseorder",
                            filters:
                                [
                                    ["internalidnumber", "equalto", poInternalID],
                                    "AND",
                                    ["taxline", "is", "F"],
                                    "AND",
                                    ["mainline", "is", "F"],
                                    "AND",
                                    ["shipping", "is", "F"],
                                    "AND",
                                    ["type", "anyof", "PurchOrd"],
                                    "AND",
                                    ["quantity", "notlessthan", "0"],
                                    "AND",
                                    ["amount", "notlessthan", "0.00"]
                                ],
                            columns:
                                [
                                    search.createColumn({
                                        name: "custitem15",
                                        join: "item",
                                        summary: "GROUP",
                                        label: "Minimum Purchase Quantity"
                                    }),
                                    search.createColumn({
                                        name: "quantity",
                                        summary: "GROUP",
                                        label: "Quantity"
                                    }),
                                    search.createColumn({
                                        name: "line",
                                        summary: "SUM",
                                        sort: search.Sort.ASC,
                                        label: "Line ID"
                                    }),
                                    search.createColumn({
                                        name: "quantityuom",
                                        summary: "GROUP",
                                        label: "Quantity in Transaction Units"
                                    }),
                                    search.createColumn({
                                        name: "quantityshiprecv",
                                        summary: "GROUP",
                                        label: "Quantity Fulfilled/Received"
                                    }),
                                    search.createColumn({
                                        name: "item",
                                        summary: "GROUP",
                                        label: "Item"
                                    })
                                ]
                        });
                        log.debug("purchaseorderSearchObj", purchaseorderSearchObj);
                        var srchRes = purchaseorderSearchObj.run().getRange(0, 1000);
                        log.debug("purchaseorderSearchObj result count", srchRes);
                        /**
                         * Description
                         * Declared two objects
                         * @type {{}}
                         */
                        var resultArray1 = {};
                        var resultArray2 = {};
                        for (var i = 0; i < srchRes.length; i++) {
                            var conMPQ = srchRes[i].getValue(srchRes[i].columns[0]);
                            log.debug("conMPQ", conMPQ);
                            /**
                             * @Description Looping MPQ Values if MPQ grater than Zero
                             */
                            if (conMPQ > 0) {
                                var poLineno = srchRes[i].getValue(srchRes[i].columns[2]);
                                log.debug("poLineno", poLineno);
                                var mpq = srchRes[i].getValue(srchRes[i].columns[0]);
                                log.debug("MPQ", mpq);
                                var qty = srchRes[i].getValue(srchRes[i].columns[1]);
                                log.debug("PO Qty", qty);
                                var qtyInTranUnit = srchRes[i].getValue(srchRes[i].columns[3]);
                                log.debug("qtyInTranUnit", qtyInTranUnit);
                                var qtyShipRecev = srchRes[i].getValue(srchRes[i].columns[4]);
                                log.debug("qtyShipRecev", qtyShipRecev);
                                var mulitiplier = Math.ceil(qtyInTranUnit / mpq);
                                log.debug("mulitiplier", mulitiplier);
                                var calMpqValue = (mulitiplier) * (mpq);
                                log.debug("calMpqValue", calMpqValue);
                                var tolerantQty = (calMpqValue) - (qtyShipRecev);
                                log.debug("MPQ Formula For Mult IRs", tolerantQty);
                                resultArray1[poLineno] = tolerantQty;
                                log.debug(" resultArray1[poLineno]", resultArray1[poLineno]);
                            } else {
                                /**
                                 * @Description Looping Tolerance Values
                                 */
                                var poLineno = srchRes[i].getValue(srchRes[i].columns[2]);
                                log.debug("poLineno", poLineno);
                                var qty = srchRes[i].getValue(srchRes[i].columns[1]);
                                log.debug("PO Qty", qty);
                                var qtyInTranUnit = srchRes[i].getValue(srchRes[i].columns[3]);
                                log.debug("qtyInTranUnit", qtyInTranUnit);
                                var qtyShipRecev = srchRes[i].getValue(srchRes[i].columns[4]);
                                log.debug("qtyShipRecev", qtyShipRecev);
                                var tolrance = (qtyInTranUnit) * (TOLERANCERATE);
                                log.debug("Tolerance", tolrance);
                                var calTol = Number(tolrance) + Number(qty);
                                log.debug("calTol", calTol);
                                var tolerantQty = Number(calTol) - Number(qtyShipRecev);
                                log.debug("MPQ Formula For Mult IRs", tolerantQty);
                                resultArray2[poLineno] = tolerantQty;
                                log.debug(" resultArray2[poLineno]", resultArray2[poLineno]);
                            }
                        }
                        log.debug("resultArray1", resultArray1);
                        log.debug("resultArray2", resultArray2);
                        var irLineCount = irRec.getLineCount({
                            sublistId: 'item'
                        });
                        log.debug("irLineCount", irLineCount);
                        /**
                         * @Description resultArray1 works with MPQ value
                         */
                        for (var key in resultArray1) {
                            var valuesArr = resultArray1[key]
                            log.debug("valuesArr", valuesArr);
                            var flag = 0;
                            for (var x = 0; x < irLineCount; x++) {
                                var itemRecieve = irRec.getSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'itemreceive',
                                    line: x
                                });
                                if (itemRecieve == true) {
                                    var orderLine = irRec.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'orderline',
                                        line: x
                                    });
                                    log.debug("orderLine", orderLine)
                                    var Qty = irRec.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'quantity',
                                        line: x
                                    });
                                    log.debug("IF Qty", Qty)
                                    var oldQty = irRec.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'custcol_jj_ir_old_item_qty',
                                        line: x
                                    });
                                    log.debug("IF oldQty", oldQty)
                                    // for (var i = 0; i < valuesArr.length; i++) {
                                    var poLineID = key
                                    log.debug("poLineID", poLineID);
                                    log.debug("IF order line", orderLine);
                                    if (poLineID == orderLine) {
                                        var qtytolerance = resultArray1[key]
                                        log.debug("qtytolerance", qtytolerance);
                                        var sum = Number(qtytolerance) + Number(oldQty)
                                        log.debug("sum", sum)
                                        var roundedsum = sum.toFixed(5).replace(/\d(?=(\d{3})+\.)/g, '$&,');
                                        log.debug("sum", roundedsum)
                                        log.debug("tpeof sum", typeof (roundedsum))
                                        var introundedsum = Number(roundedsum)
                                        log.debug("sum", introundedsum)
                                        log.debug("tpeof sum", typeof (introundedsum))
                                        if (Number(Qty) > (Number(qtytolerance) + Number(oldQty))) {
                                            flag = 1;
                                            log.debug("enterd main condition");
                                            var UEcustom_error = error.create({
                                                name: 'ITEM QUANTITY REACHED ITS MAXIMUM LIMIT',
                                                message: 'ITEM QUANTITY REACHED ITS MAXIMUM LIMIT:<BR/> <BR/>Not allowed to receive items of quantity more than Minimum Purchase Quantity of the related Purchase order items and receiving is restricted to ordered quantity.',
                                                notifyOff: true
                                            });
                                            throw UEcustom_error.message;
                                            return false;
                                        }
                                    }
                                }
                            }
                        }
                        /**
                         * @Description resultArray2 works with Tolerance Rate
                         */
                        for (var key in resultArray2) {
                            var valuesArr = resultArray2[key]
                            log.debug("valuesArr", valuesArr);
                            var flag = 0;
                            for (var x = 0; x < irLineCount; x++) {
                                var itemRecieve = irRec.getSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'itemreceive',
                                    line: x
                                });
                                if (itemRecieve == true) {
                                    var orderLine = irRec.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'orderline',
                                        line: x
                                    });
                                    log.debug("orderLine", orderLine)

                                    var Qty = irRec.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'quantity',
                                        line: x
                                    });
                                    log.debug("IF Qty", Qty)
                                    var oldQty = irRec.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'custcol_jj_ir_old_item_qty',
                                        line: x
                                    });
                                    log.debug("IF oldQty", oldQty)
                                    // for (var i = 0; i < valuesArr.length; i++) {
                                    var poLineID = key
                                    log.debug("poLineID", poLineID);
                                    log.debug("IF order line", orderLine);
                                    if (poLineID == orderLine) {
                                        var qtytolerance = resultArray2[key]
                                        log.debug("qtytolerance", qtytolerance);
                                        var sum = Number(qtytolerance) + Number(oldQty)
                                        log.debug("sum", sum)
                                        var roundedsum = sum.toFixed(5).replace(/\d(?=(\d{3})+\.)/g, '$&,');
                                        log.debug("sum", roundedsum)
                                        log.debug("tpeof sum", typeof (roundedsum))
                                        var introundedsum = Number(roundedsum)
                                        log.debug("sum", introundedsum)
                                        log.debug("tpeof sum", typeof (introundedsum))
                                        if (Number(Qty) > (Number(qtytolerance) + Number(oldQty))) {
                                            flag = 1;
                                            log.debug("enterd main condition");
                                            var UEcustom_error = error.create({
                                                name: 'ITEM QUANTITY REACHED ITS MAXIMUM LIMIT',
                                                message: 'ITEM QUANTITY REACHED ITS MAXIMUM LIMIT:<BR/> <BR/>Not allowed to receive items of quantity more than 5% of the related Purchase order items and receiving is restricted to ordered quantity.',
                                                notifyOff: true
                                            });
                                            throw UEcustom_error.message;
                                            return false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return {
                beforeSubmit: beforeSubmit
            };
        });
Avatar photo

By Nandesh

I’m a Junior Software Engineer in Kerala, a Graduate with a passion for computer science, and electrical engineering.

Leave a comment

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