Custom and standard actions in Sales Order.

Jira code: UMAR 45

This is a client script defining different functions in Sales Order. 1) Removing standard buttons based on the transaction status. 2) Setting values based on the current exchange rate. 3) Removing the item, a line based on some condition 4) Disabling the fields 5) Setting values in the field change of price, amount.

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

/**
 * Script Description: This script defining the function of button   
 * created po.Edited for adding custom fields.
 */

/*******************************************************************************
 * * UMAR WSR * *
 * **************************************************************************
 * Date:23/2/18 
 * Script name: NetU CS SO Btn Action
 * Script id: customscript_netu_cs_so_btnaction
 * Deployment id: customdeploy_netu_cs_so_btnaction
 * Applied to: Sales Order
 * @Created By JJ
 * 
 *Status : working with aj code edited by au
 * Revised on 25/6/2018 for Lock Create PO button
 * Revised on 28/6/2018 for update the approvers details in the new fields
 * Revised on 7/9/2018 for Disabling the Item Line Buttons
 ******************************************************************************/



define(['N/currentRecord', 'N/record', 'N/email', 'N/runtime', 'N/search', 'N/url', 'N/https', 'N/error'],

    function(currentRecord, record, email, runtime, search, url, https, e) {


        /**
         * 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
         */

        var flag = null;
        var refFlag = null;


        function checkif(singleitem) {

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

        function pageInit(scriptContext) {
            try {

                var currRecord = scriptContext.currentRecord;
                var mode = scriptContext.mode;
                var tranStatus = currRecord.getValue({
                    fieldId: 'status'
                });
                console.log('mode',mode);

               // log.debug('tranStatus', tranStatus);

                var userRole = runtime.getCurrentUser().role;
                var user = runtime.getCurrentUser().id;

                if (userRole != 3) {

                    var formTypeId = currRecord.getValue({
                        fieldId: 'customform'
                    });

                    if (formTypeId == 113) {
                        document.getElementById("tbl_item_insert").remove();
                        document.getElementById("tbl_item_copy").remove();


                        var getFields = ['item', 'amount', 'custcol_netu_optional_addi_free', 'custcol_netu_purch_gross_amount', 'taxcode_display', 'taxcode', 'tax1amt',
                            'custcol_netu_purch_price', 'custcol_netu_selling_price', 'description', 'grossamt', 'quantity', 'rate', 'units', 'taxrate1', 'custcol_netu_part_number',
                            'custcol_netu_increment', 'custcol_netu_increment_percentage', 'custcol_netu_delivery_time_type', 'altsalesamt'
                        ];

                        for (var k = 0; k < 20; k++) {
                            var objField = currRecord.getSublistField({
                                sublistId: 'item',
                                fieldId: getFields[k],
                                line: 0
                            });

                            objField.isDisabled = true;
                        }


                        if ((tranStatus == 'Pending Fulfillment') || (tranStatus == 'Billed') || (tranStatus == 'Partially Fulfilled') ||
                            (tranStatus == 'Closed') || (tranStatus == 'Pending Billing')) {
                            document.getElementById("tbl_item_remove").remove();
                        }
                    }
                }   


                if (mode == 'copy') {
                    var exRate = currRecord.getValue({
                        fieldId: 'exchangerate'
                    });

                    //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 = currRecord.getValue({
                            fieldId: fields[i]
                        });
                        value = checkif(value);
                        
                        var setvalue = parseFloat(value) * parseFloat(exRate);
                        setvalues = parseFloat(setvalue).toFixed(2);
                                
                        currRecord.setValue({
                            fieldId: setFields[i],
                            value: setvalues
                        });
                    }
                    
                    //Setting the invoicing company
                    var invoiceType = currRecord.getValue({
                        fieldId: 'custbody_netu_invoice_type'
                    });
                    var subsidiary = currRecord.getValue({
                        fieldId: 'subsidiary'
                    });
                    var customer = currRecord.getValue({
                        fieldId: 'entity'
                    });
                    
                    if( ((invoiceType == 1) || (invoiceType == 3)) && (subsidiary == 2))//invoice or both and umar
                    {
                    	 currRecord.setValue({
                             fieldId: 'custbody_netu_invoicing_company',
                             value: 44679  
                         });
                    }
                    else if( ((invoiceType == 1) || (invoiceType == 3)) && (subsidiary == 3))//invoice or both and wsr
                	{
                    	currRecord.setValue({
                    		 fieldId: 'custbody_netu_invoicing_company',
                             value: 44680  
                         });
                	}
                    else if(invoiceType == 2)//commission invoice
                    {
                    	 currRecord.setValue({
                    		 fieldId: 'custbody_netu_invoicing_company',
                             value: customer
                         });
                    }
                    
                    
                    //setting the altsales value in item line in the  record creation
                    var prfitAmnt = currRecord.getValue({
                        fieldId: 'custbody_netu_profit_amount'
                    });
                    prfitAmnt = checkif(prfitAmnt);
                    if (prfitAmnt != 0) {
                        var altsales = parseFloat(prfitAmnt) - ((parseFloat(prfitAmnt) * 12.5) / 100);
                        var lineNumforAlt = currRecord.getLineCount({
                            sublistId: 'item'
                        });
                        
                        altsales = parseFloat(altsales);

                        for (var a = 0; a < lineNumforAlt; a++) {
                        	console.log('altsales',altsales)


                            currRecord.selectLine({
                                sublistId: 'item',
                                line: a
                            });
                            // set data
                            currRecord.setCurrentSublistValue({
                                sublistId: 'item',
                                fieldId: 'altsalesamt',
                                value: altsales,
                                ignoreFieldChange: true,
                                fireSlavingSync: false
                            });

                            //commit line
                            currRecord.commitLine({
                                sublistId: 'item'
                            });
                        }
                    }
                    
                    
                    console.log('altsales22')


                }

                /*
                 * AU STARTS*/


                jQuery("#item_remove").click(function() {

                    var itemid = currRecord.getCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_item_id'
                    });

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

                    var removeList = getRemoveList(currRecord);

                    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 = currRecord.findSublistLineWithValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_item_id',
                            value: removeList[i]
                        });
                        // remove line
                        if (trueLineNumber > -1) {
                            currRecord.removeLine({
                                sublistId: 'item',
                                line: trueLineNumber,
                                ignoreRecalc: true
                            });
                        }
                    }




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

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


                        // to get the option of each  items
                        options[i] = currRecord.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 = currRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'custcol_netu_actual_cost_price',
                                line: i
                            });
                            actualPrice.push(actPrice);

                        }

                        // to get the min  actual price 
                    }
                    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 = currRecord.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_netu_item_id',
                            line: i
                        });
                        actPrice = currRecord.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;
                        }
                    }

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

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

                    var percent = currRecord.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 set the min value
                    // to select the line
                    currRecord.selectLine({
                        sublistId: 'item',
                        line: lineNumber
                    });
                    // set data
                    currRecord.setCurrentSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_purch_price',
                        value: minimumActualPrice,
                        ignoreFieldChange: true,
                        fireSlavingSync: true
                    });

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

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

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

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

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

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

                });

                //enabling the approvers based on the current user role if not administrator
                if ((userRole != 3) && (tranStatus == 'Pending Fulfillment')) {

                    console.log('pending inn');
                    var employeeSearchObj = search.create({
                        type: "employee",
                        filters: [
                            ["internalidnumber", "equalto", user],
                            "AND",
                            ["custentity_netu_quote_approver", "anyof", "1", "2", "3", "4", "6"]
                        ],
                        columns: [
                            search.createColumn({
                                name: "entityid",
                                sort: search.Sort.ASC,
                                label: "Name"
                            }),
                            search.createColumn({ name: "custentity_netu_quote_approver", label: "Quote Approver" })
                        ]
                    });
                    var searchResultCount = employeeSearchObj.runPaged().count;
                    if (searchResultCount != 0) {
                        var approverResult = employeeSearchObj.run().getRange({
                            start: 0,
                            end: 1
                        });
                        approveId = approverResult[0].getValue({
                            name: 'custentity_netu_quote_approver'
                        });

                        if (approveId == 1) {

                            var objField3 = currRecord.getField({
                                fieldId: 'custbody_netu_manager_1'
                            });
                            var email3 = currRecord.getField({
                                fieldId: 'custbody_netu_manager1_email'
                            });
                            objField3.isDisabled = false;
                            email3.isDisabled = false;

                        } else if (approveId == 2) {
                            var objField4 = currRecord.getField({
                                fieldId: 'custbody_netu_manager_2'
                            });
                            var email4 = currRecord.getField({
                                fieldId: 'custbody_netu_manager2_email'
                            });
                            objField4.isDisabled = false;
                            email4.isDisabled = false;

                        } else if (approveId == 3) {
                            var objField1 = currRecord.getField({
                                fieldId: 'custbody_netu_sales_spervisor'
                            });
                            var email1 = currRecord.getField({
                                fieldId: 'custbody_netu_salessupervisor_email'
                            });
                            objField1.isDisabled = false;
                            email1.isDisabled = false;

                        } else if (approveId == 4) {
                            var objField2 = currRecord.getField({
                                fieldId: 'custbody_netu_financial_controller'
                            });
                            var email2 = currRecord.getField({
                                fieldId: 'custbody_netu_financialcontroller_emai'
                            });
                            objField2.isDisabled = false;
                            email2.isDisabled = false;
                        } else if (approveId == 6) {
                            var objField5 = currRecord.getField({
                                fieldId: 'custbody_netu_director'
                            });
                            var email5 = currRecord.getField({
                                fieldId: 'custbody_netu_director_email'
                            });
                            objField5.isDisabled = false;
                            email5.isDisabled = false;

                        }
                    }
                }

                if (userRole == 3) {
                    var enableFields = ['custbody_netu_sales_spervisor', 'custbody_netu_financial_controller', 'custbody_netu_manager_1', 'custbody_netu_manager_2', 'custbody_netu_director',
                        'custbody_netu_salessupervisor_email', 'custbody_netu_financialcontroller_emai', 'custbody_netu_manager1_email', 'custbody_netu_manager2_email', 'custbody_netu_director_email'
                    ];

                    for (var k = 0; k < 10; k++) {
                        var enaFields = currRecord.getField({
                            fieldId: enableFields[k]
                        });
                        enaFields.isDisabled = false;
                    }
                }


                /*
                 * AU ENDS*/


            } catch (e) {
                /*log.debug({
               title: e.name,
               details: e.message
              });*/
                console.log(e.name, e.message);
            }
        }



        function lineInit(scriptContext) {
            try {

                var currentrecord = scriptContext.currentRecord;
                var userRole = runtime.getCurrentUser().role;

                //disabling the item line fields if not administrator
                /*if(userRole!=3){
        jQuery(".uir-machine-row").click(function(){
         // jQuery( ".uir-machine-row" ).focus(); 
          
          jQuery('.uir-machine-row').css('pointer-events', 'none');
          jQuery( "#item_form" ).click();
        //  window.scrollTo(0, 1);  
        });
      }*/
                //custpage_send

                var itemid = currentrecord.getCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'custcol_netu_item_id'
                });
                // if item is additional/free item normal netsuite remove
                if ((itemid.includes("_"))) {
                    console.log("extra item");
                }
                // if item is normal item trigger remove
                else {
                    // remove onclick function of standard netsuite Remove button
                    jQuery('#item_remove').attr('onclick', '');
                    // when user click on remove button 
                }
            } catch (e) {
                console.log("error@lininit=", e.message);
            }


        }

        function fieldChanged(scriptContext) {

            try {

                var currentRec = scriptContext.currentRecord;
                //based on the field change of values from purchase requisition
                if ((scriptContext.sublistId == 'item') && (scriptContext.fieldId == 'quantity')) {
                    try {
                        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'
                            });
                            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);
                        }

                        var grossSum = calculateGrossSum(currentRec);

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

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

                }




                if (scriptContext.fieldId == 'custbody_netu_so_freight_change') {
                    try {

                        var freightChange = currentRec.getValue({
                            fieldId: 'custbody_netu_so_freight_change'
                        });
                        freightChange = checkif(freightChange);

                        var subjob = currentRec.getValue({
                            fieldId: 'custbody_netu_subjob'
                        });
                        var purchaseorderSearchObj = search.create({
                            type: "purchaseorder",
                            filters: [
                                ["type", "anyof", "PurchOrd"],
                                "AND",
                                ["custbody_netu_subjob", "anyof", subjob],
                                "AND",
                                ["mainline", "is", "T"]
                            ],
                            columns: [
                                search.createColumn({ name: "internalid", label: "Internal ID" })
                            ]
                        });
                        var searchResultCount = purchaseorderSearchObj.runPaged().count;
                        if (searchResultCount > 0) {
                            var poResults = purchaseorderSearchObj.run().getRange({
                                start: 0,
                                end: 1
                            });

                            poId = poResults[0].getValue({
                                name: 'internalid'
                            });

                            record.submitFields({
                                type: record.Type.PURCHASE_ORDER,
                                id: poId,
                                values: {
                                    'custbody_netu_so_freight_change': freightChange
                                },
                                options: {
                                    enableSourcing: false,
                                    ignoreMandatoryFields: true
                                }
                            });
                        }



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

                }



                if ((scriptContext.sublistId == 'item') && (scriptContext.fieldId == 'custcol_netu_purch_price')) {
                    try {
                        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
                        });

                        rateAndTotal(currentRec);
                        var grossSum = calculateGrossSum(currentRec);

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

                        salesfields(currentRec, grossSum);
                        costRecalculation(currentRec);
                        profit(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
                        });


                        var grossSum = calculateGrossSum(currentRec);

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

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


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




                var fieldId = scriptContext.fieldId;

                //based on the field change approver check box adding the email id in the corresponding field
                if ((fieldId == 'custbody_netu_sales_spervisor') || (fieldId == 'custbody_netu_financial_controller') ||
                    (fieldId == 'custbody_netu_manager_1') || (fieldId == 'custbody_netu_manager_2') || (fieldId == 'custbody_netu_director')) {

                    var app_Val = currentRec.getValue({
                        fieldId: fieldId
                    });

                    if (app_Val == true) {

                        var userObj = runtime.getCurrentUser();
                        var userObjEmail = userObj.email;

                        if (fieldId == 'custbody_netu_sales_spervisor') {
                            var app_Val = currentRec.setValue({
                                fieldId: 'custbody_netu_salessupervisor_email',
                                value: userObjEmail
                            });
                        } else if (fieldId == 'custbody_netu_financial_controller') {
                            var app_Val = currentRec.setValue({
                                fieldId: 'custbody_netu_financialcontroller_emai',
                                value: userObjEmail
                            });
                        } else if (fieldId == 'custbody_netu_manager_1') {
                            var app_Val = currentRec.setValue({
                                fieldId: 'custbody_netu_manager1_email',
                                value: userObjEmail
                            });
                        } else if (fieldId == 'custbody_netu_manager_2') {
                            var app_Val = currentRec.setValue({
                                fieldId: 'custbody_netu_manager2_email',
                                value: userObjEmail
                            });
                        } else if (fieldId == 'custbody_netu_director') {
                            var app_Val = currentRec.setValue({
                                fieldId: 'custbody_netu_director_email',
                                value: userObjEmail
                            });
                        }

                    } else {



                        if (fieldId == 'custbody_netu_sales_spervisor') {
                            var app_Val = currentRec.setValue({
                                fieldId: 'custbody_netu_salessupervisor_email',
                                value: null
                            });
                        } else if (fieldId == 'custbody_netu_financial_controller') {
                            var app_Val = currentRec.setValue({
                                fieldId: 'custbody_netu_financialcontroller_emai',
                                value: null
                            });
                        } else if (fieldId == 'custbody_netu_manager_1') {
                            var app_Val = currentRec.setValue({
                                fieldId: 'custbody_netu_manager1_email',
                                value: null
                            });
                        } else if (fieldId == 'custbody_netu_manager_2') {
                            var app_Val = currentRec.setValue({
                                fieldId: 'custbody_netu_manager2_email',
                                value: null
                            });
                        } else if (fieldId == 'custbody_netu_director') {
                            var app_Val = currentRec.setValue({
                                fieldId: 'custbody_netu_director_email',
                                value: null
                            });
                        }

                    }

                }


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

        }


        //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'
                });

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

                if ((increment == "") || (increment == null) || (increment == undefined)) {
                    increment = '0';
                }

                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'
                    });


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

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

                    if ((incrementnew == "") || (incrementnew == null) || (incrementnew == undefined)) {
                        incrementnew = '0';
                    }


                    //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);


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


                    } 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.message);
            }
        }


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

        function sublistChanged(scriptContext) {

            try {

                var currentRec = scriptContext.currentRecord;
                var grossSum = calculateGrossSum(currentRec);
                costRecalculation(currentRec);

                //setting the sales gross sum
                currentRec.setValue({
                    fieldId: 'custbody_netu_sales_gross_amount',
                    value: grossSum
                });
                salesfields(currentRec, grossSum);
                //profit(currentRec);
                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);
                var profit = parseFloat(profit).toFixed(2);

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

                var profitPercentage = (profit / parseFloat(sellingPrice)) * 100;
                profitPercentage = checkif(profitPercentage);
                profitPercentage = parseFloat(profitPercentage).toFixed(2);
                
                currentRec.setValue({
                    fieldId: 'custbody_netu_profit_perc',
                    value: profitPercentage
                });
                /*
                var count = currentRec.getLineCount({
                  sublistId : 'item'
                });
                console.log('count',count);
                var lineNum = currentRec.selectLine({
                    sublistId: 'item',
                    line: count-1
                });
                lineNum.setCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'amount',
                    value: '120',
                    ignoreFieldChange: true
                });
                lineNum.commitLine({
                    sublistId: 'item'
                });*/

            } 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);
            }
        }



        //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
                    });
                    console.log('incId',incId);
                    
                    if (!incId) {
                        var amount = currentRec.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'grossamt',
                            line: i
                        });
                        amount = checkif(amount);
                        grossSum = grossSum + parseFloat(amount);
                        console.log('grossSum',grossSum);
                    }
                }
                return grossSum;

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







        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 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);
                //profit(currentRec); 
            } catch (e) {
                console.log(e);
            }



        }




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

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

                vCommiAmnt = parseFloat(vCommiAmnt).toFixed(2);
                //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'
                });
                var afterDiscV = currentRec.getValue({
                    fieldId: 'custbody_netu_cost_discount_amount'
                });
                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 vCommiAmntBase = parseFloat(netAmntV) * parseFloat(purExV);
                vCommiAmntBase = parseFloat(vCommiAmntBase).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_net_amount_b',
                    value: vCommiAmntBase,
                    ignoreFieldChange: true
                });

                packingFreight(currentRec);
                // profit(currentRec);

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

        }




        //(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'
                });


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

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



                if ((venodrPacking == "") || (venodrPacking == null) || (venodrPacking == undefined)) {

                    venodrPacking = '0';

                }

                if ((vendorfreight == "") || (vendorfreight == null) || (vendorfreight == undefined)) {
                    vendorfreight = '0';
                }




                //setting venodrPacking(base)
                var venodrPackingBase = parseFloat(purEx) * parseFloat(venodrPacking);
                currentRec.setValue({
                    fieldId: 'custbody_netu_v_packing_charges_b',
                    value: venodrPackingBase,
                    ignoreFieldChange: true
                });



                //setting vendorfreight(base)
                var vendorfreightBase = parseFloat(purEx) * parseFloat(vendorfreight);
                currentRec.setValue({
                    fieldId: 'custbody_netu_v_freight_b',
                    value: vendorfreightBase,
                    ignoreFieldChange: true
                });


                var costNetAmtAfterchange = parseFloat(costGrossSum) + parseFloat(venodrPacking) + parseFloat(vendorfreight);
                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_net_amnt_charges',
                    value: costNetAmtAfterchange,
                    ignoreFieldChange: true
                });


                //setting costNetAmtAfterchange(base)
                var costNetAmtAfterchangeBase = parseFloat(purEx) * parseFloat(costNetAmtAfterchange);
                costNetAmtAfterchangeBase = parseFloat(costNetAmtAfterchangeBase).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custbody_netu_cost_net_amnt_charges_b',
                    value: costNetAmtAfterchangeBase,
                    ignoreFieldChange: true
                });

                // profit(currentRec);


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


        }



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

            try {

                var excRate = currentRec.getValue({
                    fieldId: 'exchangerate'
                });
                var salesGrossBase = parseFloat(excRate) * parseFloat(grossSum); //custbody_netu_sales_gross_amount_b

                var discPer = currentRec.getValue({
                    fieldId: 'custbody_netu_c_discount_perc'
                });
                discPer = checkif(discPer);
                var packHandling = currentRec.getValue({
                    fieldId: 'custbody_netu_packing_charges'
                });

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


                var salediscAmount = (grossSum * parseFloat(discPer)) / 100; //custbody_netu_sales_discount_amount

                var discountbase = parseFloat(excRate) * parseFloat(salediscAmount); //custbody_netu_sales_discount_amount_b

                var netAmount = parseFloat(grossSum) - parseFloat(salediscAmount); //custbody_netu_sales_net_amount

                var netBase = parseFloat(excRate) * parseFloat(netAmount); //custbody_netu_sales_net_amount_b

                var salesNetAmtAfterCharge = parseFloat(netAmount) + parseFloat(packHandling) + parseFloat(freight); //custbody_netu_sales_net_amnt_charges

                var salesAfterChargeBase = parseFloat(excRate) * parseFloat(salesNetAmtAfterCharge); //custbody_netu_sales_net_amnt_charges_b

                var calcFieldSales = [salesGrossBase, salediscAmount, discountbase, netAmount, netBase, salesNetAmtAfterCharge, salesAfterChargeBase];
                var setFileldsSales = ['custbody_netu_sales_gross_amount_b', 'custbody_netu_sales_discount_amount', '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 g = 0; g < 7; g++) {

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



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

        }


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

            try {

                //Setting the url of the suitelet script 
                var output = url.resolveScript({
                    scriptId: 'customscript_netu_sl_change_status_save',
                    deploymentId: 'customdeploy_netu_sl_change_status_save',
                    returnExternalUrl: true,
                }) + '&subJobId=' + subjobId + '&statusNo=' + st + '&recordId=' + id + '&recordtype=' + recordtype;


                console.log('SL', output);

                https.get({
                    url: output
                });


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

        }


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

            try {

                var currRecord = scriptContext.currentRecord;
                var classtyp = currRecord.getValue({
                    fieldId: 'class'
                });
                /*var count = currRecord.getLineCount({
        sublistId : 'item'
      });
        //getting the last line item id
      var itemidIncome = currRecord.getSublistValue({
          sublistId: 'item',
          fieldId: 'custcol_netu_incomeid',
          line: count-1
      });
      
      //fetching discount
      var discGL = currRecord.getValue({
        fieldId : 'custbody_netu_sales_discount_amount'
      });
      if((discGL=="")||(discGL==null)||(discGL==undefined))
      {
        discountGL=0;
      }
      else
      {
        discountGL=-discGL; 
      }
      
        //updating the discount value when a line deleted
        if(itemidIncome)
      {
          var line = currRecord.selectLine({
            sublistId: 'item',
            line: count-1
        });
          
        //inserting a new line.
        line.setCurrentSublistValue({
          sublistId : 'item',
          fieldId : 'amount',
          value : discountGL,
          ignoreFieldChange : true
        });
        line.setCurrentSublistValue({
                    sublistId : 'item',
                    fieldId : 'quantity',
                    value : null,
                    ignoreFieldChange : true
                });
                line.setCurrentSublistValue({
                    sublistId : 'item',
                    fieldId : 'units',
                    value : null,
                    ignoreFieldChange : true
                });
        
        line.commitLine({
          sublistId : 'item'
        });
        
      }
        var flag=true;
        */
                //***************************************************************************       
                /*search.lookupFields.promise({
                type: search.Type.CLASSIFICATION,
                id: classtyp,
                columns : ['custrecord_netu_no_profit_validation']
                })
                
           .then(function (result) {
                log.debug({
                    details: "Completed: " + result
                });
             var incAcc=profitValidation.custrecord_netu_no_profit_validation;
                
                var profitAmount=currRecord.getValue({
                  fieldId: 'custbody_netu_profit_amount'
                });
                


                if(!incAcc)
                  {
                  if(profitAmount>0){
                    
                    //savecheck(currRecord,paymentType);
                    flag=true;
                    
                  }
                  else{
                      
                      alert('Profit Validation Failed');
                      flag=false;
                    }
                    
                  }
                else
                  {
                  //savecheck(currRecord,paymentType);
                  flag=true;
                  }
                
                
                    return flag;
             
              })
           .catch(function onRejected(reason) {
                
                });
        
        */


                //*****************************************************************************     
                //getting the profit validation check box value based on the class.


                var formTypeId = currRecord.getValue({
                    fieldId: 'customform'
                });

                if (formTypeId == 113) {

                    var profitValidation = search.lookupFields({
                        type: search.Type.CLASSIFICATION,
                        id: classtyp,
                        columns: ['custrecord_netu_no_profit_validation']
                    });
                    var incAcc = profitValidation.custrecord_netu_no_profit_validation;

                    var profitAmount = currRecord.getValue({
                        fieldId: 'custbody_netu_profit_amount'
                    });

                    if (!incAcc) {
                        if (profitAmount > 0) {
                            flag = true;
                        } else {
                            alert('Profit Validation Failed');
                            flag = false;
                        }

                    } else {
                        flag = true;
                    }


                    return flag;
                } else {
                    return true;
                }


                //********************************************************************
            } catch (e) {
                console.log(e.message);
            }
        }
        
        
        /*
         * Function defining the action of PUrchase Order button
         */
        function createPO() {

            try {
                document.getElementById("custpage_so_purchaseOrder_btn").disabled = true;
                var currentRec = currentRecord.get();
                var id = currentRec.id;

                //Setting the url of the suitelet script that coping items
                var output = url.resolveScript({
                    scriptId: 'customscript_netu_sl_create_po',
                    deploymentId: 'customdeploynetu_sl_create_po',
                    returnExternalUrl: false
                }) + '&quoteID=' + id;

                window.location = output;

            } 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'
                });
                sellingPrice = checkif(sellingPrice);
                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);
                profitPercentage = parseFloat(profitPercentage).toFixed(2);

                currentRec.setValue({
                    fieldId: 'custbody_netu_profit_perc',
                    value: profitPercentage,
                    ignoreFieldChange: true
                });
            } catch (e) {
                console.log(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))) {
                        console.log("count if inn");
                        count++;
                        console.log("itemid=", other_itemid);

                    }
                }
                console.log("count=", count);
                for (var i = 0; i < lineNum; i++) {
                    other_itemid = currentrecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_netu_item_id',
                        line: i
                    });

                    console.log("other_itemid=", other_itemid);
                    if ((count == 1) && (isNormal == 1)) {
                        if (other_itemid.startsWith(itemid_)) {
                            removeList.push(other_itemid);
                        }
                    }

                }

                return removeList;

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


        //complete button action(send action)
        function completeAction() {

            try {

                jQuery('#tr_custpage_complete').css('opacity', '0.7').css('pointer-events', 'none');
                jQuery('#tr_secondarycustpage_complete').css('opacity', '0.7').css('pointer-events', 'none');

                var currRecord = currentRecord.get();
                var id = currRecord.id;
                var recordtype = currRecord.type;

                var subJobid = currRecord.getValue({
                    fieldId: 'custbody_netu_subjob'
                });

                currRecord.setValue({
                    fieldId: 'custbody_netu_subjob_status',
                    value: '17',
                    ignoreFieldChange: true
                });

                st = '17';
                //changeStatus(subJobid,st);
                changeStatus(subJobid, st, id, recordtype);
                jQuery('#tbl_secondarycustpage_proforma_invoice').show();
                jQuery('#tbl_custpage_proforma_invoice').show();

                jQuery('#tbl_secondarycustpage_packing_list').show();
                jQuery('#tbl_custpage_packing_list').show();

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

        function rejectOrder() {
            try {

                var currRecord = currentRecord.get();
                var id = currRecord.id;
                var recordtyp = currRecord.type;
                var emailApprove = null;
                var approverNm = null;

                var userId = runtime.getCurrentUser().id;
                var senderId = userId;

                var cnfm = confirm("Do you want to continue with reject order?");
                if (cnfm == true) {

                    jQuery('#tdbody_custpage_reject_order_btn').css('opacity', '0.5').css('pointer-events', 'none');

                    var salesorderdtls = search.lookupFields({
                        type: record.Type.SALES_ORDER,
                        id: id,
                        columns: ['custbody_netu_subjob']
                    });

                    if (salesorderdtls.custbody_netu_subjob != null) {
                        subjobId = salesorderdtls.custbody_netu_subjob[0].value;
                        console.log('subjobId', subjobId);
                    }


                    record.submitFields({
                        type: record.Type.SALES_ORDER,
                        id: id,
                        values: {
                            custbody_netu_subjob_status: '25',
                            orderstatus: 'A'
                        },
                        options: {
                            enableSourcing: false,
                            ignoreMandatoryFields: true
                        }
                    });

                    var st = 25;


                    var employeeSearchObj = search.create({
                        type: "employee",
                        filters: [
                            ["custentity_netu_quote_approver", "anyof", "2", "1"]
                        ],
                        columns: [
                            search.createColumn({
                                name: "entityid",
                                sort: search.Sort.ASC,
                                label: "Name"
                            }),
                            search.createColumn({ name: "email", label: "Email" }),
                            search.createColumn({ name: "altemail", label: "Alt. Email" }),
                            search.createColumn({ name: "custentity_netu_quote_approver", label: "Quote Approver" })
                        ]
                    });
                    var searchResultCount = employeeSearchObj.runPaged().count;
                    if (searchResultCount != 0) {
                        var employeeResults = employeeSearchObj.run().getRange({
                            start: 0,
                            end: 100
                        });

                        for (var k = 0; k < searchResultCount; k++) {
                            emailApprove = employeeResults[k].getValue({
                                name: 'email'
                            });

                            approverNm = employeeResults[k].getValue({
                                name: "entityid",
                                sort: search.Sort.ASC
                            });

                            email.send({
                                author: senderId,
                                recipients: emailApprove,
                                subject: 'Credit Limit Alert',
                                body: 'Hi,<br><br> The sales order ' + id + ' has been rejeted by ' + approverNm + '.<br><br>Thank You<br>Team UMAR',

                            });
                        }
                    }

                    window.location.reload();
                    changeStatus(subjobId, st, id, recordtyp)
                }

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


        function validateDelete(scriptContext) {
            try {

                //Disallowing the removal of Packing, Fright and Discount Item Lines
                var CurrRecord = scriptContext.currentRecord;


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

                console.log('income_ID', income_ID);

                if (income_ID == 1 || income_ID == 2 || income_ID == 3) {
                    return false;
                } else {
                    return true;
                }

            } catch (e) {
                console.log(e.message);
            }
        }
        
        
        function proformaBtnAction(){
        	
        	try {
        		
        		  var currentRec = currentRecord.get();
                  var id = currentRec.id;

                  var quotedtls = search.lookupFields({
                      type: record.Type.SALES_ORDER,
                      id: id,
                      columns: ['custbody_netu_customer_contac', 'custbody_netu_customer_contact_cc']
                  });

                  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=10';


                  //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);
    		}
        	
        }


        return {
            pageInit: pageInit,
            lineInit: lineInit,
            fieldChanged: fieldChanged,
            sublistChanged: sublistChanged,
            validateDelete: validateDelete,
            changeStatus: changeStatus,
            createPO: createPO,
            saveRecord: saveRecord,
            getRemoveList: getRemoveList,
            completeAction: completeAction,
            rejectOrder: rejectOrder,
            proformaBtnAction: proformaBtnAction
        };

    });

Leave a comment

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