Jira code: UMAR-19
This script is for 
- setting a button ‘Unable To Quote’, ‘Create Requisition’, ‘Requisition Reminder’, ‘Offer Received Date’ in the Requisition record’s View mode
- setting a button ‘Calculate Total’ in edit mode
- setting a button ‘Create S/Q’ in the Requisition record’s View mode if offer received from vendor
- Disabling all button in some statuses
User Event Script
/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 * @NModuleScope SameAccount
 */
/**
 * Script Description: This script is for setting a button 'Unable To Quote' in the Requisition record's View mode
 * setting a button 'Create Requisition' in the Requisition record's View mode
 * setting a button calculate total in edit mode
 * setting a button 'Requisition Reminder' in the Requisition record's View mode
 * adding the button 'Offer Received Date'
 * setting a button 'Create S/Q' in the Requisition record's View mode if offer received from vendor
 * REvised on 23/4/18 for disabling all button in some statuses
 */
/*******************************************************************************
 * * UMAR WSR * *
 * **************************************************************************
 * Date:13/2/18 
 * Script name: NetU UE Requisition Btns
 * Script id: customscript_netu_ue_requisition_btns
 * Deployment id: customdeploy_netu_ue_requisition_btns
 * Applied to: Requisition
 * 
 ******************************************************************************/
//test
define(['N/record', 'N/search', 'N/ui/serverWidget', 'N/runtime'],
    function(record, search, serverWidget, runtime) {
        /**
         * Function definition to be triggered before record is loaded.
         *
         * @param {Object} scriptContext
         * @param {Record} scriptContext.newRecord - New record
         * @param {string} scriptContext.type - Trigger type
         * @param {Form} scriptContext.form - Current form
         * @Since 2015.2
         */
        function beforeLoad(scriptContext) {
            try {
                var CustRec = scriptContext.form;
                var recId = scriptContext.newRecord.id;
                log.debug({
                    title: 'recId',
                    details: recId
                });
                //getting the current status
                var sta = search.lookupFields({
                    type: 'customrecord_netu_purchase_requisition',
                    id: recId,
                    columns: ['custrecord_netu_req_sub_job_status']
                });
                var status = sta.custrecord_netu_req_sub_job_status[0].value;
                //Getting The role of current User
                var userRole = runtime.getCurrentUser().role;
                log.debug("Internal ID of current user role: " + userRole);
                if (scriptContext.type == 'view') {
                    //Loading Client Script
                    CustRec.clientScriptFileId = 1653;
                    //Set a Requisition Reminder button and Provide the action for the button by calling the function in client script  
                    var reqRemin = CustRec.addButton({
                        id: 'custpage_requisition_reminder',
                        label: 'Requisition Reminder',
                        functionName: 'SendRequisitionReminder'
                    });
                    //Set a Send Requisition button and Provide the action for the button by calling the function in client script
                    var sendRQ = CustRec.addButton({
                        id: 'custpage_send_requisition',
                        label: 'Send Requisition',
                        functionName: 'SendRequisition'
                    });
                    //offer Received date button 
                    var offerDate = CustRec.addButton({
                        id: 'custpage_receiveddate_btn',
                        label: 'Offer Received Date',
                        functionName: 'DateNow'
                    });
                    //Set a Unable To Quote button and Provide the action for the button by calling the function in client script
                    var unableToQuote = CustRec.addButton({
                        id: 'custpage_unable_to_quote',
                        label: 'Unable To Quote',
                        functionName: 'ChangeToUnableToQuote'
                    });
                    //Set a Create S/Q button and Provide the action for the button by calling the function in client script
                    var buttonSQ = CustRec.addButton({
                        id: 'custpage_create_sq_btn',
                        label: 'Create S/Q',
                        functionName: 'CreateSQ'
                    });
                    buttonSQ.isDisabled = true;
                    //Set a Create S/Q button and Provide the action for the button by calling the function in client script
                    var rqDtls = search.lookupFields({
                        type: 'customrecord_netu_purchase_requisition',
                        id: recId,
                        columns: ['custrecord_netu_req_rfq_date', 'custrecord_netu_req_offer_received_date', 'custrecord_netu_req_sub_job_status', 'custrecord_netu_req_net_amount']
                    });
                    var rqDate = rqDtls.custrecord_netu_req_rfq_date[0];
                    var netAmt = rqDtls.custrecord_netu_req_net_amount;
                    var rqReceived = rqDtls.custrecord_netu_req_offer_received_date[0];
                    var sbStatus = null;
                    if (rqDtls.custrecord_netu_req_sub_job_status != null) {
                        sbStatus = rqDtls.custrecord_netu_req_sub_job_status[0].value;
                    }
                    //Disabling the Offer Received Date and Requisition Reminder buttons until Requisition is not send  
                    if (rqDate == null) {
                        offerDate.isDisabled = true;
                        reqRemin.isDisabled = true;
                    }
                    //Disabling the Send Requisition button if RFQ Date is not null(After Sending PR)  
                    if ((rqDate != null)) {
                        sendRQ.isDisabled = true;
                    }
                    /*Requisition Reminder, Send Requisition and Offer Received Date buttons are deactivated 
                     *when the RFQ Date and RFQ Received Date are not blank and the Sub Job status is above Requisition
                     */
                    if ((rqDate != null) && (rqReceived != null) && (3 <= sbStatus <= 22)) {
                        reqRemin.isDisabled = true;
                        sendRQ.isDisabled = true;
                        offerDate.isDisabled = true;
                    }
                    log.debug({
                        title: 'netAmt',
                        details: netAmt
                    });
                    //Disabling the Offer Received Date if Transaction cost is null  
                    if (netAmt == null || netAmt == '' || netAmt == undefined) {
                        offerDate.isDisabled = true;
                    }
                    //Searching for any Open Quotation for this quotation
                    var quotationSearchObj = search.create({
                        type: "transaction",
                        filters: [
                            ["type", "anyof", "Estimate"],
                            "AND",
                            ["custbody_netu_purchase_requisition", "anyof", recId],
                            "AND",
                            ["mainline", "is", "T"]
                        ],
                        columns: [
                            "mainline",
                            search.createColumn({
                                name: "trandate",
                                sort: search.Sort.ASC
                            }),
                            "type",
                            "tranid",
                            "entity"
                        ]
                    });
                    var searchResultCount = quotationSearchObj.runPaged().count;
                    //Create SQ button is enabled if offer is received and sub job status is Offer
                    if ((rqDate != null) && (rqReceived != null) && ((sbStatus == 3) || (searchResultCount <= 0))) {
                        buttonSQ.isDisabled = false;
                    }
                    //Requisition Reminder button is enabled if offer is not received
                    if ((rqDate != null) && (rqReceived == null)) {
                        reqRemin.isDisabled = false;
                    }
                    //disabling all buttons in view mode if status is order lost,unable to quote, sub job cancelled
                    if ((status == 10) || (status == 4) || (status == 20)) {
                        reqRemin.isDisabled = true;
                        sendRQ.isDisabled = true;
                        offerDate.isDisabled = true;
                        unableToQuote.isDisabled = true;
                        buttonSQ.isDisabled = true;
                    }
                }
                if (scriptContext.type == scriptContext.UserEventType.EDIT) {
                    //Loading Client Script
                    CustRec.clientScriptFileId = 1653;
                    var currentReco = scriptContext.newRecord;
                    var id = currentReco.id;
                    //Searching for any Open Quotation for this quotation
                    var quotationSearchObj = search.create({
                        type: "transaction",
                        filters: [
                            ["type", "anyof", "Estimate"],
                            "AND",
                            ["custbody_netu_purchase_requisition", "anyof", id],
                            "AND",
                            ["mainline", "is", "T"]
                        ],
                        columns: [
                            "mainline",
                            search.createColumn({
                                name: "trandate",
                                sort: search.Sort.ASC
                            }),
                            "type",
                            "tranid",
                            "entity"
                        ]
                    });
                    var searchResultCount = quotationSearchObj.runPaged().count;
                    log.debug({
                        title: 'searchResultCount',
                        details: searchResultCount + ',' + userRole
                    });
                    if (userRole != 3) {
                        //removing edit button on anothor roles once a Quotation is created
                        if ((searchResultCount > 0) || ((status == 10) || (status == 4) || (status == 20))) {
                            //disabling the sub tabs if the status is order lost or cancel and Not Administrator Role.
                            var jobField1 = CustRec.addField({
                                id: 'custpage_jobid',
                                type: 'INLINEHTML',
                                label: 'Job Id'
                            });
                            var html = "<script>jQuery( document ).ready(function() { jQuery('#div__body').css('pointer-events', 'none'); });</script>"
                            jobField1.defaultValue = html;
                        }
                    }
                    var getComm = currentReco.getText({
                        fieldId: 'custrecord_netu_req_fixed_comm_principal'
                    });
                    if (!getComm) {
                        var vendor = currentReco.getValue({
                            fieldId: 'custrecord_netu_req_vendor'
                        });
                        //checking the vendor principle location
                        var principleLocation = search.lookupFields({
                            type: search.Type.VENDOR,
                            id: vendor,
                            columns: ['custentity_netu_principal_location', 'custentity_netu_commission_type', 'custentity_netu_discount_perc']
                        });
                        //getting the Vendor Discount
                        var vendid = principleLocation.custentity_netu_discount_perc;
                        var vendor_discount = null;
                        //var alertDisc='';
                        if ((vendid == "") || (vendid == null) || (vendid == undefined)) {
                            var alertDisc = 'Vendor discount is not defined';
                        } else {
                            var vendper = vendid.split("%");
                            vendor_discount = vendper[0];
                        }
                        //Getting the Location of main Job
                        var mainjobLocation = search.lookupFields({
                            type: 'customrecord_netu_purchase_requisition',
                            id: recId,
                            columns: ['custrecord_netu_req_location']
                        });
                        log.debug('mainjobLocation', mainjobLocation);
                        var alertMainLocation = '';
                        var alertVendorLocation = '';
                        var locationFlag = 0;
                        var fixCommission = null;
                        var jobLocationDtls = mainjobLocation.custrecord_netu_req_location;
                        var mainLocation = null;
                        if (jobLocationDtls == null || jobLocationDtls == "" || jobLocationDtls == undefined) {
                            alertMainLocation = 'Location is not defined';
                        } else {
                            //log.debug('jobLocationDtls',jobLocationDtls);
                            mainLocation = jobLocationDtls[0].value;
                            var location = principleLocation.custentity_netu_principal_location[0];
                            var prinLocation = null;
                            if (location == null || location == "" || location == undefined) {
                                alertVendorLocation = 'Principal location is not defined for the vendor at the time of creation';
                            } else {
                                //log.debug('principleLocation11',location);
                                var length = principleLocation.custentity_netu_principal_location.length;
                                //Checking whether the Vendor location and Main job location are same 
                                for (var k = 0; k < length; k++) {
                                    prinLocation = principleLocation.custentity_netu_principal_location[k].value;
                                    if (mainLocation == prinLocation) {
                                        locationFlag = 1;
                                        log.debug('locationFlag', locationFlag);
                                        break;
                                    }
                                }
                                //If locations are same gettimg the Commission
                                if (locationFlag == 1) {
                                    //getting the current class
                                    var itemClass = currentReco.getValue({
                                        fieldId: 'custrecord_netu_req_class'
                                    });
                                    //Searching the vendor commission from the vendor budget and fixed commission list.
                                    var custrecord_netu_vendor_class_commissionObj = search.create({
                                        type: "customrecord_netu_vendor_budget",
                                        filters: [
                                            ["custrecord_netu_class", "anyof", itemClass],
                                            "AND",
                                            ["custrecord_netu_vendor_budget_record", "anyof", vendor]
                                        ],
                                        columns: [
                                            "custrecord_netu_vendor_class_commission"
                                        ]
                                    });
                                    //log.debug('custrecord_netu_vendor_class_commissionObj',custrecord_netu_vendor_class_commissionObj);
                                    var vendorCommissionResultCount = custrecord_netu_vendor_class_commissionObj.runPaged().count;
                                    log.debug('vendorCommissionResultCount', vendorCommissionResultCount);
                                    if (vendorCommissionResultCount != 0) {
                                        var vendorFixedResults = custrecord_netu_vendor_class_commissionObj.run().getRange({ //start:0,
                                            start: 0,
                                            end: 1
                                        });
                                        log.debug('vendorFixedResults', vendorFixedResults);
                                        fixedCommi = vendorFixedResults[0].getValue({
                                            name: 'custrecord_netu_vendor_class_commission'
                                        });
                                        var fixedCom = fixedCommi.split("%");
                                        fixCommission = fixedCom[0];
                                        log.debug('fixCommission', fixCommission);
                                    }
                                }
                            }
                        }
                        var commObj = '{ "vendor_discount" : ' + vendor_discount + ',"alertMainLocation" : "' + alertMainLocation + '","alertVendorLocation" : "' + alertVendorLocation + '","locationFlag" : ' + locationFlag + ',"fixCommission" : ' + fixCommission + '}';
                        currentReco.setText({
                            fieldId: 'custrecord_netu_req_fixed_comm_principal',
                            text: commObj
                        });
                        log.debug('commObj', commObj);
                    }
                }
            } catch (e) {
                log.debug({
                    title: e.name,
                    details: e.message
                });
            }
        }
        return {
            beforeLoad: beforeLoad
        };
    });Client Script
/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */
/**
 * Script Description: This script defining the function of button   
 */
/*******************************************************************************
 * * UMAR WSR * *
 * **************************************************************************
 * Date:13/2/18 
 * Script name: NetU CS Req Btn Action
 * Script id: customscript_netu_cs_req_btnaction
 * Deployment id: customdeploy_netu_cs_req_btnaction
 * Applied to: Requisition
 * Revised on 21/4/2018 for vendor commission record f.c
 * Revised on 23/4/2018 for setting gross amount, quantity in the case of direct
 * Revised on 13/5/2018 for send requisition
 * Revised on 25/6/2018 for Lock Create SQ button
 * Revised on 12/9/2018 for Commission issue
 * 
 ******************************************************************************/
define(['N/currentRecord', 'N/record', 'N/email', 'N/runtime', 'N/search', 'N/url', 'N/https', 'N/error', 'N/currency', 'N/file'],
    function(currentRecord, record, email, runtime, search, url, https, e, currency, file) {
        /*
         * AJ Starts
         */
        var vendpercentage = null;
        var excRate = null;
        var locFlag = null;
        var flag = null;
        var comimflag = 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 vedorDiscFlag = 0; //vendor discount is not defined
        var commiFlag = 0; //scale commission is not defined from a specific range.
        function checkif(singleitem) {
            if (singleitem == "" || singleitem == null ||
                singleitem == undefined || isNaN(singleitem) == true) {
                return 0;
            } else {
                return singleitem;
            }
        }
        function pageInit(scriptContext) {
            try {
                console.log('Hi')
                var currentReco = scriptContext.currentRecord;
                var id = currentReco.id;
                var userRole = runtime.getCurrentUser().role;
                var currencyVendor = currentReco.getText({
                    fieldId: 'custrecord_netu_req_currency_code'
                });
                var contact = currentReco.getText({
                    fieldId: 'custrecord_netu_pur_req_vendor_contact'
                });
                if (currencyVendor != null && currencyVendor != "" && currencyVendor != undefined) {
                    //getting current exchange rate
                    excRate = currency.exchangeRate({
                        source: currencyVendor,
                        target: 'EUR',
                        date: new Date()
                    });
                }
                var rfqDate = currentReco.getValue({
                    fieldId: 'custrecord_netu_req_rfq_date'
                });
                if ((rfqDate == null || rfqDate == "" || rfqDate == undefined) && (userRole != 3)) {
                    jQuery('#recmachcustrecord_netu_pur_req_id_form').css('pointer-events', 'none');
                    jQuery('#tr_fg_fieldGroup111').css('pointer-events', 'none');
                }
                //disable field vendor discount based on status
                var status = currentReco.getValue({
                    fieldId: 'custrecord_netu_req_sub_job_status'
                });
                if ((status != 22) && (status >= 6) && (userRole != 3)) {
                    jQuery('#items_div').css('pointer-events', 'none');
                }
                if ((status < 6) || (status == 22)) {
                    var field = currentReco.getField({
                        fieldId: 'custrecord_netu_req_vendor_discount_perc'
                    });
                    field.isDisabled = false;
                } else {
                    var field = currentReco.getField({
                        fieldId: 'custrecord_netu_req_vendor_discount_perc'
                    });
                    field.isDisabled = true;
                }
            } catch (e) {
                console.log(e.message);
            }
        }
        function fieldChanged(scriptContext) {
            try {
                //setting commission in the field change of scale checkbox
                if (scriptContext.fieldId == 'custrecord_netu_req_scale_commission') {
                    try {
                        var currentRec = scriptContext.currentRecord;
                        var noCommi = null;
                        var vend = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_vendor'
                        });
                        //checking the vendor commission type
                        var vendorComtype = search.lookupFields({
                            type: search.Type.VENDOR,
                            id: vend,
                            columns: ['custentity_netu_commission_type']
                        });
                        //console.log(vendorComtype);
                        var vendorType = vendorComtype.custentity_netu_commission_type[0];
                        console.log(vendorType);
                        if (vendorType == null || vendorType == "" || vendorType == undefined) {
                            alert('The vendor type is not defined for this vendor');
                        } else {
                            noCommi = vendorType.value;
                        }
                        if (noCommi != 3) {
                            var getComm = currentRec.getText({
                                fieldId: 'custrecord_netu_req_fixed_comm_principal'
                            });
                            var getCommObj = JSON.parse(getComm);
                            var locFlagg = getCommObj.locationFlag;
                            console.log('Get commObj', locFlagg);
                            currentRec.setValue({
                                fieldId: 'custrecord_netu_commission_change',
                                value: 0,
                                ignoreFieldChange: true
                            });
                            var scaleCheck = currentRec.getValue({
                                fieldId: 'custrecord_netu_req_scale_commission'
                            });
                            if (scaleCheck) {
                                var grossAfterScale = currentRec.getValue({
                                    fieldId: 'custrecord_netu_req_total_after_discount'
                                });
                                if (grossAfterScale == null || grossAfterScale == "" || grossAfterScale == undefined) {
                                    alert('The total after discount amount is missing');
                                } else {
                                    if (locFlagg == 1) {
                                        var commissionAmt = vendorCommissionScale(currentRec, grossAfterScale);
                                        commissionAndNet(currentRec, commissionAmt);
                                    } else {
                                        currentRec.setValue({
                                            fieldId: 'custrecord_netu_req_commission_percent',
                                            value: 0,
                                            ignoreFieldChange: true
                                        });
                                        currentRec.setValue({
                                            fieldId: 'custrecord_netu_req_vendor_comm_perc',
                                            value: 0,
                                            ignoreFieldChange: true
                                        });
                                        var commissionAmt = 0;
                                        commissionAndNet(currentRec, commissionAmt);
                                    }
                                }
                            }
                            if (!scaleCheck) {
                                if (locFlagg == 1) {
                                    var commission_Amnt = vendorCommission(currentRec);
                                    commissionAndNet(currentRec, commission_Amnt);
                                } else {
                                    currentRec.setValue({
                                        fieldId: 'custrecord_netu_req_commission_percent',
                                        value: 0,
                                        ignoreFieldChange: true
                                    });
                                    currentRec.setValue({
                                        fieldId: 'custrecord_netu_req_vendor_comm_perc',
                                        value: 0,
                                        ignoreFieldChange: true
                                    });
                                    var commission_Amnt = 0;
                                    commissionAndNet(currentRec, commission_Amnt);
                                }
                            }
                        } else {
                            alert('vendor commission type is "No commission"');
                        }
                    } catch (e) {
                        console.log(e.message);
                    }
                }
                //recalculating  values in discount% field change
                if (scriptContext.fieldId == 'custrecord_netu_req_vendor_discount_perc') {
                    try {
                        var currentRec = scriptContext.currentRecord;
                        flag = 0;
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_discount_change',
                            value: 1,
                            ignoreFieldChange: true
                        });
                        var gros_Sum = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_gross_amount'
                        });
                        discount(currentRec, gros_Sum);
                        var returnCommission = commission(currentRec, gros_Sum);
                        commissionAndNet(currentRec, returnCommission);
                    } catch (e) {
                        console.log(e.message);
                    }
                }
                //setting net amount in the commission% field change
                if (scriptContext.fieldId == 'custrecord_netu_req_vendor_comm_perc') {
                    try {
                        var currentRec = scriptContext.currentRecord;
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_commission_change',
                            value: 1,
                            ignoreFieldChange: true
                        });
                        var gros_SUM = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_gross_amount'
                        });
                        var total_Aft = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_total_after_discount'
                        });
                        var commi_perc = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_vendor_comm_perc'
                        });
                        commi_perc = checkif(commi_perc);
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_req_commission_percent',
                            value: commi_perc,
                            ignoreFieldChange: true
                        });
                        var comm_Amnt = checkif((parseFloat(total_Aft) * commi_perc) / 100);
                        var comm_Amount = parseFloat(comm_Amnt).toFixed(2);
                        commissionAndNet(currentRec, comm_Amount);
                    } catch (e) {
                        console.log(e.message);
                    }
                }
                //recalculating  values in discount amount field change
                if (scriptContext.fieldId == 'custrecord_netu_req_vendor_discount_amt') {
                    try {
                        flag = 1;
                        var currentRec = scriptContext.currentRecord;
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_discount_change',
                            value: 1,
                            ignoreFieldChange: true
                        });
                        var disco_Amnt = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_vendor_discount_amt'
                        });
                        disco_Amnt = checkif(disco_Amnt);
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_req_discount_amount',
                            value: disco_Amnt,
                            ignoreFieldChange: true
                        });
                        var vend_gros = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_gross_amount'
                        });
                        var vendorPer = checkif((parseFloat(disco_Amnt) * 100) / parseFloat(vend_gros));
                        var vend_per = parseFloat(vendorPer).toFixed(2);
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_req_vendor_discount_perc',
                            value: vend_per,
                            ignoreFieldChange: true
                        });
                        discount(currentRec, vend_gros);
                        var returnCommission = commission(currentRec, vend_gros);
                        commissionAndNet(currentRec, returnCommission);
                    } catch (e) {
                        console.log(e.message);
                    }
                }
                //recalculating  values in commission amount field change
                if (scriptContext.fieldId == 'custrecord_netu_pur_req_comm_amount') {
                    try {
                        var currentRec = scriptContext.currentRecord;
                        comimflag = 1;
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_commission_change',
                            value: 1,
                            ignoreFieldChange: true
                        });
                        var com_Amnt = currentRec.getValue({
                            fieldId: 'custrecord_netu_pur_req_comm_amount'
                        });
                        com_Amnt = checkif(com_Amnt);
                        var aft_disc = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_total_after_discount'
                        });
                        var tot_gross = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_gross_amount'
                        });
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_req_commission_amount',
                            value: com_Amnt,
                            ignoreFieldChange: true
                        });
                        //var commPer = (parseFloat(com_Amnt)*100)/parseFloat(aft_disc);
                        var commPer = checkif((com_Amnt * 100) / aft_disc);
                        var vend_com_perc = parseFloat(commPer).toFixed(2);
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_req_vendor_comm_perc',
                            value: vend_com_perc,
                            ignoreFieldChange: true
                        });
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_req_commission_percent',
                            value: vend_com_perc,
                            ignoreFieldChange: true
                        });
                        commissionAndNet(currentRec, com_Amnt);
                    } catch (e) {
                        console.log(e.message);
                    }
                }
                //setting base values in currenct field change
                if (scriptContext.fieldId == 'custrecord_netu_req_currency_code') {
                    try {
                        var currentRec = scriptContext.currentRecord;
                        var curr = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_currency_code'
                        });
                        excRateNew = currency.exchangeRate({
                            source: curr,
                            target: 'EUR',
                            date: new Date()
                        });
                        excRate = excRateNew;
                        // setting cost and sales base values
                        var fields = ['custrecord_netu_req_gross_amount',
                            'custrecord_netu_req_discount_amount',
                            'custrecord_netu_req_commission_amount',
                            'custrecord_netu_req_net_amount'
                        ];
                        var setFields = ['custrecord_netu_req_gross_amount_base',
                            'custrecord_netu_req_discount_amount_base',
                            'custrecord_netu_req_commission_amt_base',
                            'custrecord_netu_req_net_amount_base'
                        ];
                        for (var i = 0; i < 4; i++) {
                            var value = currentRec.getValue({
                                fieldId: fields[i]
                            });
                            value = checkif(value);
                            var setvalue = parseFloat(value) * parseFloat(excRate);
                            setvalue = parseFloat(setvalue).toFixed(2);
                            currentRec.setValue({
                                fieldId: setFields[i],
                                value: setvalue
                            });
                        }
    
                    } catch (e) {
                        console.log(e.message);
                    }
                }
                //setting the gross amount in the sublist fieldchange.
                if (((scriptContext.sublistId == 'recmachcustrecord_netu_pur_req_id') && (scriptContext.fieldId == 'custrecord_netu_quantity')) ||
                    ((scriptContext.sublistId == 'recmachcustrecord_netu_pur_req_id') && (scriptContext.fieldId == 'custrecord_netu_pur_req_price'))) {
                    try {
                        var currentRec = scriptContext.currentRecord;
                        //calculating the gross amount based on the field change
                        var subTyp = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_sub_status'
                        });
                        if (subTyp == 2) {
                            //calculating the gross amount based on the field change
                            var sublistquantity = currentRec.getCurrentSublistValue({
                                sublistId: 'recmachcustrecord_netu_pur_req_id',
                                fieldId: 'custrecord_netu_quantity'
                            });
                            if (sublistquantity == null || sublistquantity == "" || sublistquantity == undefined) {
                                sublistquantity = 1;
                            }
                            sublistprice = currentRec.getCurrentSublistValue({
                                sublistId: 'recmachcustrecord_netu_pur_req_id',
                                fieldId: 'custrecord_netu_pur_req_price',
                            });
                            grossAmt = parseFloat(sublistquantity) * parseFloat(sublistprice);
                            //setting the gross amount
                            currentRec.setCurrentSublistValue({
                                sublistId: 'recmachcustrecord_netu_pur_req_id',
                                fieldId: 'custrecord_netu_pur_req_gross_amount',
                                value: checkif(grossAmt),
                                ignoreFieldChange: true
                            });
                        } else {
                            //calculating the gross amount based on the field change
                            var sublistquantity = currentRec.getCurrentSublistValue({
                                sublistId: 'recmachcustrecord_netu_pur_req_id',
                                fieldId: 'custrecord_netu_quantity'
                            });
                            sublistprice = currentRec.getCurrentSublistValue({
                                sublistId: 'recmachcustrecord_netu_pur_req_id',
                                fieldId: 'custrecord_netu_pur_req_price',
                            });
                            grossAmt = parseFloat(sublistquantity) * parseFloat(sublistprice);
                            //setting the gross amount
                            currentRec.setCurrentSublistValue({
                                sublistId: 'recmachcustrecord_netu_pur_req_id',
                                fieldId: 'custrecord_netu_pur_req_gross_amount',
                                value: checkif(grossAmt),
                                ignoreFieldChange: true
                            });
                        }
                    } catch (e) {
                        console.log(e.message);
                    }
                }
            } catch (e) {
                console.log(e.message);
            }
        }
        //************************************************************************************              
        function sublistChanged(scriptContext) {
            try {
                var currentRec = scriptContext.currentRecord;
                flag = 0;
                var rfq = currentRec.getValue({
                    fieldId: 'custrecord_netu_req_rfq_date'
                });
                if (rfq) {
                    var count = currentRec.getLineCount({
                        sublistId: 'recmachcustrecord_netu_pur_req_id'
                    });
                    var grossSum = 0;
                    for (var i = 0; i < count; i++) {
                        var amount = currentRec.getSublistValue({
                            sublistId: 'recmachcustrecord_netu_pur_req_id',
                            fieldId: 'custrecord_netu_pur_req_gross_amount',
                            line: i
                        });
                        amount = checkif(amount);
                        grossSum = grossSum + parseFloat(amount);
                    }
                    grossSum = parseFloat(grossSum).toFixed(2);
                    //getting the vendor currency
                    var currencyVendor = currentRec.getText({
                        fieldId: 'custrecord_netu_req_currency_code'
                    });
                    if ((currencyVendor == "") || (currencyVendor == null) || (currencyVendor == undefined)) {
                        alert('Please enter a value for currency');
                        return false;
                    }
                    //getting current exchange rate
                    excRate = currency.exchangeRate({
                        source: currencyVendor,
                        target: 'EUR',
                        date: new Date()
                    });
                    currentRec.setValue({
                        fieldId: 'custrecord_netu_req_gross_amount',
                        value: grossSum
                    });
                    //set base values
                    var grossBase = parseFloat(grossSum) * parseFloat(excRate);
                    var grossBasefix = parseFloat(grossBase).toFixed(2);
                    currentRec.setValue({
                        fieldId: 'custrecord_netu_req_gross_amount_base',
                        value: grossBasefix,
                        ignoreFieldChange: true
                    });
                    discount(currentRec, grossSum);
                    var returnCommission = commission(currentRec, grossSum);
                    // console.log('returnCommission',returnCommission);
                    commissionAndNet(currentRec, returnCommission);
                }
            } catch (e) {
                console.log(e.message);
            }
        }
        //************************************************************************************     
        function discount(currentRec, grosAmnt) {
            try {
                var disc = currentRec.getValue({
                    fieldId: 'custrecord_netu_req_vendor_discount_perc'
                });
                var vendr = currentRec.getValue({
                    fieldId: 'custrecord_netu_req_vendor'
                });
                var discChange = currentRec.getValue({
                    fieldId: 'custrecord_netu_discount_change'
                });
                var vendpercentage = null;
                //pull from record only if the percentage is null
                if (discChange != 1) {
                    if ((disc == "") || (disc == null) || (disc == undefined)) {
                        var getComm = currentRec.getText({
                            fieldId: 'custrecord_netu_req_fixed_comm_principal'
                        });
                        var getCommObj = JSON.parse(getComm);
                        var vendpercentage = getCommObj.vendor_discount;
                        console.log('Get commObj', vendpercentage);
                        if ((vendpercentage == "") || (vendpercentage == null) || (vendpercentage == undefined)) {
                            vendpercentage = 0;
                            if (vedorDiscFlag == 0) {
                                alert('vendor discount is not defined');
                            }
                            vedorDiscFlag = 1;
                        }
                        //setting the  discount percentage
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_req_vendor_discount_perc',
                            value: vendpercentage,
                            ignoreFieldChange: true
                        });
                    }
                }
                //getting disc percentage
                var vendpercentage = currentRec.getValue({
                    fieldId: 'custrecord_netu_req_vendor_discount_perc'
                });
                vendpercentage = checkif(vendpercentage);
                
                if (flag != 1) {
                    var discAmnt = (parseFloat(grosAmnt) * parseFloat(vendpercentage)) / 100;
                    var discAmntTot = parseFloat(discAmnt).toFixed(2);
                    currentRec.setValue({
                        fieldId: 'custrecord_netu_req_vendor_discount_amt',
                        value: discAmntTot,
                        ignoreFieldChange: true
                    });
                    currentRec.setValue({
                        fieldId: 'custrecord_netu_req_discount_amount',
                        value: discAmntTot,
                        ignoreFieldChange: true
                    });
                }
                var discAmntTot = currentRec.getValue({
                    fieldId: 'custrecord_netu_req_discount_amount'
                });
                var discBase = parseFloat(excRate) * parseFloat(discAmntTot);
                var discBasefix = parseFloat(discBase).toFixed(2);
                //base discount amount
                currentRec.setValue({
                    fieldId: 'custrecord_netu_req_discount_amount_base',
                    value: discBasefix,
                    ignoreFieldChange: true
                });
                var afterDiscount = parseFloat(grosAmnt) - parseFloat(discAmntTot);
                var afterDiscountTot = parseFloat(afterDiscount).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custrecord_netu_req_total_after_discount',
                    value: afterDiscountTot
                });
            } catch (e) {
                console.log(e.message);
            }
        }
        //************************************************************************************      
        //pulling commission from vendor record based on the commission  type.
        function commission(currentRec, grosAmnt) {
            try {
                var commipercentage = currentRec.getValue({
                    fieldId: 'custrecord_netu_req_commission_percent'
                });
                var commiCheck = currentRec.getValue({
                    fieldId: 'custrecord_netu_req_commission_amount'
                });
                var commiChange = currentRec.getValue({
                    fieldId: 'custrecord_netu_commission_change'
                });
                var getComm = currentRec.getText({
                    fieldId: 'custrecord_netu_req_fixed_comm_principal'
                });
                var getCommObj = JSON.parse(getComm);
                console.log("getCommObj", getCommObj);
                var locFlag = getCommObj.locationFlag;
                var alertVendor = getCommObj.alertVendorLocation;
                var alertMain = getCommObj.alertMainLocation;
                if ((alertVendor) && (vendorAlert != 1)) {
                    alert(alertVendor);
                    vendorAlert = 1;
                }
                if ((alertMain) && (mainAlert != 1)) {
                    alert(alertMain);
                    mainAlert = 1;
                }
                if (commiChange != 1) {
                    //if((commiCheck==null || commiCheck=="" || commiCheck==undefined) && (locFlag==1))
                    if (locFlag == 1) {
                        var vend = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_vendor'
                        });
                        //checking the vendor commission type
                        var vendorComtype = search.lookupFields({
                            type: search.Type.VENDOR,
                            id: vend,
                            columns: ['custentity_netu_commission_type']
                        });
                        //console.log(vendorComtype);
                        var vendorType1 = vendorComtype.custentity_netu_commission_type[0];
                        var vendorType = null;
                        if (vendorType1 == null || vendorType1 == "" || vendorType1 == undefined) {
                            alert('The vendor type is not defined for this vendor');
                        } else {
                            vendorType = vendorType1.value;
                        }
                        if (vendorType == '3') {
                            currentRec.setValue({
                                fieldId: 'custrecord_netu_req_vendor_comm_perc',
                                value: 0,
                                ignoreFieldChange: true
                            });
                            currentRec.setValue({
                                fieldId: 'custrecord_netu_pur_req_comm_amount',
                                value: 0,
                                ignoreFieldChange: true
                            });
                            currentRec.setValue({
                                fieldId: 'custrecord_netu_req_commission_percent',
                                value: 0,
                                ignoreFieldChange: true
                            });
                            var commissionAmnt = 0;
                        } else {
                            var scaleFieldValue = currentRec.getValue({
                                fieldId: 'custrecord_netu_req_scale_commission'
                            });
                            var grosAmntAfterDisc = currentRec.getValue({
                                fieldId: 'custrecord_netu_req_total_after_discount'
                            });
                            console.log('scaleFieldValue', scaleFieldValue);
                            if ((scaleFieldValue == false)) {
                                var commissionAmnt = vendorCommission(currentRec);
                            }
                            if (scaleFieldValue == true) {
                                var commissionAmnt = vendorCommissionScale(currentRec, grosAmntAfterDisc);
                            }
                        }
                    } else if (locFlag == 0) {
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_req_commission_percent',
                            value: 0,
                            ignoreFieldChange: true
                        });
                        currentRec.setValue({
                            fieldId: 'custrecord_netu_req_vendor_comm_perc',
                            value: 0,
                            ignoreFieldChange: true
                        });
                        var commissionAmnt = 0;
                        //var commissionAmnt=(parseFloat(totalAft)*parseFloat(commipercentage))/100;
                        console.log('commissionAmnt', commissionAmnt);
                    } else {
                        var totalAft = currentRec.getValue({
                            fieldId: 'custrecord_netu_req_total_after_discount'
                        });
                        //console.log(commiCheck);
                        var commissionAmnt = checkif((parseFloat(totalAft) * parseFloat(commipercentage)) / 100);
                        console.log('commissionAmnt', commissionAmnt);
                    }
                } else {
                    var totalAft = currentRec.getValue({
                        fieldId: 'custrecord_netu_req_total_after_discount'
                    });
                    //console.log(commiCheck);
                    var commissionAmnt = checkif((parseFloat(totalAft) * parseFloat(commipercentage)) / 100);
                    console.log('commissionAmnt', commissionAmnt);
                }
                //console.log('commissionAmntb4',commissionAmnt);
                commissionAmnt = parseFloat(commissionAmnt).toFixed(2);
                return commissionAmnt;
            } catch (e) {
                console.log(e.message);
            }
        }
        //************************************************************************************         
        //setting commission amount and  net amount.
        function commissionAndNet(currentRec, commissionAmnt) {
            try {
                /*if(comimflag!=1)
                {*/
                currentRec.setValue({
                    fieldId: 'custrecord_netu_req_commission_amount',
                    value: commissionAmnt,
                    ignoreFieldChange: true
                });
                currentRec.setValue({
                    fieldId: 'custrecord_netu_pur_req_comm_amount',
                    value: commissionAmnt,
                    ignoreFieldChange: true
                });
               
                //setting base values
                var commiBase = parseFloat(excRate) * parseFloat(commissionAmnt);
                var commiBasefix = parseFloat(commiBase).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custrecord_netu_req_commission_amt_base',
                    value: commiBasefix,
                    ignoreFieldChange: true
                });
                var totaFter = currentRec.getValue({
                    fieldId: 'custrecord_netu_req_total_after_discount'
                });
                totaFter = checkif(totaFter);
                var netAmnt = (parseFloat(totaFter) - parseFloat(commissionAmnt));
                netAmnt = parseFloat(netAmnt).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custrecord_netu_req_net_amount',
                    value: netAmnt,
                    ignoreFieldChange: true
                });
                var netBase = parseFloat(excRate) * parseFloat(netAmnt);
                netBase = parseFloat(netBase).toFixed(2);
                currentRec.setValue({
                    fieldId: 'custrecord_netu_req_net_amount_base',
                    value: netBase,
                    ignoreFieldChange: true
                });
            } catch (e) {
                console.log(e.message);
            }
        }
        //************************************************************************************       
        //getting vendor fixed commission based on the vendor budget and commission list
        function vendorCommission(currentReco) {
            try {
                var getComm = currentReco.getText({
                    fieldId: 'custrecord_netu_req_fixed_comm_principal'
                });
                var getCommObj = JSON.parse(getComm);
                var fix_commi = parseFloat(getCommObj.fixCommission);
              
                if (fix_commi) {
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_req_vendor_comm_perc',
                        value: fix_commi,
                        ignoreFieldChange: true
                    });
                   
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_req_commission_percent',
                        value: fix_commi,
                        ignoreFieldChange: true
                    });
                    //getting the current class
                    var afterDiscTotal = currentReco.getValue({
                        fieldId: 'custrecord_netu_req_total_after_discount'
                    });
                    var commissionAmnt = checkif((parseFloat(afterDiscTotal) * parseFloat(fix_commi)) / 100);
                    console.log('fix_commiaftr', fix_commi);
                    console.log(commissionAmnt);
                } else {
                    alert('Fixed Commission is not defined for Vendor');
                    var commissionAmnt = 0;
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_req_commission_percent',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_req_commission_amount',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_req_vendor_comm_perc',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_pur_req_comm_amount',
                        value: 0,
                        ignoreFieldChange: true
                    });
                }
                //console.log(commissionAmnt);
                //commissionAmnt = parseFloat(commissionAmnt).toFixed(2);
                return commissionAmnt;
            } catch (e) {
                console.log(e.message);
            }
        }
        //************************************************************************************      
        //  CASE WHEN 1000 between {custrecord_netu_commission_amount_from} and {custrecord_netu_commission_amount_to} THEN 1 ELSE 0 END
        //getting the commission based on the vendor commission list.
        function vendorCommissionScale(currentReco, commisionAmntscale) {
            try {
                //getting the current vendor
                var vendor = currentReco.getValue({
                    fieldId: 'custrecord_netu_req_vendor'
                });
                console.log('vendor', vendor);
                var vendorName = currentReco.getText({
                    fieldId: 'custrecord_netu_req_vendor'
                });
                var orginalTAD = commisionAmntscale;
                //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 "+commisionAmntscale+" 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"
                    ]
                });
                console.log('customrecord_netu_vendor_commissionSearchObj', customrecord_netu_vendor_commissionSearchObj);
                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
                    });
                    console.log('vendorScaleResults', vendorScaleResults);
                    var newTAD = 0;
                    var commiAmnt = 0;
                    var commiAmntNew = 0;
                    var scaleCommiPE = 0;
                    var scaleCommission = 0;
                    var amountTo = 0;
                    for (var f = 0; f < vendorScaleCommissionResultCount; f++) {
                        amountTo = vendorScaleResults[f].getValue({
                            name: 'custrecord_netu_commission_amount_to'
                        });
                        console.log('amountTo', commisionAmntscale + ',' + amountTo);
                        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) {
                                console.log('commisionAmntscale', commisionAmntscale + ',' + scaleCommission);
                                commiAmntNew = (parseFloat(commisionAmntscale) * parseFloat(scaleCommission)) / 100;
                                console.log('commiAmntNew', commiAmntNew);
                            } else {
                                commiAmntNew = scaleCommission;
                            }
                            commiAmnt = parseFloat(commiAmnt) + parseFloat(commiAmntNew);
                            console.log('commiAmnt', commiAmnt);
                            break;
                        }
                    }
                    var commiPerecenatge = (parseFloat(commiAmnt) * 100) / parseFloat(orginalTAD);
                    commiPerecenatge = parseFloat(commiPerecenatge).toFixed(2);
                    console.log('commiPerecenatge', commiPerecenatge);
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_req_vendor_comm_perc',
                        value: commiPerecenatge,
                        ignoreFieldChange: true
                    });
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_req_commission_percent',
                        value: commiPerecenatge,
                        ignoreFieldChange: true
                    });
                    return commiAmnt;
                } else {
                    alert('Scale Commission is not defined for Vendor "' + vendorName + '"');
                    var scaleComm = 0;
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_req_commission_percent',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_req_commission_amount',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_req_vendor_comm_perc',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    currentReco.setValue({
                        fieldId: 'custrecord_netu_pur_req_comm_amount',
                        value: 0,
                        ignoreFieldChange: true
                    });
                    return scaleComm;
                }
            } catch (e) {
                console.log(e.message);
            }
        }
        //offer received date button action
        function DateNow() {
            try {
                document.getElementById("custpage_receiveddate_btn").disabled = true;
                //getting current date
                var today = new Date();
                var dd = today.getDate();
                var mm = today.getMonth() + 1;
                var yyyy = today.getFullYear();
                todayy = dd + '/' + mm + '/' + yyyy;
                //Getting current record id
                var currentRec = currentRecord.get();
                var id = currentRec.id;
                var myLookupFields = search.lookupFields({
                    type: 'customrecord_netu_purchase_requisition',
                    id: id,
                    columns: ['custrecord_netu_sub_job_number', 'custrecord_netu_req_currency_code', 'custrecord_netu_req_vendor_reference']
                });
                var subid = null;
                var vendorRefernce = null;
                var purchaseCurrency = null;
                if (myLookupFields.custrecord_netu_sub_job_number[0] != null) {
                    subid = myLookupFields.custrecord_netu_sub_job_number[0].value;
                }
                if (myLookupFields.custrecord_netu_req_currency_code[0] != null) {
                    console.log(myLookupFields.custrecord_netu_req_currency_code);
                    purchaseCurrency = myLookupFields.custrecord_netu_req_currency_code[0].value;
                }
                if (myLookupFields.custrecord_netu_req_vendor_reference != null) {
                    console.log(myLookupFields.custrecord_netu_req_vendor_reference);
                    vendorRefernce = myLookupFields.custrecord_netu_req_vendor_reference;
                }
                //setting the subjob status and offer received date in purchase requisition
                record.submitFields({
                    type: 'customrecord_netu_purchase_requisition',
                    id: id,
                    values: {
                        custrecord_netu_req_sub_job_status: '3',
                        custrecord_netu_req_offer_received_date: todayy
                    },
                    options: {
                        enableSourcing: false,
                        ignoreMandatoryFields: true
                    }
                });
                //setting the subjob status in record subjob.
                record.submitFields({
                    type: 'customrecord_netu_sub_job',
                    id: subid,
                    values: {
                        custrecord_netu_subjob_status: '3',
                        custrecord_netu_subjob_currency_code: purchaseCurrency,
                        custrecord_netu_subjob_vendor_ref: vendorRefernce
                    },
                    options: {
                        enableSourcing: false,
                        ignoreMandatoryFields: true
                    }
                });
                window.location.reload(true);
                alert('The status and date has been updated');
                var st = '3';
                changeStatus(subid, st);
            } catch (e) {
                console.log(e.message);
            }
        }
        //return true only if the currency field is filled
        function validateLine(scriptContext) {
            try {
                var currentRec = scriptContext.currentRecord;
                var rfqDate = currentRec.getValue({
                    fieldId: 'custrecord_netu_req_rfq_date'
                });
                if (rfqDate) {
                    //getting the vendor currency
                    var currencyVendor = currentRec.getText({
                        fieldId: 'custrecord_netu_req_currency_code'
                    });
                    //getting type
                    var subType = currentRec.getValue({
                        fieldId: 'custrecord_netu_req_sub_status'
                    });
                    //calculating the gross amount based on the field change
                    var quantityVendor = currentRec.getCurrentSublistValue({
                        sublistId: 'recmachcustrecord_netu_pur_req_id',
                        fieldId: 'custrecord_netu_quantity'
                    });
                    var priceVendor = currentRec.getCurrentSublistValue({
                        sublistId: 'recmachcustrecord_netu_pur_req_id',
                        fieldId: 'custrecord_netu_pur_req_price',
                    });
                    if ((currencyVendor == "") || (currencyVendor == null) || (currencyVendor == undefined)) {
                        alert('Please enter currency');
                        return false;
                    }
                    if ((priceVendor == "") || (priceVendor == null) || (priceVendor == undefined)) {
                        alert('item price is missing');
                        return false;
                    }
                    //if parts
                    if (subType == 1) {
                        if ((quantityVendor == "") || (quantityVendor == null) || (quantityVendor == undefined)) {
                            alert('item quantity is missing');
                            return false;
                        }
                        if ((currencyVendor) && (priceVendor) && (quantityVendor)) {
                            console.log('hhhh');
                            return true;
                        }
                    } else {
                        if ((currencyVendor) && (priceVendor)) {
                            return true;
                        }
                    }
                }
                return true;
            } catch (e) {
                console.log(e.message);
            }
        }
        /*
         * Function to send a Requisition Reminder Email
         */
        function SendRequisitionReminder() {
            try {
                document.getElementById("custpage_requisition_reminder").disabled = true;
                console.log('Test1');
                //Getting current record id
                var currentRec = currentRecord.get();
                var id = currentRec.id;
                var userId = runtime.getCurrentUser().id;
                console.log(userId);
                var senderId = userId;
                var vendorId = null;
                var vendorIdcc = null;
                var recipientId = null;
                var recipientCC = null;
                var sendReqId = null;
                var prDtls = search.lookupFields({
                    type: 'customrecord_netu_purchase_requisition',
                    id: id,
                    columns: ['custrecord_netu_pur_req_vendor_contact', 'custrecord_netu_pur_req_vendor_contactcc','custrecord_netu_send_req_mail_id']
                });
                
                if(prDtls.custrecord_netu_send_req_mail_id != null)
                	{
                	sendReqId = prDtls.custrecord_netu_send_req_mail_id;
                	}
                var venId = prDtls.custrecord_netu_pur_req_vendor_contact[0];
                //getting vendor contact
                if ((venId == null) || (venId == "") || (venId == undefined)) {
                    alert('vendor contact is missing');
                    setTimeout(function() { document.getElementById("custpage_requisition_reminder").disabled = false; }, 1000);
                    return false;
                } else {
                    vendorId = venId.value;
                    console.log('vendorId', vendorId);
                    var vendDtls = search.lookupFields({
                        type: search.Type.CONTACT,
                        id: vendorId,
                        columns: ['email']
                    });
                    if ((vendDtls.email == null) || (vendDtls.email == "") || (vendDtls.email == undefined)) {
                        //alert('Email is missing for the Vendor Contact');
                        setTimeout(function() { document.getElementById("custpage_requisition_reminder").disabled = false; }, 1000);
                        // return false;
                    } else {
                        recipientId = vendDtls.email;
                    }
                }
                var venCCId = prDtls.custrecord_netu_pur_req_vendor_contactcc[0];
                //getting vendor contact cc
                if ((venCCId == null) || (venCCId == "") || (venCCId == undefined)) {
                    //alert('vendor contact cc is missing');
                    recipientCC = '';
                } else {
                    vendorIdcc = venCCId.value;
                    var vendDtlscc = search.lookupFields({
                        type: search.Type.CONTACT,
                        id: vendorIdcc,
                        columns: ['email']
                    });
                    console.log('vendDtls', vendDtlscc.email);
                    if ((vendDtlscc.email == null) || (vendDtlscc.email == "") || (vendDtlscc.email == undefined)) {
                        //alert('Email is missing for the Vendor Contact CC');
                    } else {
                        recipientCC = vendDtlscc.email;
                    }
                }
                //Setting the url of the suitelet script 
                var output = url.resolveScript({
                    scriptId: 'customscript_netu_sl_send_req_email',
                    deploymentId: 'customdeploy_netu_sl_send_req_email',
                    returnExternalUrl: false,
                }) + '&recId=' + id + '&emailId=' + vendorId + '&emailIdCC=' + recipientCC + '&sendReqId=' + sendReqId +'&typename=3'
                console.log(output);
                //Opens url on a new Window
                newWindow = window.open(output, 'netsuite', 'menubar=1,resizable=1,width=740,height=800');
                 var timer = setInterval(function() {
                    if (newWindow.closed) {
                        //console.log('Reload');
                        clearInterval(timer);
                        document.getElementById("custpage_requisition_reminder").disabled = false;
                        //window.location.reload(true);
                    }
                }, 1000);
            } catch (e) {
                console.log(e.message);
            }
        }
        /*
         * Function to send a Requisition Email
         */
        function SendRequisition() {
            try {
                document.getElementById("custpage_send_requisition").disabled = true;
                var temp;
                //Getting current record id
                var currentRec = currentRecord.get();
                var id = currentRec.id;
                var prDtls = search.lookupFields({
                    type: 'customrecord_netu_purchase_requisition',
                    id: id,
                    columns: ['custrecord_netu_pur_req_vendor_contact', 'custrecord_netu_pur_req_vendor_contactcc', 'custrecord_netu_req_sub_status', 'custrecord_netu_pur_req_main_job', 'custrecord_netu_sub_job_number', 'custrecord_netu_req_subsidiary']
                });
                if (prDtls.custrecord_netu_req_subsidiary[0] != null) {
                    subsidiary = prDtls.custrecord_netu_req_subsidiary[0].value;
                }
                var vendorId = null;
                var vendorIdcc = null;
                var recipientId = null;
                var recipientCC = null;
                var venId = prDtls.custrecord_netu_pur_req_vendor_contact[0];
                //getting vendor contact
                if ((venId == null) || (venId == "") || (venId == undefined)) {
                    alert('vendor contact is missing');
                    setTimeout(function() { document.getElementById("custpage_send_requisition").disabled = false; }, 100);
                    return false;
                } else {
                    vendorId = venId.value;
                    var vendDtls = search.lookupFields({
                        type: search.Type.CONTACT,
                        id: vendorId,
                        columns: ['email']
                    });
                    console.log('vendDtls', vendDtls.email);
                    if ((vendDtls.email == null) || (vendDtls.email == "") || (vendDtls.email == undefined)) {
                        //alert('Email is missing for the Vendor Contact');
                        setTimeout(function() { document.getElementById("custpage_send_requisition").disabled = false; }, 100);
                        //return false;
                    } else {
                        recipientId = vendDtls.email;
                    }
                }
                var venCCId = prDtls.custrecord_netu_pur_req_vendor_contactcc[0];
                //getting vendor contact cc
                if ((venCCId == null) || (venCCId == "") || (venCCId == undefined)) {
                    //alert('vendor contact cc is missing');
                    recipientCC = '';
                } else {
                    vendorIdcc = venCCId.value;
                    console.log('vendorIdcc', vendorIdcc);
                    var vendDtlscc = search.lookupFields({
                        type: search.Type.CONTACT,
                        id: vendorIdcc,
                        columns: ['email']
                    });
                    console.log('vendDtls', vendDtlscc.email);
                    if ((vendDtlscc.email == null) || (vendDtlscc.email == "") || (vendDtlscc.email == undefined)) {
                        //alert('Email is missing for the Vendor Contact CC');
                    } else {
                        recipientCC = vendDtlscc.email;
                    }
                }
                var mainRef = null,
                    mainRefText = null,
                    subjobTy = null,
                    subjobRefText = null;
                if (prDtls.custrecord_netu_pur_req_main_job[0] != null) {
                    mainRef = prDtls.custrecord_netu_pur_req_main_job[0].value;
                    mainRefText = prDtls.custrecord_netu_pur_req_main_job[0].text;
                } else {
                    alert('Main Job Reference is missing');
                    setTimeout(function() { document.getElementById("custpage_send_requisition").disabled = false; }, 100);
                    return false;
                }
                if (prDtls.custrecord_netu_req_sub_status[0] != null) {
                    subjobTy = prDtls.custrecord_netu_req_sub_status[0].value;
                } else {
                    alert('Sub Job Type is not defined');
                    setTimeout(function() { document.getElementById("custpage_send_requisition").disabled = false; }, 100);
                    return false;
                }
                var fileId = null;
                if (subjobTy == 2) {//direct
                    temp = 13;
                } else if (subjobTy == 1) {//parts
                    fileId = '';
                    temp = 15;
                }
                //Setting the url of the suitelet script 
                var output = url.resolveScript({
                    scriptId: 'customscript_netu_sl_send_req_email',
                    deploymentId: 'customdeploy_netu_sl_send_req_email',
                    returnExternalUrl: false,
                }) + '&recId=' + id + '&emailId=' + vendorId + '&emailIdCC=' + recipientCC + '&subJobType=' + subjobTy + '&temp=' + temp + '&typename=2'
                //Opens url on a new Window
                newWindow = window.open(output, 'netsuite', 'menubar=1,resizable=1,width=740,height=800');
                //After newWindow Closed reload the Purchase Requisition 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 change the sub job status in all related records
         */
        function changeStatus(subjobId, st) {
            try {
                https.get({
                    url: '/app/site/hosting/scriptlet.nl?script=221&deploy=1&subJobId=' + subjobId + '&statusNo=' + st
                });
            } catch (e) {
                console.log(e.message);
            }
        }
        /*
         * Function to change the Sub-job status to Unable To Quote
         */
        function ChangeToUnableToQuote() {
            try {
                document.getElementById("custpage_unable_to_quote").disabled = true;
                var cnfm = confirm("Do you want to continue with Unable To Quote?");
                if (cnfm == true) {
                    //Getting current record id
                    var currentRec = currentRecord.get();
                    var id = currentRec.id;
                    var subjobId = search.lookupFields({
                        type: 'customrecord_netu_purchase_requisition',
                        id: id,
                        columns: ['custrecord_netu_sub_job_number']
                    });
                    var subJobid = subjobId.custrecord_netu_sub_job_number[0].value;
                    console.log('subJobid', subJobid);
                    //Change the Sub-job status to Unable To Quote in the Sub-job record
                    var subStatus = record.submitFields({
                        type: 'customrecord_netu_sub_job',
                        id: subJobid,
                        values: {
                            custrecord_netu_subjob_status: '4'
                        },
                        options: {
                            enableSourcing: false,
                            ignoreMandatoryFields: true
                        }
                    });
                    var st = '4';
                    changeStatus(subJobid, st);
                    console.log(subStatus);
                    document.getElementById("custpage_unable_to_quote").disabled = false;
                    window.location.reload(true);
                }
                setTimeout(function() { document.getElementById("custpage_unable_to_quote").disabled = false; }, 100);
            } catch (e) {
                console.log(e.message);
            }
        }
        /*
         * Function to Create Sales Quote
         */
        function CreateSQ() {
            try {
                document.getElementById("custpage_create_sq_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_sq',
                    deploymentId: 'customdeploy_netu_sl_create_sq',
                    returnExternalUrl: false
                }) + '&requisitionId=' + id;
                console.log('SL:', output);
                window.location = output;
            } catch (e) {
                console.log(e.message);
                alert(e.message);
            }
        }
        /*
         * AM Ends
         */
        function saveRecord(scriptContext) {
            try {
                var currentRec = scriptContext.currentRecord;
                var recordId = currentRec.id;
                console.log('recordId:', recordId);
                var rfqDate = currentRec.getValue({
                    fieldId: 'custrecord_netu_req_rfq_date'
                });
                if (rfqDate) {
                    var getCommi = currentRec.getText({
                        fieldId: 'custrecord_netu_req_fixed_comm_principal'
                    });
                    var getCommObjt = JSON.parse(getCommi);
                    var locFlagS = getCommObjt.locationFlag;
                    var sub_type = currentRec.getValue({
                        fieldId: 'custrecord_netu_req_sub_status'
                    });
                    var scaleComm = currentRec.getValue({
                        fieldId: 'custrecord_netu_req_scale_commission'
                    });
                    var commPerc = currentRec.getValue({
                        fieldId: 'custrecord_netu_req_vendor_comm_perc'
                    });
                    var commAmt = currentRec.getValue({
                        fieldId: 'custrecord_netu_req_commission_amount'
                    });
                    var netAmt = currentRec.getValue({
                        fieldId: 'custrecord_netu_req_net_amount'
                    });
                    var currencyVendor = currentRec.getText({
                        fieldId: 'custrecord_netu_req_currency_code'
                    });
                    var numLines = currentRec.getLineCount({
                        sublistId: 'recmachcustrecord_netu_pur_req_id'
                    });
                    if (currencyVendor == null || currencyVendor == "" || currencyVendor == undefined) {
                        alert('please enter currency');
                        return false;
                    }
                    //checking whether item quantity or price is missing if the type is parts
                    if (sub_type == 1) {
                        for (var i = 0; i < numLines; i++) {
                            var partQty = currentRec.getSublistValue({
                                sublistId: 'recmachcustrecord_netu_pur_req_id',
                                fieldId: 'custrecord_netu_quantity',
                                line: i
                            });
                            var partPrice = currentRec.getSublistValue({
                                sublistId: 'recmachcustrecord_netu_pur_req_id',
                                fieldId: 'custrecord_netu_pur_req_gross_amount',
                                line: i
                            });
                            if (partQty == null || partQty == "" || partQty == undefined) {
                                alert("item quantity is missing");
                                return false;
                            }
                            if (partPrice == null || partPrice == "" || partPrice == undefined) {
                                alert("item price is missing");
                                return false;
                            }
                        }
                    }
                    if (sub_type == 2) {
                        var directPrice = currentRec.getSublistValue({
                            sublistId: 'recmachcustrecord_netu_pur_req_id',
                            fieldId: 'custrecord_netu_pur_req_gross_amount',
                            line: 0
                        });
                        if (directPrice == null || directPrice == "" || directPrice == undefined) {
                            alert("item price is missing");
                            return false;
                        }
                    }
                    //checking commission based on the condition(principal location)
                    if (locFlagS == 1) {
                        if ((scaleComm == false && commPerc == null) || (scaleComm == false && commPerc == "") || (scaleComm == false && commPerc == undefined)) {
                            logme("Commission");
                            return false;
                        }
                        if ((scaleComm == true && commAmt == null) || (scaleComm == true && commAmt == "") || (scaleComm == true && commAmt == undefined)) {
                            logme("Commission");
                            return false;
                        }
                    }
                    if (netAmt == null || netAmt == "" || netAmt == undefined) {
                        logme("Net Amount");
                        return false;
                    }
                }
                return true;
            } catch (e) {
                console.log(e.message);
            }
        }
        /*******************************************************************************
         * Log these data
         * 
         * @param title
         * @param details
         * @returns
         * 
         * Created on 09-Aug-2017
         */
        function logme(title) {
            alert(title + ' is Missing');
            return false;
        }
        return {
            pageInit: pageInit,
            SendRequisitionReminder: SendRequisitionReminder,
            SendRequisition: SendRequisition,
            changeStatus: changeStatus,
            ChangeToUnableToQuote: ChangeToUnableToQuote,
            CreateSQ: CreateSQ,
            DateNow: DateNow,
            fieldChanged: fieldChanged,
            validateLine: validateLine,
            sublistChanged: sublistChanged,
            logme: logme,
            saveRecord: saveRecord
        };
    });