Client-side actions: Quotation

Jira code: UMAR 44,47,85,130,93

The different actions that performed in this client script are, 1) Setting discount, packing, freight based on item line for GL impact 2) Recalculating different custom fields in the quotation, when item line changes 3) Open an email widget in quotation button click. 4) Checking the profit on the save action 5) Validating field in item line.

/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */

/**
 * Script Description: This script defining the function of button  
 * edited for discount percentage post souring
 */

/*******************************************************************************
 * * UMAR WSR * *
 * **************************************************************************
 * Date:13/2/18 
 * Script name: NetU CS Quote Btn Action
 * Script id: customscript_netu_cs_quote_btnaction
 * Deployment id: customdeploy_netu_cs_quote_btnaction
 * Applied to: Quotation
 * Revised on 21/4/18 for setting disc,pack,freight based on item line (not completed)
 * Revised on 23/4/18 for setting disc,pack,freight based on item line for gl impact
 * edited for the principal location...not complete
 * Revised on 10/5/18 for recalculating cost values in item line changes.
 * Revised on 15/5/18 for packing,freight,discount setting on save
 * Revised on 30/5/18 for open an email widget in quotation button click.
 * Revised on 1/6/18 for setting new condition for profit
 * Revised on 15/6/18 for Improving performance and validating customer second reference.
 * Revised on 28/6/18 for unit price field change
 * new correct code 30/8/18 with increased performance(eg:costChngSaveflag)
 * doing commission change by user(7-9-18)
 * b4 discount change(up)
 

 ******************************************************************************/

define(['N/currentRecord', 'N/record', 'N/runtime', 'N/search', 'N/url', 'N/ui/dialog', 'N/https'],

    function(currentRecord, record, runtime, search, url, dialog, https) {

        /**
         * Function to be executed after page is initialized.
         *
         * @param {Object} scriptContext
         * @param {Record} scriptContext.currentRecord - Current form record
         * @param {string} scriptContext.mode - The mode in which the record is being accessed (create, copy, or edit)
         *
         * @since 2015.2
         */

        function checkif(singleitem) {

            if (singleitem == "" || singleitem == null || singleitem == undefined || isNaN(singleitem) == true) {
                return 0;
            } else {
                return singleitem;
            }
        }

        function checkForParameter(parameter) {
            if (parameter != "" && parameter != null && parameter != undefined && parameter != "undefined" && parameter != " ") {
                return true;
            } else {
                return false;
            }
        }

        var costChngSaveflag = 1;
        var discAmntChngflag; //if discount amount changed by user
        var custpercentage = 0;
        var priceFlag = null;
        var refFlag = null;
        var rateFlag = null;
        var vendorAlert = 0; //if location is not defined for the vendor in vendor record
        var mainAlert = 0; //if location is not defined in the record
        var fixCommiAlert = 0; //fixed commission is not defined for the vendor
        var sacleCommiAlert = 0; //scale commission is not defined for the vendor
        var deliveryChange = 0;
        var commiFlag = 0; //scale commission is not defined from a specific range.

        function pageInit(scriptContext) {
            try {
               
                var currentReco = scriptContext.currentRecord;
                costChngSaveflag = 0;

                //getting the current exchange rate
                var exRate = currentReco.getValue({
                    fieldId: 'exchangerate'
                });

                var gross_amnt_base = currentReco.getValue({
                    fieldId: 'custbody_netu_cost_gross_amount_base'
                });
                //gross amount base will be null at the time of creation
                if ((gross_amnt_base == "") || (gross_amnt_base == null) || (gross_amnt_base == undefined)) {
                    //setting cost and sales base values
                    var fields = ['custbody_netu_cost_gross_amount', 'custbody_netu_cost_discount_amount', 'custbody_netu_cost_commission_amount',
                        'custbody_netu_cost_net_amount', 'custbody_netu_v_packing_charges', 'custbody_netu_v_freight', 'custbody_netu_cost_net_amnt_charges',
                        'custbody_netu_sales_gross_amount', 'custbody_netu_sales_discount_amount', 'custbody_netu_sales_net_amount',
                        'custbody_netu_packing_charges', 'custbody_netu_freight', 'custbody_netu_sales_net_amnt_charges'
                    ];

                    var setFields = ['custbody_netu_cost_gross_amount_base', 'custbody_netu_cost_discount_amount_b', 'custbody_netu_cost_commission_amount_b',
                        'custbody_netu_cost_net_amount_b', 'custbody_netu_v_packing_charges_b', 'custbody_netu_v_freight_b', 'custbody_netu_cost_net_amnt_charges_b',
                        'custbody_netu_sales_gross_amount_b', 'custbody_netu_sales_discount_amount_b', 'custbody_netu_sales_net_amount_b',
                        'custbody_netu_packing_charges_b', 'custbody_netu_freight_b', 'custbody_netu_sales_net_amnt_charges_b'
                    ];

                    for (var i = 0; i < 13; i++) {
                        var value = currentReco.getValue({
                            fieldId: fields[i]
                        });
                        value = checkif(value);

                        var setvalue = parseFloat(value) * parseFloat(exRate);
                        setvalue = parseFloat(setvalue).toFixed(2);

                        currentReco.setValue({
                            fieldId: setFields[i],
                            value: setvalue
                        });
                    }
                } else {

                    var countt = currentReco.getLineCount({
                        sublistId: 'item'
                    });

                    //removing the lines packing,freight,discount
                    for (var k = countt - 1; k >= 0; k--) {
                        var itemidIncomee = currentReco.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_incomeid',
                            line: k
                        });
                        if ((itemidIncomee == 1) || (itemidIncomee == 2) || (itemidIncomee == 3)) {
                            currentReco.removeLine({
                                sublistId: 'item',
                                line: k,
                                ignoreRecalc: true
                            });
                        }
                    }

                }
                
                //when removing an item line
                jQuery("#item_remove").click(function() {
                    var itemid = currentReco.getCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_item_id'
                    });

                    var lineNum = currentReco.getLineCount({
                        sublistId: 'item'
                    });

                    var removeList = getRemoveList(currentReco);

                    var id = removeList[0];
                    var itemId = parseInt(id);
                    var removeListLength = removeList.length;
                    for (var i = 0; i < removeListLength; i++) {
                        //find line number of additional/free item to be removed
                        var trueLineNumber = currentReco.findSublistLineWithValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_item_id',
                            value: removeList[i]
                        });
                        // remove line
                        if (trueLineNumber > -1) {
                            currentReco.removeLine({
                                sublistId: 'item',
                                line: trueLineNumber,
                                ignoreRecalc: true
                            });
                        }
                    }

                    var actualPrice = [],
                        options = [],
                        actPrice, ItemId, k = 0,
                        countOflines = 0;

                    for (var i = 0; i < lineNum - 1; i++) {
                        ItemId = currentReco.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_item_id',
                            line: i
                        });
                        // to get the option of each  items
                        options[i] = currentReco.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_optional_addi_free',
                            line: i
                        });
                        if ((ItemId.startsWith(itemId)) && ((options[i] == 'Optional') || (options[i] == "Normal"))) {
                            // to get the actual price of each optional items
                            actPrice = currentReco.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'custcol_netu_actual_cost_price',
                                line: i
                            });
                            actualPrice.push(actPrice);

                        }

                        // to get the min  actual price 
                    }
                    console.log('actualPrice', actualPrice);
                    var minimumActualPrice = actualPrice[0];

                    for (var j = 1; j < lineNum - 1; j++) {
                        if ((minimumActualPrice > actualPrice[j])) {
                            minimumActualPrice = actualPrice[j];
                        }
                    }

                    var atPrice = 0,
                        lineNumber;

                    for (var i = 0; i < lineNum - 1; i++) {
                        ItemId = currentReco.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_item_id',
                            line: i
                        });
                        actPrice = currentReco.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_actual_cost_price',
                            line: i
                        });

                        if ((ItemId.startsWith(itemId)) && (actPrice == minimumActualPrice) && ((options[i] == 'Optional') || (options[i] == "Normal"))) {
                            lineNumber = i;
                        }
                    }


                    var quantity = currentReco.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'quantity',
                        line: lineNumber
                    });

                    // to get the increment & percent
                    var increment = currentReco.getValue({
                        fieldId: 'custbody_netu_increment'
                    });
                    increment = checkif(increment);

                    var percent = currentReco.getValue({
                        fieldId: 'custbody_netu_increment_perc_checkbox'
                    });
                    if (percent) {
                        var incrementper = (parseFloat(minimumActualPrice) * parseFloat(increment)) / 100;
                        increment = incrementper;
                    }

                    var cost_gross = parseFloat(quantity) * parseFloat(minimumActualPrice);
                    var sellingp = parseFloat(increment) + parseFloat(minimumActualPrice);
                    var groosAmnt = parseFloat(sellingp) * parseFloat(quantity);
                   
                    // to select the line
                    currentReco.selectLine({
                        sublistId: 'item',
                        line: lineNumber
                    });
                    // set data
                    currentReco.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_purch_price',
                        value: minimumActualPrice,
                        ignoreFieldChange: true,
                        fireSlavingSync: true
                    });

                    currentReco.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_purch_gross_amount',
                        value: cost_gross,
                        ignoreFieldChange: true,
                        fireSlavingSync: true
                    });

                    // to set the increment
                    currentReco.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_increment',
                        value: increment,
                        ignoreFieldChange: true,
                        fireSlavingSync: true
                    });
                    // percent
                    currentReco.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_increment_percentage ',
                        value: percent,
                        ignoreFieldChange: true,
                        fireSlavingSync: true
                    });

                    currentReco.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'rate',
                        value: sellingp,
                        ignoreFieldChange: true,
                        fireSlavingSync: true
                    });

                    currentReco.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_selling_price',
                        value: sellingp,
                        ignoreFieldChange: true,
                        fireSlavingSync: true
                    });

                    currentReco.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'amount',
                        value: groosAmnt,
                        ignoreFieldChange: true,
                        fireSlavingSync: true
                    });


                    //commit line
                    currentReco.commitLine({
                        sublistId: 'item'
                    });

                });
                costChngSaveflag = 1;


            } catch (e) {
                console.log(e.message);
            }
        }

        /*
         * Function to recalculate all values when delete an itemline
         */

        function sublistChanged(scriptContext) {

            try {

                if (costChngSaveflag != 0 && deliveryChange != 1) {
                    var currentRec = scriptContext.currentRecord;

                    var grossSum = calculateGrossSum(currentRec);
                    grossSum = parseFloat(grossSum).toFixed(2);

                    //setting the sales gross sum
                    currentRec.setValue({
                        fieldId: 'custbody_netu_sales_gross_amount',
                        value: grossSum,
                        ignoreFieldChange: true
                    });

                    salesfields(currentRec, grossSum);
                    salesPackAnddfreight(currentRec);
                    costRecalculation(currentRec);

                    //calculating and setting the profit values
                    var sellingPrice = currentRec.getValue({
                        fieldId: 'custbody_netu_sales_net_amount'
                    });
                    sellingPrice = checkif(sellingPrice);

                    var costPrice = currentRec.getValue({
                        fieldId: 'custbody_netu_cost_net_amount'
                    });
                    costPrice = checkif(costPrice);

                    var profit = parseFloat(sellingPrice) - parseFloat(costPrice);
                    profit = parseFloat(profit).toFixed(2);

                    currentRec.setValue({
                        fieldId: 'custbody_netu_profit_amount',
                        value: profit,
                        ignoreFieldChange: true
                    });


                    var profitPercentage = (profit / parseFloat(sellingPrice)) * 100;
                    profitPercentage = checkif(profitPercentage);
                    var profitPer = parseFloat(profitPercentage).toFixed(2);

                    currentRec.setValue({
                        fieldId: 'custbody_netu_profit_perc',
                        value: profitPer,
                        ignoreFieldChange: true
                    });

                }
            } catch (e) {
                console.log(e.message);
            }

        }


        //checking customer reference and customer second references are already existing in any other records
        function validateField(scriptContext) {

            try {

                if (scriptContext.fieldId == 'custbody_netu_customer_reference') {

                    var currentRecord = scriptContext.currentRecord;

                    var recId = currentRecord.id;

                    var customerRef = currentRecord.getValue({
                        fieldId: 'custbody_netu_customer_reference'
                    });

                    var customerSecdRef = currentRecord.getValue({
                        fieldId: 'custbody_netu_customer_2nd_ref'
                    });
                    customerRef = customerRef.replace(/(^\s*)|(\s*$)/gi, "");
                    customerRef = customerRef.replace(/[ ]{2,}/gi, " ");
                    customerRef = customerRef.replace(/\n /, "\n");

                    if (customerSecdRef == '' || customerSecdRef == null || customerSecdRef == undefined) {} else {
                        if (customerRef.toUpperCase() == customerSecdRef.toUpperCase()) {
                            console.log('customerRef.toUppe' + ',' + customerRef.toUpperCase() + ',' + customerSecdRef.toUpperCase());
                            alert('Customer Reference Already Exists in current record');
                            currentRecord.setValue({
                                fieldId: 'custbody_netu_customer_reference',
                                value: null,
                                ignoreFieldChange: true
                            });
                            return false;
                        }
                    }
                    var customer = currentRecord.getValue({
                        fieldId: 'entity'
                    });

                    var vessel = currentRecord.getValue({
                        fieldId: 'custbody_netu_vessel'
                    });
                    var subjob = currentRecord.getValue({
                        fieldId: 'custbody_netu_subjob'
                    });
                    
                    var mainjobNo = currentRecord.getValue({
                        fieldId: 'custbody_netu_main_job'
                    });


                    var vesselNames = getJobsWithCustomerReference(customerRef, customer, vessel, subjob, recId, mainjobNo);

                    if (vesselNames != '') {

                        alert('Customer Reference Already Exists in ' + vesselNames);

                        currentRecord.setValue({
                            fieldId: 'custbody_netu_customer_reference',
                            value: null,
                            ignoreFieldChange: true
                        });

                        return false;
                    }

                }


                if (scriptContext.fieldId == 'custbody_netu_customer_2nd_ref') {

                    var currentRecord = scriptContext.currentRecord;

                    var recId = currentRecord.id;

                    var customerRefN = currentRecord.getValue({
                        fieldId: 'custbody_netu_customer_reference'
                    });

                    var customerSecdRefN = currentRecord.getValue({
                        fieldId: 'custbody_netu_customer_2nd_ref'
                    });
                    customerSecdRefN = customerSecdRefN.replace(/(^\s*)|(\s*$)/gi, "");
                    customerSecdRefN = customerSecdRefN.replace(/[ ]{2,}/gi, " ");
                    customerSecdRefN = customerSecdRefN.replace(/\n /, "\n");

                    if (customerRefN == '' || customerRefN == null || customerRefN == undefined) {

                    } else {
                        if (customerSecdRefN.toUpperCase() == customerRefN.toUpperCase()) {

                            alert('Customer Reference Already Exists in current record');

                            currentRecord.setValue({
                                fieldId: 'custbody_netu_customer_2nd_ref',
                                value: null,
                                ignoreFieldChange: true
                            });
                            return false;
                        }
                    }
                    var customer = currentRecord.getValue({
                        fieldId: 'entity'
                    });

                    var vessel = currentRecord.getValue({
                        fieldId: 'custbody_netu_vessel'
                    });
                    var subjob = currentRecord.getValue({
                        fieldId: 'custbody_netu_subjob'
                    });
                    var mainjobNo = currentRecord.getValue({
                        fieldId: 'custbody_netu_main_job'
                    });

                    var vesselNames = getJobsWithCustomerReference(customerSecdRefN, customer, vessel, subjob, recId, mainjobNo);

                    if (vesselNames != '') {

                        alert('Customer Reference Already Exists in ' + vesselNames);

                        currentRecord.setValue({
                            fieldId: 'custbody_netu_customer_2nd_ref',
                            value: null,
                            ignoreFieldChange: true
                        });

                        return false;
                    }


                }

                return true;

            } catch (e) {


                console.log(e.message);
            }
        }





        function fieldChanged(scriptContext) {

            try {

                //setting customer percentage if customer changes.
                if (scriptContext.fieldId == 'entity') {
                    try {
                        var currentRec = scriptContext.currentRecord;
                        //finding the discount percentage from customer record.
                        var custId = currentRec.getValue({
                            fieldId: 'entity'
                        });

                        var custDis = search.lookupFields({
                            type: search.Type.CUSTOMER,
                            id: custId,
                            columns: ['custentity_netu_cust_discount_per']
                        });

                        var custid = custDis.custentity_netu_cust_discount_per;

                        if ((custid == "") || (custid == null) || (custid == undefined)) {
                            custpercentage = 0;
                        } else {
                            var custper = custid.split("%");
                            custpercentage = custper[0];
                        }

                        //setting the scale discount amount
                        currentRec.setValue({
                            fieldId: 'custbody_netu_c_discount_perc',
                            value: custpercentage,
                            ignoreFieldChange: true
                        });

                    } catch (e) {
                        console.log(e.message);
                    }
                }


                //setting increment in all item lines.
                if ((scriptContext.fieldId == 'custbody_netu_increment') || (scriptContext.fieldId == 'custbody_netu_increment_perc_checkbox')) {

                    try {

                        var currentRec = scriptContext.currentRecord;

                        //validating the increment value
                        var fieldIncr = currentRec.getValue({
                            fieldId: 'custbody_netu_increment'
                        });
                        fieldIncr = checkif(fieldIncr);
                        incremetAndTotal(currentRec);

                    } catch (e) {
                        console.log(e.message);
                    }

                }


                //setting delivery time/unit in all item lines.
                if ((scriptContext.fieldId == 'custbody_netu_delivery_time_unit') || (scriptContext.fieldId == 'custbody_netu_delivery_time')) {

                    try {

                        deliveryChange = 1;
                        var currentRec = scriptContext.currentRecord;

                        var deliveryTime = currentRec.getValue({
                            fieldId: 'custbody_netu_delivery_time'
                        });
                        var deliveryUnit = currentRec.getText({
                            fieldId: 'custbody_netu_delivery_time_unit'
                        });
                        console.log('deliveryUnit', deliveryUnit);

                        if (deliveryTime == null || deliveryTime == '' || deliveryTime == undefined) {
                            deliveryTime = 0;
                        }
                        if (deliveryUnit == null || deliveryUnit == '' || deliveryUnit == undefined) {
                            deliveryUnit = ' ';
                        }

                        var NumLines = currentRec.getLineCount({
                            sublistId: 'item'
                        });

                        for (var l = 0; l < NumLines; l++) {

                            currentRec.selectLine({
                                sublistId: 'item',
                                line: l
                            });
                            currentRec.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'custcol_netu_delivery_time_type',
                                value: deliveryTime + ' ' + deliveryUnit,
                                fireSlavingSync: false,
                                ignoreFieldChange: true

                            });

                            currentRec.commitLine({
                                sublistId: 'item'
                            });
                        }

                        deliveryChange = 0;
                    } catch (e) {
                        console.log(e.message);
                    }
                }


                //validating the increment field in item line
                if (((scriptContext.sublistId == 'item') &&
                        (scriptContext.fieldId == 'custcol_netu_increment')) || ((scriptContext.sublistId == 'item') &&
                        (scriptContext.fieldId == 'custcol_netu_increment_percentage'))) {

                    try {
                        var currentRec = scriptContext.currentRecord;
                        rateAndTotal(currentRec);
                    } catch (e) {
                        console.log(e.message);
                    }
                }


                //based on the field change of values from purchase requisition
                if ((scriptContext.sublistId == 'item') && (scriptContext.fieldId == 'custcol_netu_purch_price')) {
                    try {
                    	
                        var currentRec = scriptContext.currentRecord;
                        
                        //fetching the itemId for excluding the line 'D'
                        var itemId = currentRec.getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'item'
                        });
                        
                        //excluding the description line
                        if(itemId!= '213')
                        {

                        var fieldIncr = currentRec.getValue({
                            fieldId: 'custbody_netu_increment'
                        });
                        fieldIncr = checkif(fieldIncr);

                        var fieldIncrPer = currentRec.getValue({
                            fieldId: 'custbody_netu_increment_perc_checkbox'
                        });
                        if (fieldIncrPer) {
                            currentRec.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'custcol_netu_increment_percentage',
                                value: true,
                                ignoreFieldChange: true
                            });
                        }

                        //calculating the cost gross amount based on the field change
                        var quantity = currentRec.getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantity'
                        });
                        quantity = checkif(quantity);

                        var Price = currentRec.getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_purch_price'
                        });
                        Price = checkif(Price);

                        var costgrossNew = parseFloat(quantity) * parseFloat(Price);

                        //Setting cost gross amount
                        currentRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_purch_gross_amount',
                            value: costgrossNew,
                            ignoreFieldChange: true
                        });

                        currentRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_increment',
                            value: fieldIncr,
                            ignoreFieldChange: true
                        });


                        //setting delivery time and unit 
                        var deliveryTime = currentRec.getValue({
                            fieldId: 'custbody_netu_delivery_time'
                        });
                        var deliveryUnit = currentRec.getText({
                            fieldId: 'custbody_netu_delivery_time_unit'
                        });

                        deliveryTime = checkif(deliveryTime);

                        if (deliveryUnit == null || deliveryUnit == '' || deliveryUnit == undefined) {
                            deliveryUnit = ' ';
                        }

                        currentRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_delivery_time_type',
                            value: deliveryTime + ' ' + deliveryUnit,
                            fireSlavingSync: false,
                            ignoreFieldChange: true

                        });
                        rateAndTotal(currentRec);
                    }

                    } catch (e) {
                        console.log(e.message);
                    }


                }


                if ((scriptContext.sublistId == 'item') && (scriptContext.fieldId == 'quantity')) {
                    try {

                        console.log('qunatity');
                        var currentRec = scriptContext.currentRecord;
                        
                    	//fetching the itemId for excluding the line 'D'
                        var itemId = currentRec.getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'item'
                        });
                        
                        if(itemId!= '213')
                        {
                        var fieldIncr = currentRec.getValue({
                            fieldId: 'custbody_netu_increment'
                        });
                        fieldIncr = checkif(fieldIncr);

                        //calculating the cost gross amount based on the field change
                        var quantity = currentRec.getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantity'
                        });

                        quantity = checkif(quantity);

                        var Price = currentRec.getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_purch_price'
                        });
                        Price = checkif(Price);

                        var costgrossNew = parseFloat(quantity) * parseFloat(Price);

                        //Setting cost gross amount
                        currentRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_purch_gross_amount',
                            value: costgrossNew,
                            ignoreFieldChange: true
                        });

                        currentRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_increment',
                            value: fieldIncr,
                            ignoreFieldChange: true
                        });

                        if (refFlag == 1) {
                            var rate = currentRec.getCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'rate'
                            });
                            rate = checkif(rate);
                            var amnt = parseFloat(rate) * parseFloat(quantity);

                            currentRec.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'amount',
                                value: amnt,
                                ignoreFieldChange: true
                            });
                            currentRec.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'custcol_netu_selling_gross',
                                value: amnt,
                                ignoreFieldChange: true
                            });

                        } else {
                            rateAndTotal(currentRec);
                        }
                   }

                    } catch (e) {
                        console.log(e.message);
                    }


                }


                if ((scriptContext.sublistId == 'item') && (scriptContext.fieldId == 'rate')) {
                    try {
                        refFlag = 1;
                        var currentRec = scriptContext.currentRecord;


                        var rateNw = currentRec.getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'rate'
                        });
                        rateNw = checkif(rateNw);

                        var quantityNw = currentRec.getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantity'
                        });
                        quantityNw = checkif(quantityNw);

                        var amountNw = parseFloat(quantityNw) * parseFloat(rateNw);

                        currentRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_selling_price',
                            value: rateNw,
                            ignoreFieldChange: true
                        });

                        currentRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'amount',
                            value: amountNw,
                            ignoreFieldChange: true
                        });

                        currentRec.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_selling_gross',
                            value: amountNw,
                            ignoreFieldChange: true
                        });

                    } catch (e) {
                        console.log(e.message);
                    }
                }



                //calculating values in discount amount field change
                if (scriptContext.fieldId == 'custbody_netu_sales_discount_amount') {
                    try {

                        discAmntChngflag = 1;
                        var currentRec = scriptContext.currentRecord;

                        var exrate = currentRec.getValue({
                            fieldId: 'exchangerate'
                        });
                        var commiChange = currentRec.getValue({
                            fieldId: 'custbody_netu_sales_discount_amount'
                        });
                        var gross = currentRec.getValue({
                            fieldId: 'custbody_netu_sales_gross_amount'
                        });
                        var fre = currentRec.getValue({
                            fieldId: 'custbody_netu_freight'
                        });
                        var pack = currentRec.getValue({
                            fieldId: 'custbody_netu_packing_charges'
                        });
                        fre = checkif(fre);
                        pack = checkif(pack);
                        commiChange = checkif(commiChange);
                        gross = checkif(gross);

                        var commiBase = commiChange * parseFloat(exrate);
                        var net = parseFloat(gross) - parseFloat(commiChange);
                        var netBase = net * parseFloat(exrate);
                        var salesNetAmtAfterCh = parseFloat(net) + parseFloat(pack) + parseFloat(fre);
                        var salesNetAmtAfterChBase = salesNetAmtAfterCh * parseFloat(exrate);

                        var calFileds = [commiBase, net, netBase, salesNetAmtAfterCh, salesNetAmtAfterChBase];
                        var setFileds = ['custbody_netu_sales_discount_amount_b', 'custbody_netu_sales_net_amount', 'custbody_netu_sales_net_amount_b', 'custbody_netu_sales_net_amnt_charges', 'custbody_netu_sales_net_amnt_charges_b'];
                        for (var l = 0; l < 5; l++) {
                            calFileds[l] = parseFloat(calFileds[l]).toFixed(2);
                           
                            currentRec.setValue({
                                fieldId: setFileds[l],
                                value: calFileds[l],
                                ignoreFieldChange: true
                            });
                        }

                        profit(currentRec);


                    } catch (e) {
                        console.log(e.message);
                    }

                }




                //calculating values in cost commission amount change
                if (scriptContext.fieldId == 'custbody_netu_cost_commission_amount') {
                    try {
                        var currentRec = scriptContext.currentRecord;
                        currentRec.setValue({
                            fieldId: 'custbody_netu_commi_change_by_user',
                            value: 1,
                            ignoreFieldChange: true
                        });
                        var grossA = currentRec.getValue({
                            fieldId: 'custbody_netu_cost_gross_amount'
                        });
                        grossA = checkif(grossA);

                        var discAm = currentRec.getValue({
                            fieldId: 'custbody_netu_cost_discount_amount'
                        });
                        discAm = checkif(discAm);

                        var exrate = currentRec.getValue({
                            fieldId: 'exchangerate'
                        });
                        var commiChangeNew = currentRec.getValue({
                            fieldId: 'custbody_netu_cost_commission_amount'
                        });
                        commiChangeNew = checkif(commiChangeNew);

                        var newCostcommiBase = commiChangeNew * parseFloat(exrate);
                        newCostcommiBase = parseFloat(newCostcommiBase).toFixed(2);
                        currentRec.setValue({
                            fieldId: 'custbody_netu_cost_commission_amount_b',
                            value: newCostcommiBase,
                            ignoreFieldChange: true
                        });

                        var after = parseFloat(grossA) - parseFloat(discAm);
                        var newCostcommi = (parseFloat(commiChangeNew) * 100) / parseFloat(after);
                        var commiPer = parseFloat(newCostcommi).toFixed(2);
                        currentRec.setValue({
                            fieldId: 'custbody_netu_v_commission_perc',
                            value: commiPer,
                            ignoreFieldChange: true
                        });

                        netCommission(currentRec, commiChangeNew);
                        profit(currentRec);
                    } catch (e) {
                        console.log(e.message);
                    }

                }



                //calculating values in cost discount amount change
                if (scriptContext.fieldId == 'custbody_netu_cost_discount_amount') {
                    try {
                        var currentRec = scriptContext.currentRecord;
                        var grossAD = currentRec.getValue({
                            fieldId: 'custbody_netu_cost_gross_amount'
                        });
                        grossAD = checkif(grossAD);

                        var discA = currentRec.getValue({
                            fieldId: 'custbody_netu_cost_discount_amount'
                        });
                        discA = checkif(discA);

                        var exrate = currentRec.getValue({
                            fieldId: 'exchangerate'
                        });

                        var discABase = discA * parseFloat(exrate);
                        discABase = parseFloat(discABase).toFixed(2);
                        currentRec.setValue({
                            fieldId: 'custbody_netu_cost_discount_amount_b',
                            value: discABase,
                            ignoreFieldChange: true
                        });

                        var perDisc = (parseFloat(discA) * 100) / parseFloat(grossAD);
                        perDisc = parseFloat(perDisc).toFixed(2);
                        currentRec.setValue({
                            fieldId: 'custbody_netu_v_discount_perc',
                            value: perDisc,
                            ignoreFieldChange: true
                        });

                        var commissiPer = currentRec.getValue({
                            fieldId: 'custbody_netu_v_commission_perc'
                        });

                        var AmntCommi = (parseFloat(commissiPer) * (parseFloat(grossAD) - parseFloat(discA))) / 100;

                        netCommission(currentRec, AmntCommi);
                        profit(currentRec);


                    } catch (e) {
                        console.log(e.message);
                    }

                }


                if ((scriptContext.fieldId == 'custbody_netu_c_discount_perc')) {
                    try {
                        discAmntChngflag = 0;
                        var currentRec = scriptContext.currentRecord;
                        var grossSum = currentRec.getValue({
                            fieldId: 'custbody_netu_sales_gross_amount'
                        });
                        grossSum = checkif(grossSum);

                        salesfields(currentRec, grossSum);
                        salesPackAnddfreight(currentRec);
                        profit(currentRec);
                    } catch (e) {
                        console.log(e.message);
                    }
                }


                //setting in the field change of packing,freight,discount
                if ((scriptContext.fieldId == 'custbody_netu_packing_charges') || (scriptContext.fieldId == 'custbody_netu_freight')) {
                    try {

                        var currentRec = scriptContext.currentRecord;
                        var grossSum = currentRec.getValue({
                            fieldId: 'custbody_netu_sales_gross_amount'
                        });
                        grossSum = checkif(grossSum);
                        salesPackAnddfreight(currentRec);
                        profit(currentRec);
                    } catch (e) {
                        console.log(e.message);
                    }
                }

                //setting values in the field change of vendor packing and freight
                if ((scriptContext.fieldId == 'custbody_netu_v_packing_charges') || (scriptContext.fieldId == 'custbody_netu_v_freight')) {

                    try {
                        var currentRec = scriptContext.currentRecord;
                        packingFreight(currentRec);
                        profit(currentRec);
                    } catch (e) {
                        console.log(e.message);
                    }
                }



                //calculating gross values in the field change of vendor discount.
                if (scriptContext.fieldId == 'custbody_netu_v_discount_perc') {
                    try {
                        var currentRec = scriptContext.currentRecord;
                        var exchRate = currentRec.getValue({
                            fieldId: 'exchangerate'
                        });

                        var vendorDisc = currentRec.getValue({
                            fieldId: 'custbody_netu_v_discount_perc'
                        });
                        vendorDisc = checkif(vendorDisc);

                        var grossAmnt = currentRec.getValue({
                            fieldId: 'custbody_netu_cost_gross_amount'
                        });
                        grossAmnt = checkif(grossAmnt);

                        var costdiscAmount = (grossAmnt * parseFloat(vendorDisc)) / 100;
                        costdiscAmount = parseFloat(costdiscAmount).toFixed(2);

                        //setting the cost discount amount
                        currentRec.setValue({
                            fieldId: 'custbody_netu_cost_discount_amount',
                            value: costdiscAmount,
                            ignoreFieldChange: true
                        });

                        var costdiscAmountBase = (parseFloat(costdiscAmount) * parseFloat(exchRate));
                        costdiscAmountBase = parseFloat(costdiscAmountBase).toFixed(2);
                        //setting the cost discount amount(base)
                        currentRec.setValue({
                            fieldId: 'custbody_netu_cost_discount_amount_b',
                            value: costdiscAmountBase,
                            ignoreFieldChange: true
                        });

                        //finding the commission amount
                        var vendCommi = currentRec.getValue({
                            fieldId: 'custbody_netu_v_commission_perc'
                        });

                        if (vendCommi) {
                            //finding the commission amount
                            var vendorCommiAmnt = ((parseFloat(grossAmnt) - parseFloat(costdiscAmount)) * parseFloat(vendCommi)) / 100;
                            
                        } else if (!vendCommi) {
                            var vendorCommiAmnt = currentRec.getValue({
                                fieldId: 'custbody_netu_cost_commission_amount'
                            });
                        }
                        netCommission(currentRec, vendorCommiAmnt);
                        profit(currentRec);
                    } catch (e) {
                        console.log(e.message);
                    }
                }


                //calculating cost values in the field change of commission percentage.
                if (scriptContext.fieldId == 'custbody_netu_v_commission_perc') {
                    try {
                        var currentRec = scriptContext.currentRecord;

                        currentRec.setValue({
                            fieldId: 'custbody_netu_commi_change_by_user',
                            value: 1,
                            ignoreFieldChange: true
                        });

                        var CommiPercentage = currentRec.getValue({
                            fieldId: 'custbody_netu_v_commission_perc'
                        });
                        CommiPercentage = checkif(CommiPercentage);

                        var CommiGross = currentRec.getValue({
                            fieldId: 'custbody_netu_cost_gross_amount'
                        });
                        CommiGross = checkif(CommiGross);

                        var CommiDisc = currentRec.getValue({
                            fieldId: 'custbody_netu_cost_discount_amount'
                        });
                        CommiDisc = checkif(CommiDisc);

                        var commissionAmnt = ((parseFloat(CommiGross) - parseFloat(CommiDisc)) * parseFloat(CommiPercentage)) / 100;

                        netCommission(currentRec, commissionAmnt);
                        profit(currentRec);



                    } catch (e) {
                        console.log(e);
                    }
                }


                //calculating cost values in the field change of scale check box.
                if (scriptContext.fieldId == 'custbody_netu_scale_commission') {
                    try {

                        var currentRec = scriptContext.currentRecord;
                        currentRec.setValue({
                            fieldId: 'custbody_netu_commi_change_by_user',
                            value: null,
                            ignoreFieldChange: true
                        });
                        var scaleValue = currentRec.getValue({
                            fieldId: 'custbody_netu_scale_commission'
                        });
                        var scaleGross = currentRec.getValue({
                            fieldId: 'custbody_netu_cost_gross_amount'
                        });
                        scaleGross = checkif(scaleGross);

                        var scaleCommiAmount = null;

                        var getCommi = currentRec.getText({
                            fieldId: 'custbody_netu_location_principal'
                        });

                        var locFlag = null;
                        if (getCommi) {
                            var getCommObjt = JSON.parse(getCommi);
                            var locFlag = getCommObjt.locationFlag;
                            var alertVendor = getCommObjt.alertVendorLocation;
                            var alertMain = getCommObjt.alertMainLocation;

                            if ((alertVendor) && (vendorAlert != 1)) {
                                alert(alertVendor);
                                vendorAlert = 1;
                            }

                            if ((alertMain) && (mainAlert != 1)) {
                                alert(alertMain);
                                mainAlert = 1;
                            }

                        }
                        if (locFlag == 1) {
                            if (scaleValue) {
                                scaleCommiAmount = vendorCommissionScale(currentRec);
                                
                            } else if (!scaleValue) {
                                scaleCommiAmount = vendorCommission(currentRec, getCommObjt);
                            }

                            netCommission(currentRec, scaleCommiAmount);
                            profit(currentRec);
                        } else {
                            currentRec.setValue({
                                fieldId: 'custbody_netu_v_commission_perc',
                                value: 0,
                                ignoreFieldChange: true
                            });
                            currentRec.setValue({
                                fieldId: 'custbody_netu_cost_commission_amount',
                                value: 0,
                                ignoreFieldChange: true
                            });

                            var scaleCommiAmount = 0;

                            netCommission(currentRec, scaleCommiAmount);
                            profit(currentRec);

                            return false;
                        }
                    } catch (e) {
                        console.log(e);
                    }
                }


                if ((scriptContext.sublistId == 'item') &&
                    (scriptContext.fieldId == 'custcol_netu_select')) {
                   
                    var CurrRecord = scriptContext.currentRecord;
                    // to get line number
                    var linNum = CurrRecord.getLineCount({
                        sublistId: 'item'
                    });
                    // get current line checkbox value
                    var current_select = CurrRecord
                        .getCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_select'
                        });
                    // get line number of current line
                    var currline = CurrRecord.getCurrentSublistIndex({
                        sublistId: 'item'
                    });
                    
                    // get line number of other line where checkbox is true
                    var trueLineNumber = CurrRecord
                        .findSublistLineWithValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_select',
                            value: 'T'
                        });
                    
                    if (trueLineNumber > -1) {
                        // set the true checkbox to false

                        CurrRecord.selectLine({
                            sublistId: 'item',
                            line: trueLineNumber
                        });
                        CurrRecord.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_select',
                            value: false,
                            ignoreFieldChange: true
                        });
                        CurrRecord.commitLine({
                            sublistId: 'item'
                        });

                    }
                    //set true to current line checkbox
                    if (currline != trueLineNumber) {
                        CurrRecord.selectLine({
                            sublistId: 'item',
                            line: currline
                        });
                        CurrRecord.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_select',
                            value: true,
                            ignoreFieldChange: true
                        });
                    } else {

                        CurrRecord.selectLine({
                            sublistId: 'item',
                            line: currline
                        });
                    }
                }
                
            } catch (e) {
                console.log(e);
            }
        }


        function lineInit(scriptContext) {
            try {

                var currentrecord = scriptContext.currentRecord;
                // get item id
                var itemid = currentrecord.getCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'custcol_netu_item_id'
                });

                var subjob = currentrecord.getValue({
                    fieldId: 'custbody_netu_subjob_type'
                });
                //console.log("***subjob ****",subjob);
                // if item is additional/free item normal netsuite remove
                if ((itemid.includes("_")) || (itemid.includes("-"))) {
                    //console.log("extra item");
                    document.getElementById('item_custcol_netu_select_fs_inp').disabled = true;

                }
                // if item is normal item trigger remove
                else {
                    document.getElementById('item_custcol_netu_select_fs_inp').disabled = false;
                    // remove onclick function of standard netsuite Remove button
                    jQuery('#item_remove').attr('onclick', '');
                    // when user click on remove button 
                }
                if (subjob != 1) {

                    document.getElementById('item_custcol_netu_select_fs_inp').disabled = true;
                }

            } catch (e) {
                console.log("error@sublistchange=", e.message);
            }
        }



        function getRemoveList(currentrecord) {

            try {
                var removeList = [],
                    count = 0,
                    isNormal = 0;

                var itemid = currentrecord.getCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'custcol_netu_item_id'
                });
                // console.log("item id in get remove list fn=",itemid);
                // to get the min . price and options
                var actualPrice = [];


                var lineNum = currentrecord.getLineCount({
                    sublistId: 'item'
                });

                var optId = parseInt(itemid);
                var optionalId = optId + '-';
                var itemid_ = optId + '_';
                var other_itemid = itemid;
                removeList.push(itemid);
                if ((itemid == optId) || (other_itemid.startsWith(optionalId))) {
                    isNormal = 1;
                }
                // get internal id of matching additional/free items of current item line and push to array
                for (var i = 0; i < lineNum; i++) {
                    other_itemid = currentrecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_item_id',
                        line: i
                    });
                    if ((other_itemid == optId) || (other_itemid.startsWith(optionalId))) {
                        count++;
                    }
                }
               
                for (var i = 0; i < lineNum; i++) {
                    other_itemid = currentrecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_item_id',
                        line: i
                    });
                    if ((count == 1) && (isNormal == 1)) {
                        if (other_itemid.startsWith(itemid_)) {
                            removeList.push(other_itemid);
                        }
                    }
                }

                return removeList;

            } catch (e) {
                console.log(e.message);
            }
        }

        /***** Remove item line END*****/

        //getting commission based on the vendor commission and budget record.
        function vendorCommission(currentReco, getCommObjt) {

            try {

                var vendornm = currentReco.getText({
                    fieldId: 'custbody_netu_vendor'
                });
                var fix_commi = getCommObjt.fixCommission;

                if (fix_commi) {
                    currentReco.setValue({
                        fieldId: 'custbody_netu_v_commission_perc',
                        value: fix_commi,
                        ignoreFieldChange: true
                    });

                    var CommiGrossSs = currentReco.getValue({
                        fieldId: 'custbody_netu_cost_gross_amount'
                    });
                    CommiGrossSs = checkif(CommiGrossSs);

                    var CommiDiscSs = currentReco.getValue({
                        fieldId: 'custbody_netu_cost_discount_amount'
                    });
                    CommiDiscSs = checkif(CommiDiscSs);

                    var commissionAmntScale = ((parseFloat(CommiGrossSs) - parseFloat(CommiDiscSs)) * parseFloat(fix_commi)) / 100;

                } else {
                	

                    if (fixCommiAlert != 1) {
                        alert('Fixed Commission is not defined for Vendor "' + vendornm + '"');
                        fixCommiAlert = 1;
                    }
                        
                    var commissionAmntScale = 0;

                    currentReco.setValue({
                        fieldId: 'custbody_netu_v_commission_perc',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    currentReco.setValue({
                        fieldId: 'custbody_netu_cost_commission_amount',
                        value: 0,
                        ignoreFieldChange: true
                    });
                }
                return commissionAmntScale;

            } catch (e) {
                console.log(e.message);
            }

        }



        //getting the commission based on the commission list record.
        function vendorCommissionScale(currentReco) {

            try {

                var CommiGrossS = currentReco.getValue({
                    fieldId: 'custbody_netu_cost_gross_amount'
                });
                var CommiDiscS = currentReco.getValue({
                    fieldId: 'custbody_netu_cost_discount_amount'
                });
                var afterDiscAmnt = parseFloat(CommiGrossS) - parseFloat(CommiDiscS);
                commisionAmntscale = checkif(afterDiscAmnt);

                var orginalTAD = commisionAmntscale;

                //getting the current vendor
                var vendor = currentReco.getValue({
                    fieldId: 'custbody_netu_vendor'
                });

                var vendorName = currentReco.getText({
                    fieldId: 'custbody_netu_vendor'
                });
               
                //Searching the vendor commission from the vendor budget and fixed commission list.
                var customrecord_netu_vendor_commissionSearchObj = search.create({
                    type: "customrecord_netu_vendor_commission",
                    filters: [
                        ["custrecord_netu_vendor_commission_record", "anyof", vendor],
                        /* "AND", 
                      ["formulanumeric: CASE WHEN "+afterDiscAmnt+" between {custrecord_netu_commission_amount_from} and {custrecord_netu_commission_amount_to} THEN 1 ELSE 0 END","equalto","1"]
                  */
                    ],
                    columns: [
                        search.createColumn({
                            name: "custrecord_netu_commission_amount_to",
                            sort: search.Sort.ASC,
                            label: "Commission Amount To"
                        }),
                        "custrecord_netu_commission_amount_from",
                        "custrecord_netu_commission_amount_to",
                        "custrecord_netu_commission_value",
                        "custrecord_netu_ommission_percentage",
                        "custrecord_netu_vendor_commission_record"
                    ]
                });

                var vendorScaleCommissionResultCount = customrecord_netu_vendor_commissionSearchObj.runPaged().count;
                console.log('vendorScaleCommissionResultCount', vendorScaleCommissionResultCount);

                if (vendorScaleCommissionResultCount != 0) {


                    var vendorScaleResults = customrecord_netu_vendor_commissionSearchObj.run().getRange({
                        start: 0,
                        end: 50
                    });

                    var newTAD = 0;
                    var commiAmnt = 0;
                    var commiAmntNew = 0;
                    var scaleCommiPE = 0;
                    var scaleCommission = 0;

                    for (var f = 0; f < vendorScaleCommissionResultCount; f++) {

                        var amountTo = vendorScaleResults[f].getValue({
                            name: 'custrecord_netu_commission_amount_to'
                        });

                        if (commisionAmntscale >= amountTo) {
                            commisionAmntscale = parseFloat(commisionAmntscale) - parseFloat(amountTo);

                            scaleCommiPE = vendorScaleResults[f].getValue({
                                name: 'custrecord_netu_ommission_percentage'
                            });
                            scaleCommission = vendorScaleResults[f].getValue({
                                name: 'custrecord_netu_commission_value'
                            });
                            if (scaleCommiPE) {
                                commiAmntNew = (parseFloat(amountTo) * parseFloat(scaleCommission)) / 100;
                            } else {
                                commiAmntNew = scaleCommission;
                            }
                            commiAmnt = parseFloat(commiAmnt) + parseFloat(commiAmntNew);


                            if (f == vendorScaleCommissionResultCount - 1 && commiFlag != 1) {
                                alert('Commission is not defined from the range ' + amountTo + '');
                                commiFlag = 1;
                            }


                        } else {
                            scaleCommiPE = vendorScaleResults[f].getValue({
                                name: 'custrecord_netu_ommission_percentage'
                            });

                            scaleCommission = vendorScaleResults[f].getValue({
                                name: 'custrecord_netu_commission_value'
                            });

                            if (scaleCommiPE) {
                                commiAmntNew = (parseFloat(commisionAmntscale) * parseFloat(scaleCommission)) / 100;
                            } else {
                                commiAmntNew = scaleCommission;
                            }
                            commiAmnt = parseFloat(commiAmnt) + parseFloat(commiAmntNew);

                            break;
                        }
                    }

                    var commiPerecenatge = (parseFloat(commiAmnt) * 100) / parseFloat(orginalTAD);
                    commiPerecenatge = parseFloat(commiPerecenatge).toFixed(2);

                    currentReco.setValue({
                        fieldId: 'custbody_netu_v_commission_perc',
                        value: commiPerecenatge,
                        ignoreFieldChange: true
                    });
                    return commiAmnt;

                } else {
                    if (sacleCommiAlert != 1) {
                        alert('Scale Commission is not defined for Vendor "' + vendorName + '"');
                        sacleCommiAlert = 1;
                    }

                    currentReco.setValue({
                        fieldId: 'custbody_netu_v_commission_perc',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    currentReco.setValue({
                        fieldId: 'custbody_netu_cost_commission_amount',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    var commiamntt = 0;
                    return commiamntt;
                }

            } catch (e) {
                console.log(e.message);
            }

        }

        //(cost) setting commission amount,net amount...and.....(base values)
        function netCommission(currentRec, vCommiAmnt) {
            try {

                vCommiAmnt = parseFloat(vCommiAmnt).toFixed(2);
                var purExV = currentRec.getValue({
                    fieldId: 'exchangerate'
                });

                //setting commission amount and base
                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_commission_amount',
                    value: vCommiAmnt,
                    ignoreFieldChange: true
                });
                var vCommiAmntBase = parseFloat(vCommiAmnt) * parseFloat(purExV);
                vCommiAmntBase = parseFloat(vCommiAmntBase).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_commission_amount_b',
                    value: vCommiAmntBase,
                    ignoreFieldChange: true
                });

                //finding the net amount
                var grossV = currentRec.getValue({
                    fieldId: 'custbody_netu_cost_gross_amount'
                });
                grossV = checkif(grossV);

                var afterDiscV = currentRec.getValue({
                    fieldId: 'custbody_netu_cost_discount_amount'
                });
                afterDiscV = checkif(afterDiscV);

                var netAmntV = parseFloat(grossV) - parseFloat(afterDiscV) - parseFloat(vCommiAmnt);
                netAmntV = parseFloat(netAmntV).toFixed(2);

                //setting net amount and base
                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_net_amount',
                    value: netAmntV,
                    ignoreFieldChange: true
                });
                var vCommiNetBase = parseFloat(netAmntV) * parseFloat(purExV);
                vCommiNetBase = parseFloat(vCommiNetBase).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_net_amount_b',
                    value: vCommiNetBase,
                    ignoreFieldChange: true
                });

                packingFreight(currentRec);
                
            } catch (e) {
                console.log(e.message);
            }

        }

        //(cost) setting values packing,freight,cost after charges...and all its base values...setting profit
        function packingFreight(currentRec) {
            try {

                //getting the current exchange rate
                var purEx = currentRec.getValue({
                    fieldId: 'exchangerate'
                });

                //getting the cost net amount
                var costGrossSum = currentRec.getValue({
                    fieldId: 'custbody_netu_cost_net_amount'
                });
                costGrossSum = checkif(costGrossSum);

                var venodrPacking = currentRec.getValue({
                    fieldId: 'custbody_netu_v_packing_charges'
                });
                venodrPacking = checkif(venodrPacking);

                var vendorfreight = currentRec.getValue({
                    fieldId: 'custbody_netu_v_freight'
                });
                vendorfreight = checkif(vendorfreight);

                var venodrPackingBase = parseFloat(purEx) * parseFloat(venodrPacking);
                var vendorfreightBase = parseFloat(purEx) * parseFloat(vendorfreight);
                var costNetAmtAfterchange = parseFloat(costGrossSum) + parseFloat(venodrPacking) + parseFloat(vendorfreight);
                var costNetAmtAfterchangeBase = parseFloat(purEx) * parseFloat(costNetAmtAfterchange);

                var calcFields = [venodrPackingBase, vendorfreightBase, costNetAmtAfterchange, costNetAmtAfterchangeBase];
                var setFileldss = ['custbody_netu_v_packing_charges_b', 'custbody_netu_v_freight_b', 'custbody_netu_cost_net_amnt_charges', 'custbody_netu_cost_net_amnt_charges_b']

                for (var g = 0; g < 4; g++) {

                    calcFields[g] = parseFloat(calcFields[g]).toFixed(2);
                    currentRec.setValue({
                        fieldId: setFileldss[g],
                        value: calcFields[g],
                        ignoreFieldChange: true
                    });
                }


            } catch (e) {
                console.log(e);
            }
        }

        function costRecalculation(currentRec) {
            try {
                var grandSum = calculateGrossSumCost(currentRec);

                grandSum = parseFloat(grandSum).toFixed(2);

                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_gross_amount',
                    value: grandSum,
                    ignoreFieldChange: true
                });

                var excRateC = currentRec.getValue({
                    fieldId: 'exchangerate'
                });
                //setting sales gross amount(base)
                var salesGrossBaseC = parseFloat(excRateC) * parseFloat(grandSum);
                salesGrossBaseC = parseFloat(salesGrossBaseC).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_gross_amount_base',
                    value: salesGrossBaseC,
                    ignoreFieldChange: true
                });

                //getting discount percentage
                var discPerC = currentRec.getValue({
                    fieldId: 'custbody_netu_v_discount_perc'
                });

                var costdiscAmountC = (grandSum * parseFloat(discPerC)) / 100;
                costdiscAmountC = parseFloat(costdiscAmountC).toFixed(2);
                //setting the scale discount amount
                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_discount_amount',
                    value: costdiscAmountC,
                    ignoreFieldChange: true
                });

                //setting the scale discount amount(base)
                var discountbaseC = parseFloat(excRateC) * parseFloat(costdiscAmountC);
                discountbaseC = parseFloat(discountbaseC).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_discount_amount_b',
                    value: discountbaseC,
                    ignoreFieldChange: true
                });

                //*****************************************
                var getCommi2 = currentRec.getText({
                    fieldId: 'custbody_netu_location_principal'
                });
                var scaleValues = currentRec.getValue({
                    fieldId: 'custbody_netu_scale_commission'
                });
                var userCommiChange = currentRec.getValue({
                    fieldId: 'custbody_netu_commi_change_by_user'
                });

                if (!userCommiChange) {

                   var locFlag2 = null;
                    if (getCommi2) {
                        var getCommObjt = JSON.parse(getCommi2);
                        var locFlag2 = getCommObjt.locationFlag;
                        var alertVendor = getCommObjt.alertVendorLocation;
                        var alertMain = getCommObjt.alertMainLocation;

                        if ((alertVendor) && (vendorAlert != 1)) {
                            alert(alertVendor);
                            vendorAlert = 1;
                        }

                        if ((alertMain) && (mainAlert != 1)) {
                            alert(alertMain);
                            mainAlert = 1;
                        }


                    }

                    if (locFlag2 == 1) {
                        if (scaleValues) {
                            scaleCommiAmount = vendorCommissionScale(currentRec);
                            console.log('scaleCommiAmount', scaleCommiAmount);
                        } else if (!scaleValues) {
                            scaleCommiAmount = vendorCommission(currentRec, getCommObjt);
                        }
                    } else {
                        currentRec.setValue({
                            fieldId: 'custbody_netu_v_commission_perc',
                            value: 0,
                            ignoreFieldChange: true
                        });
                        currentRec.setValue({
                            fieldId: 'custbody_netu_cost_commission_amount',
                            value: 0,
                            ignoreFieldChange: true
                        });

                        var scaleCommiAmount = 0;
                    }

                    netCommission(currentRec, scaleCommiAmount);

                } else {

                    var vendCommi = currentRec.getValue({
                        fieldId: 'custbody_netu_v_commission_perc'
                    });

                    if (vendCommi) {
                        //finding the commission amount
                        var vendorCommiAmnt = ((parseFloat(grandSum) - parseFloat(costdiscAmountC)) * parseFloat(vendCommi)) / 100;
                        
                    } else if (!vendCommi) {
                        var vendorCommiAmnt = currentRec.getValue({
                            fieldId: 'custbody_netu_cost_commission_amount'
                        });
                    }
                    netCommission(currentRec, vendorCommiAmnt);
               }
            } catch (e) {
                console.log(e);
            }
        }
        

        //setting the selling price and grand total in the field change of increment in item line.
        function rateAndTotal(currentRec) {
            try {

                //calculating the selling price based on the field change
                var Price = currentRec.getCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'custcol_netu_purch_price'
                });
                Price = checkif(Price);

                var increment = currentRec.getCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'custcol_netu_increment'
                });
                increment = checkif(increment);

                var quantity = currentRec.getCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'quantity'
                });

                var perCheckline = currentRec.getCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'custcol_netu_increment_percentage'
                });
                
                //calculating the selling price(rate) by checking the weather it is direct increment or percentage.
                if (perCheckline) {
                    incrementPer = parseFloat(increment * Price) / 100;
                    sellingPrice = parseFloat(incrementPer) +
                        parseFloat(Price);


                    //Setting true in item line
                    currentRec.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_increment_percentage',
                        value: true,
                        ignoreFieldChange: true
                    });



                } else if (!perCheckline) {
                    sellingPrice = parseFloat(increment) +
                        parseFloat(Price);
                    currentRec.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_increment_percentage',
                        value: false,
                        ignoreFieldChange: true
                    });

                }

                //setting selling price(rate)
                currentRec.setCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'rate',
                    value: sellingPrice,
                    ignoreFieldChange: true
                });


                //calculating grand total(amount)
                var grandTotal = sellingPrice * quantity;

                currentRec.setCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'amount',
                    value: grandTotal,
                    //fireSlavingSync : false,
                    ignoreFieldChange: true
                });


                currentRec.setCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'custcol_netu_selling_price',
                    value: sellingPrice,
                    ignoreFieldChange: true
                });


                currentRec.setCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'custcol_netu_selling_gross',
                    value: grandTotal,
                    //fireSlavingSync : false,
                    ignoreFieldChange: true
                });

                if (Price == 0) {
                    var actualprice = currentRec.getCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_actual_cost_price'
                    });
                    actualprice = checkif(actualprice);

                    var perChecklinenew = currentRec.getValue({
                        fieldId: 'custbody_netu_increment_perc_checkbox'
                    });

                    var incrementnew = currentRec.getValue({
                        fieldId: 'custbody_netu_increment'
                    });
                    incrementnew = checkif(incrementnew);

                    //calculating the selling price(rate) by checking the weather it is direct increment or percentage.
                    if (perChecklinenew) {

                        var incrementPer = parseFloat(incrementnew * actualprice) / 100;
                        sellingPrice = parseFloat(incrementPer) + parseFloat(actualprice);


                    } else if (!perChecklinenew) {
                        sellingPrice = parseFloat(incrementnew) + parseFloat(actualprice);


                    }

                    var grossSelling = sellingPrice * quantity;

                    currentRec.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_increment',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    currentRec.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'rate',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    currentRec.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'amount',
                        value: 0,
                        ignoreFieldChange: true
                    });

                    currentRec.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_selling_price',
                        value: sellingPrice,
                        ignoreFieldChange: true
                    });

                    currentRec.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_selling_gross',
                        value: grossSelling,
                        //fireSlavingSync : false,
                        ignoreFieldChange: true
                    });


                }



            } catch (e) {
                console.log(e);
            }
        }




        //finding the gross amount if item line field change occurs.
        function calculateGrossSum(currentRec) {
            try {
                var count = currentRec.getLineCount({
                    sublistId: 'item'
                });
                var grossSum = 0;
                for (var i = 0; i < count; i++) {

                    var incId = currentRec.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_incomeid',
                        line: i
                    });
                    if (!incId) {
                        var amount = currentRec.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'grossamt',
                            line: i
                        });
                        amount = checkif(amount);
                        grossSum = grossSum + parseFloat(amount);
                    }
                }
                return grossSum;
            } catch (e) {
                console.log(e.message);
            }
        }




        //finding the gross amount if item line field change occurs for cost values
        function calculateGrossSumCost(currentRec) {
            try {
                var count = currentRec.getLineCount({
                    sublistId: 'item'
                });
                var grossSum = 0;
                for (var i = 0; i < count; i++) {

                    var incId = currentRec.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_incomeid',
                        line: i
                    });
                    if (!incId) {
                        var amount = currentRec.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_purch_gross_amount',
                            line: i
                        });
                        amount = checkif(amount);
                        grossSum = grossSum + parseFloat(amount);
                    }
                }
                return grossSum;
            } catch (e) {
                console.log(e.message);
            }
        }





        //setting the values in sales fields.
        function salesfields(currentRec, grossSum) {
            try {

                var excRate = currentRec.getValue({
                    fieldId: 'exchangerate'
                });
                //setting sales gross amount(base)
                var salesGrossBase = parseFloat(excRate) * parseFloat(grossSum);
                salesGrossBase = parseFloat(salesGrossBase).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custbody_netu_sales_gross_amount_b',
                    value: salesGrossBase,
                    ignoreFieldChange: true
                });

                if (discAmntChngflag != 1) {

                    var custDiscPer = currentRec.getValue({
                        fieldId: 'custbody_netu_c_discount_perc'
                    });
                    custDiscPer = checkif(custDiscPer);

                    var salediscAmount = (grossSum * parseFloat(custDiscPer)) / 100;
                    salediscAmount = parseFloat(salediscAmount).toFixed(2);
                    //setting the scale discount amount
                    currentRec.setValue({
                        fieldId: 'custbody_netu_sales_discount_amount',
                        value: salediscAmount,
                        ignoreFieldChange: true
                    });

                    //setting the scale discount amount(base)
                    var discountbase = parseFloat(excRate) * parseFloat(salediscAmount);
                    discountbase = parseFloat(discountbase).toFixed(2);
                    currentRec.setValue({
                        fieldId: 'custbody_netu_sales_discount_amount_b',
                        value: discountbase,
                        ignoreFieldChange: true
                    });
                }
                var salediscAmount = currentRec.getValue({
                    fieldId: 'custbody_netu_sales_discount_amount'
                });


                var netAmount = parseFloat(grossSum) - parseFloat(salediscAmount);
                netAmount = parseFloat(netAmount).toFixed(2);
                //setting the sale net amount
                currentRec.setValue({
                    fieldId: 'custbody_netu_sales_net_amount',
                    value: netAmount
                });


                //setting the sale net amount(base)
                var netBase = parseFloat(excRate) * parseFloat(netAmount);
                netBase = parseFloat(netBase).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custbody_netu_sales_net_amount_b',
                    value: netBase,
                    ignoreFieldChange: true
                });


            } catch (e) {
                console.log(e.message);
            }

        }




        function salesPackAnddfreight(currentRec) {
            try {

                var excRate = currentRec.getValue({
                    fieldId: 'exchangerate'
                });
                //getting packing/handling and freight value.
                var packHandling = currentRec.getValue({
                    fieldId: 'custbody_netu_packing_charges'
                });
                packHandling = checkif(packHandling);

                var freight = currentRec.getValue({
                    fieldId: 'custbody_netu_freight'
                });
                freight = checkif(freight);

                var netAmount = currentRec.getValue({
                    fieldId: 'custbody_netu_sales_net_amount'
                });
                netAmount = checkif(netAmount);


                var packHandlingBase = parseFloat(excRate) * parseFloat(packHandling);
                var freightBase = parseFloat(excRate) * parseFloat(freight);
                var salesNetAmtAfterCharge = parseFloat(netAmount) + parseFloat(packHandling) + parseFloat(freight);
                var salesAfterChargeBase = parseFloat(excRate) * parseFloat(salesNetAmtAfterCharge);

                var calcFieldsSales = [packHandlingBase, freightBase, salesNetAmtAfterCharge, salesAfterChargeBase];
                var setFileldsSales = ['custbody_netu_packing_charges_b', 'custbody_netu_freight_b', 'custbody_netu_sales_net_amnt_charges', 'custbody_netu_sales_net_amnt_charges_b']

                for (var h = 0; h < 4; h++) {

                    calcFieldsSales[h] = parseFloat(calcFieldsSales[h]).toFixed(2);
                    currentRec.setValue({
                        fieldId: setFileldsSales[h],
                        value: calcFieldsSales[h],
                        ignoreFieldChange: true
                    });
                }



            } catch (e) {
                console.log(e.message);
            }
        }

        //calculating the profit and profit%.
        function profit(currentRec) {
            try {
                var sellingPrice = currentRec.getValue({
                    fieldId: 'custbody_netu_sales_net_amount'
                });

                var costPrice = currentRec.getValue({
                    fieldId: 'custbody_netu_cost_net_amount'
                });

                var profit = parseFloat(sellingPrice) - parseFloat(costPrice);
                var profitPercentage = (profit / parseFloat(sellingPrice)) * 100;

                profitPercentage = checkif(profitPercentage);
                var profitPer = parseFloat(profitPercentage).toFixed(2);
                profit = parseFloat(profit).toFixed(2);

                currentRec.setValue({
                    fieldId: 'custbody_netu_profit_amount',
                    value: profit,
                    ignoreFieldChange: true
                });

                currentRec.setValue({
                    fieldId: 'custbody_netu_profit_perc',
                    value: profitPer,
                    ignoreFieldChange: true
                });
            } catch (e) {
                console.log(e.message);
            }

        }


        //finding the gross amount.....setting increment,selling price,grand total in the increment body field change.
        function incremetAndTotal(currentRec) {
            try {

                var increment = currentRec.getValue({
                    fieldId: 'custbody_netu_increment'
                });
                increment = checkif(increment);

                //calculating number of item line
                var numLines = currentRec.getLineCount({
                    sublistId: 'item'
                });
                var grandSum = 0;
                // console.log('numLines',numLines);
                for (var i = 0; i < numLines; i++) {
                    currentRec.selectLine({
                        sublistId: 'item',
                        line: i
                    });
                    
                    var itemID = currentRec.getCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'item'
                    });

                    var itemadd = currentRec.getCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_optional_addi_free'
                    });

                    var idIncome = currentRec.getCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_incomeid'
                    });

                    var priceValue = currentRec.getCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_purch_price'
                    });

                    var quantity = currentRec.getCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'quantity'
                    });
                    idIncome = checkif(idIncome);
                    priceValue = checkif(priceValue);
                    quantity = checkif(quantity);
                    
                    //Excluding the description line.
                    if(itemID != '213')
                    {

                    //setting increment only if the cost price is not zero.
                    if ((priceValue != "") || (priceValue != null) || (priceValue != undefined)) {
                        if (priceValue != 0) {
                            // if((itemadd!='Free items')&&(!idIncome))
                            if (itemadd != 'Free items') {
                                currentRec.setCurrentSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'custcol_netu_increment',
                                    value: increment,
                                    fireSlavingSync: false,
                                    ignoreFieldChange: true

                                });

                                var Price = currentRec.getCurrentSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'custcol_netu_purch_price'
                                });

                                var perCheck = currentRec.getValue({
                                    fieldId: 'custbody_netu_increment_perc_checkbox'
                                });

                                if (perCheck) {
                                    incrementPer = parseFloat(increment * Price) / 100;
                                    //console.log('incrementPer',incrementPer);
                                    var sellingPr = parseFloat(incrementPer) +
                                        parseFloat(Price);
                                    sellingPrice = parseFloat(sellingPr).toFixed(2);

                                    //Setting true in item line
                                    currentRec.setCurrentSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'custcol_netu_increment_percentage',
                                        value: true,
                                        ignoreFieldChange: true
                                    });


                                } else if (!perCheck) {
                                    sellingPrice = parseFloat(increment) +
                                        parseFloat(Price);

                                    currentRec.setCurrentSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'custcol_netu_increment_percentage',
                                        value: false,
                                        ignoreFieldChange: true
                                    });

                                }

                                //setting selling price(rate)

                                currentRec.setCurrentSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'rate',
                                    value: sellingPrice,
                                    ignoreFieldChange: true
                                });

                                currentRec.setCurrentSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'custcol_netu_selling_price',
                                    value: sellingPrice,
                                    ignoreFieldChange: true
                                });

                                //calculating grand total(amount)
                                var grandTotal = sellingPrice * quantity;
                                // console.log('grandTotal',grandTotal);

                                currentRec.setCurrentSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'amount',
                                    value: grandTotal,
                                    ignoreFieldChange: true
                                });
                                currentRec.setCurrentSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'custcol_netu_selling_gross',
                                    value: grandTotal,
                                    ignoreFieldChange: true
                                });


                                currentRec.commitLine({
                                    sublistId: 'item'
                                });

                                //grandSum = grandSum + parseFloat(grandTotal);
                                var taxGross = currentRec.getSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'grossamt',
                                    line: i
                                });

                                //console.log('----taxGross==='+taxGross);
                                grandSum = grandSum + parseFloat(taxGross);

                            }
                        }
                    }


                    if (priceValue == 0) {
                        //if((itemadd!='Free items')&&(!idIncome))
                        if (!idIncome) {
                            var actualP = currentRec.getCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'custcol_netu_actual_cost_price'
                            });
                            //console.log('actualP',actualP);

                            var perCheckk = currentRec.getValue({
                                fieldId: 'custbody_netu_increment_perc_checkbox'
                            });

                            if (perCheckk) {
                                var incrementPern = parseFloat(increment * actualP) / 100;
                                var sellingPrn = parseFloat(incrementPern) +
                                    parseFloat(actualP);
                                sellingPriceNew = parseFloat(sellingPrn).toFixed(2);

                                //Setting true in item line
                                currentRec.setCurrentSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'custcol_netu_increment_percentage',
                                    value: true,
                                    ignoreFieldChange: true
                                });


                            } else if (!perCheck) {
                                sellingPriceNew = parseFloat(increment) +
                                    parseFloat(actualP);

                                currentRec.setCurrentSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'custcol_netu_increment_percentage',
                                    value: false,
                                    ignoreFieldChange: true
                                });

                            }
                            var sellingGrossAmnt = parseFloat(sellingPriceNew) * parseFloat(quantity);
                            //console.log('sellingGrossAmnt',sellingGrossAmnt);
                            sellingGrossAmntNew = parseFloat(sellingGrossAmnt).toFixed(2);

                            currentRec.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'custcol_netu_selling_price',
                                value: sellingPriceNew,
                                ignoreFieldChange: false
                            });
                            currentRec.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'custcol_netu_selling_gross',
                                value: sellingGrossAmntNew,
                                ignoreFieldChange: true
                            });
                        }
                    }
                    
                }
                    else
                    	{
                    currentRec.commitLine({
                        sublistId: 'item'
                    });
                    	}
                }

            } catch (e) {
                console.log(e.message);
            }
        }


        //Show an alert when profit is not greater than zero.
        function saveRecord(scriptContext) {
            try {
                //costChngSaveflag=0;

                var currentRec = scriptContext.currentRecord;
                var id = scriptContext.currentRecord.id;
                
                
                var total = currentRec.getValue({
                    fieldId: 'total'
                });
                var salesGross = currentRec.getValue({
                    fieldId: 'custbody_netu_sales_gross_amount'
                });
                
                if(total != salesGross)
                	{
                	alert('Please select the first item line and click on the OK button .  The  Sales Gross Amount must be equal to the Summary Sub Total Amount');
                	return false;
                	}


                var classtyp = currentRec.getValue({
                    fieldId: 'class'
                });

                var formId = currentRec.getValue({
                    fieldId: 'customform'
                });

                var afterCharge = currentRec.getValue({
                    fieldId: 'custbody_netu_sales_net_amnt_charges'
                });
                if (afterCharge < 0) {
                    alert('Total cannot be negative');
                    return false;
                }



                //getting the profit validation check box value based on the class.
                if (formId == 100) {
                    var profitValidation = search.lookupFields({
                        type: search.Type.CLASSIFICATION,
                        id: classtyp,
                        columns: ['custrecord_netu_no_profit_validation']
                    });


                    //console.log('profitValidation',profitValidation);
                    var incAcc = profitValidation.custrecord_netu_no_profit_validation;

                    if (!incAcc) {
                        var profitAmnt = currentRec.getValue({
                            fieldId: 'custbody_netu_profit_amount'
                        });

                        if (profitAmnt <= 0) {
                            alert('profit Validation Failed');
                            return false;
                        }
                    }

                }

                //getting the line count
                var count = currentRec.getLineCount({
                    sublistId: 'item'
                });
                // to get the feild select- checked or not

                var checked = [];
                //var checkedTrue=0;
                for (var i = 0; i < count; i++) {
                    checked[i] = currentRec.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_select',
                        line: i
                    });

                    // to get the item id which is checkbox true
                    if (checked[i] == true) {

                        dialog.alert({
                            title: 'Alert',
                            message: 'To add Optional/ Free / Additional item click "Set Optional" button ,To save please clear the select box'
                        });
                        return false;

                        //checkedTrue = 1;
                    }
                }

                return true;
            } catch (e) {
                console.log(e.message);
            }

        }

        /*
         * Function to change the sub job status in all related records
         */
        function changeStatus(subjobId, st) {

            try {

                //Setting the url of the suitelet script 
                var output = url.resolveScript({
                    scriptId: 'customscript_netu_sl_change_status',
                    deploymentId: 'customdeploy_netu_sl_change_status',
                    returnExternalUrl: false,
                }) + '&subJobId=' + subjobId + '&statusNo=' + st;

                //console.log('SL:', output);

                https.get({
                    url: output
                });

            } catch (e) {
                console.log(e.message);
            }

        }


        /*
         * Function to Update Offer Received Date
         * Create and open Sales Order
         * Change the Sub-job status
         */
        function CustomerOrderConfirmed() {

            try {
            	
                //Getting current record id
                var currentRec = currentRecord.get();
                var id = currentRec.id;
                //  console.log('id '+id);


                var quotedtls = search.lookupFields({
                    type: record.Type.ESTIMATE,
                    id: id,
                    columns: ['custbody_netu_purchase_requisition', 'custbody_netu_subjob' /*, 'custbody_netu_main_job', 'entity'*/ ]
                });

                var reqId = quotedtls.custbody_netu_purchase_requisition[0].value;
                var subJobid = quotedtls.custbody_netu_subjob[0].value;

                var today = new Date();
                var dd = today.getDate();
                var mm = today.getMonth() + 1;
                var yyyy = today.getFullYear();
                today = dd + '/' + mm + '/' + yyyy;

                //Change the Sub-job status, Confirm Date, Form field values in Quotation 
                record.submitFields({
                    type: record.Type.ESTIMATE,
                    id: id,
                    values: {
                        //'custbody_netu_subjob_status': '6',
                        'custbody_netu_confirmation_date': today
                        //'customform': 115
                    }
                });

                document.getElementById("custpage_customer_confirm_btn").disabled = true;
                window.location.reload(true);


            } catch (e) {
                console.log(e.message);
                //alert(e.message);
            }
        }

        function validateLine(scriptContext) {
            try {

                var i = 0;
                var CurrRecord = scriptContext.currentRecord;

                var linNum = CurrRecord.getLineCount({
                    sublistId: 'item'
                });
                // to create internal id for new
                var isNull = CurrRecord.getCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'custcol_netu_item_id'
                });

                if (linNum == 0 && isNull == 'null') {

                    // for creating Internal id

                    CurrRecord.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_item_id',
                        value: i
                    });
                    CurrRecord.setCurrentSublistText({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_optional_addi_free',
                        text: 'Normal',
                        ignoreFieldChange: true,
                        fireSlavingSync: true
                    });
                    i++;
                    return true;
                }

                // inserting a line in the sublist already exist
                else {

                    // to get latest internal Id  in the field
                    var value = [],
                        parsedValue, i;
                    var parsedArray = [];

                    for (i = 0; i < linNum; i++) {
                        //get the value in the field
                        value[i] = CurrRecord.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_item_id',
                            line: i
                        });

                    }
                    //console.log('value ' + value);
                    //to parse the value
                    for (i = 0; i < linNum; i++) {
                        if (checkForParameter(value[i])) {
                            parsedValue = parseInt(value[i]);
                            parsedArray.push(parsedValue);
                        } else {
                            continue;

                        }

                    }
                    //to sort in descending order
                    var swap = 0;
                    for (var c = 0; c < (linNum - 1); c++) {
                        for (var d = 0; d < linNum - c - 1; d++) {

                            if (parsedArray[d] < parsedArray[d + 1]) {
                                swap = parsedArray[d];
                                parsedArray[d] = parsedArray[d + 1];
                                parsedArray[d + 1] = swap;
                            }
                        }
                    }
                    //console.log('Sorted parsedArray ' + parsedArray);
                    // Now parsedArray[linNum-1] contain the largest value
                    var latestValue = parsedArray[0];
                    //console.log('latestValue ' + latestValue);
                    var k = latestValue++;
                    var No = k + 1;
                    // set value 
                    if (isNull == 'null') {

                        CurrRecord.setCurrentSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_item_id',
                            value: No
                        });
                        CurrRecord.setCurrentSublistText({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_optional_addi_free',
                            text: 'Normal',
                            ignoreFieldChange: true,
                            fireSlavingSync: true
                        });

                    }

                    return true;

                }

            } catch (e) {
                console.log(e.message);
            }


        }




        /** calls the button action for set an optional item   **/

        function addOptional() {
            try {
                // to get the current line no:
                var CurrRecord = currentRecord.get();
                var checked = [],
                    arrayForAdditional = [],
                    arrayForFree = [],
                    i, lineNum, linNum, checkedTrue = 0,
                    totalOptional = 0,
                    totalAdditional = 0,
                    totalFree = 0,
                    isChecked = 0;
                // to get total line no
                linNum = CurrRecord.getLineCount({
                    sublistId: 'item'
                });

                var increment = CurrRecord.getValue({
                    fieldId: 'custbody_netu_increment'
                });

                var percent = CurrRecord.getValue({
                    fieldId: 'custbody_netu_increment_perc_checkbox'
                });
                
                for (i = 0; i < linNum; i++) {
                    checked[i] = CurrRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_select',
                        line: i
                    });
                    //console.log("cheked=", checked[i]);
                    var itemLine;
                    // to get the item id which is checkbox true
                    if (checked[i] == true) {
                        isChecked = 1;
                        itemLine = i;
                        var itemID = CurrRecord.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_item_id',
                            line: i
                        });

                        var itemPrice = CurrRecord.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_purch_price',
                            line: i
                        });
                        var itemClass = CurrRecord.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'item',
                            line: i
                        });
                        var line = i;
                        break;
                    }
                }
               
                var array = [];

                // pop up new sl window
                if (isChecked == 1) {
                    var id = itemID + '-';


                    for (i = 0; i < linNum; i++) {
                        // to get the total no.of optional item

                        var optional = CurrRecord.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_item_id',
                            line: i
                        });
                        // to get the total additional item
                        if (optional.includes("@")) {
                            var part2Additional = optional.split("@");
                            arrayForAdditional.push(part2Additional[1]);
                        }

                        // to get the total free item
                        if (optional.includes("#")) {
                            var part2Free = optional.split("#");
                            arrayForFree.push(part2Free[1]);
                        }

                        if (optional.startsWith(id)) {
                            var part2 = optional.split("-");
                            array.push(part2[1]);
                            if (itemPrice == 0) {
                                var priceMinimum = CurrRecord.getSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'custcol_netu_purch_price',
                                    line: i
                                });
                                if (priceMinimum != 0) {
                                    itemPrice = priceMinimum;
                                    itemLine = i;
                                }
                            }
                        }
                    }
                    var arrayLength = array.length;
                    if (arrayLength != 0) {
                        //sort array
                        array.sort(function(a, b) {
                            return b - a
                        });
                        //var val=JSON.stringify(array[0]);
                        totalOptional = ++array[0];
                    }

                    var additioanlLength = arrayForAdditional.length;
                    if (additioanlLength != 0) {
                        //sort array
                        arrayForAdditional.sort(function(a, b) {
                            return b - a
                        });
                        //var val=JSON.stringify(array[0]);
                        totalAdditional = ++arrayForAdditional[0];
                    }

                    var freeLength = arrayForFree.length;
                    if (freeLength != 0) {
                        //sort array
                        arrayForFree.sort(function(a, b) {
                            return b - a
                        });
                        //var val=JSON.stringify(array[0]);
                        totalFree = ++arrayForFree[0];
                    }

                    // console.log("totalOptional=", totalOptional);
                    var urlToSl = url.resolveScript({
                        scriptId: "customscript_netu_sl_itemoptions_form",
                        deploymentId: "customdeploy_netu_sl_itemoptions_form",
                        returnExternalUrl: false,
                        params: {

                            lineNum: line,
                            itemid: itemID,
                            price: itemPrice,
                            itemclass: itemClass,
                            increment: increment,
                            percent: percent,
                            totalOptional: totalOptional,
                            itemLine: itemLine,
                            totalAdditional: totalAdditional,
                            totalFree: totalFree
                        }
                    });

                    window.open(urlToSl, " ", "toolbar=yes,scrollbars=yes,resizable=yes");
                } else {
                    dialog.alert({
                        title: 'Alert',
                        message: 'You Must select atleast 1 item.'
                    });
                }
            } catch (e) {
                console.log("error@add optional send=", e.message);
            }

        }
        /** calls the button action for set an optional item ----ENDS   **/


        /** calls the button action for edit an optional item----ENDS   **/


        /*
         * AU ENDS*/

        /*
         * Function to check the existence of the customer reference
         */
        function getJobsWithCustomerReference(customerRef, customer, vessel, subjob, recId, mainjobNo) {

            try {

                //console.log('customerRef, recId, customer, vessel',customerRef+', '+recId+', '+customer+', '+vessel); 
                var isExists = false;
                var isExistsFlag = 0;
                if (recId == '') {
                    recId = 0;
                }

                if (customer == '') {
                    customer = 0;
                }

                if (vessel == '') {
                    vessel = 0;
                }

                //Check for Existence only if the Reference field is not empty
                
                console.log('mainjobNo',mainjobNo);

                if (customerRef != '') {
                    var jobSearch = search.create({
                        type: "customrecord_netu_main_job",
                        filters: [
                            [
                                ["custrecord_netu_customer", "anyof", customer], "AND", ["custrecord_netu_vessel", "anyof", vessel]
                            ],
                            "AND", 
                            ["internalidnumber","notequalto", mainjobNo],
                            "AND",
                            [
                                ["custrecord_netu_customer_reference", "is", customerRef], "OR", ["custrecord_netu_2nd_reference", "is", customerRef]
                            ]
                        ],
                        columns: [
                            search.createColumn({
                                name: "name",
                                sort: search.Sort.ASC,
                                label: "ID"
                            }),
                            search.createColumn({ name: "custrecord_netu_vessel", label: "Vessel" }),
                            search.createColumn({ name: "custrecord_netu_subjob_vendor", label: "Vendor" })
                        ]
                    });


                    var jobResults = jobSearch.run().getRange({
                        start: 0,
                        end: 10
                    });
                    isExists = false;
                    if (jobResults != null) {
                        if (jobResults.length > 0) {
                            var ref = jobResults[0].getValue({
                                name: "name"
                            });
                            ref = 'Main Job# ' + ref;
                            isExists = true;
                            isExistsFlag = 1;

                            return ref;
                        }
                    }

                    //********************************

                    var jobSearch = search.create({
                        type: "customrecord_netu_sub_job",
                        filters: [
                            [
                                ["custrecord_netu_subjob_customer", "anyof", customer], "AND", ["custrecord_netu_subjob_vessel", "anyof", vessel]
                            ],
                            "AND", 
                            ["custrecord_netu_main_job.internalidnumber","notequalto",mainjobNo],
                            "AND",
                            [
                                ["custrecord_netu_subjob_customer_ref", "is", customerRef], "OR", ["custrecord_netu_subjob_cust_2nd_ref", "is", customerRef]
                            ]
                        ],
                        columns: [
                            search.createColumn({
                                name: "name",
                                sort: search.Sort.ASC,
                                label: "ID"
                            }),
                            search.createColumn({ name: "custrecord_netu_subjob_vessel", label: "Vessel" }),
                            search.createColumn({ name: "custrecord_netu_subjob_vendor_2", label: "Vendor" })
                        ]
                    });


                    var jobResults = jobSearch.run().getRange({
                        start: 0,
                        end: 10
                    });
                    isExists = false;
                    if (jobResults != null) {
                        if (jobResults.length > 0) {
                            var ref = jobResults[0].getValue({
                                name: "name"
                            });
                            ref = 'Sub Job# ' + ref;
                            isExists = true;
                            isExistsFlag = 1;
                            return ref;
                        }
                    }

                    //******************************************


                    var jobSearch = search.create({
                        type: "estimate",
                        filters: [
                            ["type", "anyof", "Estimate"],
                            "AND",
                            ["custbody_netu_customer", "anyof", customer],
                            "AND",
                            ["custbody_netu_vessel", "anyof", vessel],
                            "AND", 
                            ["custbody_netu_main_job.internalidnumber","notequalto",mainjobNo],
                            //["internalidnumber", "notequalto", recId],
                            "AND",
                            [
                                ["custbody_netu_customer_reference", "is", customerRef],
                                "OR",
                                ["custbody_netu_customer_2nd_ref", "is", customerRef]
                            ]
                        ],
                        columns: [
                            search.createColumn({
                                name: "tranid",
                                sort: search.Sort.ASC,
                                label: "ID"
                            }),
                            search.createColumn({ name: "custbody_netu_vessel", label: "Vessel" }),
                            //search.createColumn({name: "custrecord_netu_subjob_vendor", label: "Vendor"})
                        ]
                    });



                    var jobResults = jobSearch.run().getRange({
                        start: 0,
                        end: 10
                    });
                    console.log('jobResults Quote', jobResults);
                    isExists = false;
                    if (jobResults != null) {
                        if (jobResults.length > 0) {
                            var ref = jobResults[0].getValue({
                                name: "tranid"
                            });
                            ref = 'Quotation# ' + ref;
                            isExistsFlag = 1;
                            return ref;

                        }
                    }

                }

                if (isExistsFlag == 0) {
                    return isExists;
                }


            } catch (e) {
                console.log(e.message);
            }

        }



        function sendQuotation() {
            try {
                document.getElementById("custpage_customer_quotation_btn").disabled = true;

                //Getting current record id
                var currentRec = currentRecord.get();
                var id = currentRec.id;
                var temp = null;
                var quotedtls = search.lookupFields({
                    type: record.Type.ESTIMATE,
                    id: id,
                    columns: ['custbody_netu_customer_contac', 'custbody_netu_customer_contact_cc', 'custbody_netu_subjob_type']
                });

                if (quotedtls.custbody_netu_subjob_type != null) {
                    var subType = quotedtls.custbody_netu_subjob_type[0].value;
                }
                if (subType == 1) {
                    temp = 18;
                } else if (subType == 2) {
                    temp = 16;
                }

                console.log('quotedtls', quotedtls);


                var customerId = null;
                var customerIdcc = null;
                var recipientId = null;
                var recipientCC = null;

                var custId = quotedtls.custbody_netu_customer_contac[0];
                //getting Customer contact
                if ((custId == null) || (custId == "") || (custId == undefined)) {
                    alert('Customer contact is missing');
                    setTimeout(function() { document.getElementById("custpage_customer_quotation_btn").disabled = false; }, 100);
                    return false;
                } else {
                    customerId = custId.value;

                    console.log('customerId', customerId);


                    var custDtls = search.lookupFields({
                        type: search.Type.CONTACT,
                        id: customerId,
                        columns: ['email']
                    });
                    console.log('custDtls', custDtls.email);

                    if ((custDtls.email == null) || (custDtls.email == "") || (custDtls.email == undefined)) {
                        // alert('Email is missing for the Customer Contact');
                        setTimeout(function() { document.getElementById("custpage_customer_quotation_btn").disabled = false; }, 100);
                        //return false;
                    } else {
                        recipientId = custDtls.email;
                    }

                    console.log(recipientId);
                }

                var custCCId = quotedtls.custbody_netu_customer_contact_cc[0];

                //getting customer contact cc
                if ((custCCId == null) || (custCCId == "") || (custCCId == undefined)) {
                    // alert('Customer contact cc is missing');
                    recipientCC = '';
                } else {
                    customerIdcc = custCCId.value;
                    console.log('customerIdcc', customerIdcc);

                    var custDtlscc = search.lookupFields({
                        type: search.Type.CONTACT,
                        id: customerIdcc,
                        columns: ['email']
                    });
                    console.log('custDtlscc', custDtlscc.email);
                    if ((custDtlscc.email == null) || (custDtlscc.email == "") || (custDtlscc.email == undefined)) {
                        // alert('Email is missing for the Customer Contact CC');
                    } else {
                        recipientCC = custDtlscc.email;
                    }


                    console.log(recipientCC);
                }

                //Setting the url of the suitelet script 
                var output = url.resolveScript({
                    scriptId: 'customscript_netu_sl_send_quotation',
                    deploymentId: 'customdeploy_netu_sl_send_quotation',
                    returnExternalUrl: false,
                }) + '&recId=' + id + '&custemailId=' + customerId + '&custemailIdCC=' + recipientCC + '&sendStatus=1' + '&temp=' + temp + '&subType=' + subType;


                //Opens url on a new Window
                newWindow = window.open(output, 'netsuite', 'menubar=1,resizable=1,width=740,height=800');

                //After newWindow Closed reload the Quote page
                var timer = setInterval(function() {
                    if (newWindow.closed) {
                        //console.log('Reload');
                        clearInterval(timer);
                        window.location.reload(true);
                    }
                }, 1000);



            } catch (e) {
                console.log(e.message);
            }
        }

        /*
         * Function to open a suitelet for sub job selection to cancel
         */
        function cancelSubjob() {

            try {

                //Getting current record id
                var currentRec = currentRecord.get();
                var id = currentRec.id;

                var mainjobDtls = search.lookupFields({
                    type: search.Type.ESTIMATE,
                    id: id,
                    columns: ['custbody_netu_main_job']
                });
                var mainnjobNo = mainjobDtls.custbody_netu_main_job[0].value;
                console.log(mainnjobNo);

                //Setting the url of the suitelet script 
                var output = url.resolveScript({
                    scriptId: 'customscript_netu_sl_subjob_select',
                    deploymentId: 'customdeploy_netu_sl_subjob_select',
                    returnExternalUrl: false,
                }) + '&recId=' + mainnjobNo + '&type=2';

                //Opens url on a new Window
                newWindow = window.open(output, 'netsuite', 'menubar=1,resizable=1,width=1200,height=800');


            } catch (e) {
                console.log(e.message);
            }


        }

        //trigger from suitelet when user clicks the cancel sub job button
        function Closesuitelet() {

            try {
                //Close suitelet Window
                newWindow = window.close();

            } catch (e) {
                console.log(e.message);
            }

        }

        //trigger from suitelet when user clicks the cancel sub job button to change the selected sub job status to cancel
        function ChangeToCancel() {
            try {

                //document.getElementById("custpage_cancel").disabled = true; 
                jQuery('#tr_custpage_cancel').css('opacity', '0.5').css('pointer-events', 'none');
                //document.getElementById("custpage_load_img").style.visibility ='visible';

                var subjobRecord = currentRecord.get();
                var numLines = subjobRecord.getLineCount({
                    sublistId: 'custpage_subjob_sublist'
                });

                var flag = 0;
                var sel = 0;
                var subjobId = null;
                var subjobno = numLines;
                var count = 0;
                var resp = 0;
                var st = '20';

                for (var j = 0; j < numLines; j++) {

                    //getting value from checked box
                    var check = subjobRecord.getSublistValue({
                        fieldId: 'custpage_subjob_select',
                        sublistId: 'custpage_subjob_sublist',
                        line: j
                    });

                    if (check) {
                        count++;
                    }

                }
                if (count == 0) {
                    alert('Please select atleast one subjob');
                } else {
                    jQuery(".uir-page-title").append('<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"><div class="w3-light-grey" style="width:50%;margin-left:25%;border-radius: 25px;"> <div id="myBar" class="w3-container w3-blue" style="height:16px;width:1%;border-radius: 25px;"></div> </div><br>')

                }

                var elem = document.getElementById("myBar");
                var width = 1;
                for (var i = 0; i < numLines; i++) {


                    //getting value from checked box
                    var check = subjobRecord.getSublistValue({
                        fieldId: 'custpage_subjob_select',
                        sublistId: 'custpage_subjob_sublist',
                        line: i
                    });

                    var subjob = subjobRecord.getSublistValue({
                        fieldId: 'custpage_subjob_internal_id',
                        sublistId: 'custpage_subjob_sublist',
                        line: i
                    });
                    console.log(subjob);

                    if ((check) && ((subjob != "") && (subjob != null) && (subjob != undefined))) {

                        sel = sel + 1;
                        flag = 1;

                        subjobId = subjobRecord.getSublistValue({
                            fieldId: 'custpage_subjob_internal_id',
                            sublistId: 'custpage_subjob_sublist',
                            line: i
                        });

                        subjobReason = subjobRecord.getSublistValue({
                            fieldId: 'custpage_subjob_reason',
                            sublistId: 'custpage_subjob_sublist',
                            line: i
                        });

                        width++;

                        //Change the Sub job status to Cancel
                        var submitFieldsPromise = record.submitFields.promise({
                            type: 'customrecord_netu_sub_job',
                            id: subjobId,
                            values: {
                                'custrecord_netu_subjob_status': st,
                                'custrecord_netu_subjob_reason_code': subjobReason
                            }
                        });


                        submitFieldsPromise.then(function(subjobId) {
                            console.log((width * 30) + '%');
                            elem.style.width = (width * 20) + '%';

                            //Setting the url of the suitelet script 
                            var output = url.resolveScript({
                                scriptId: 'customscript_netu_sl_change_status',
                                deploymentId: 'customdeploy_netu_sl_change_status',
                                returnExternalUrl: false,
                            }) + '&subJobId=' + subjobId + '&statusNo=' + st;
                           
                            https.get.promise({
                                    url: output
                                }).then(function(response) {

                                    console.log(response.body);
                                    if (response.body == "success") { resp++; }

                                    if (resp == count) {
                                        if (window.onbeforeunload) {
                                            window.onbeforeunload = function() {
                                                null;
                                            };
                                        };

                                        newWindow = window.close();
                                        if (window.opener != null && !window.opener.closed) {
                                            window.opener.location.reload();
                                        }
                                    }

                                })
                                .catch(function onRejected(reason) {
                                    console.log(reason)
                                })


                        }, function(e) {
                            log.error({
                                title: e.name,
                                details: e.message
                            });
                        });
                    } else if ((check) && ((subjob == "") || (subjob == null) || (subjob == undefined))) {

                        subjobno = subjobno - 1;

                    }
                }

                //If all subjob status are selected then also change status in main job
                if (sel == subjobno) {

                    var jobDtls = search.lookupFields({
                        type: 'customrecord_netu_sub_job',
                        id: subjobId,
                        columns: ['custrecord_netu_main_job']
                    });

                    var jodId = jobDtls.custrecord_netu_main_job[0].value;
                    console.log(jodId);

                    record.submitFields({
                        type: 'customrecord_netu_main_job',
                        id: jodId,
                        values: {
                            'custrecord_netu_job_status': '4'
                        }
                    });
                }
                setTimeout(function() { document.getElementById("custpage_cancel").disabled = false; }, 100);
                
            } catch (e) {
                console.log(e.message);
            }
        }


        return {
            pageInit: pageInit,
            fieldChanged: fieldChanged,
            sublistChanged: sublistChanged,
            validateField: validateField,
            validateLine: validateLine,
            lineInit: lineInit,
            getRemoveList: getRemoveList,
            addOptional: addOptional,
            changeStatus: changeStatus,
            CustomerOrderConfirmed: CustomerOrderConfirmed,
            saveRecord: saveRecord,
            checkForParameter: checkForParameter,
            sendQuotation: sendQuotation,
            cancelSubjob: cancelSubjob,
            ChangeToCancel: ChangeToCancel,
            Closesuitelet: Closesuitelet
        };

    });

Leave a comment

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