Sales Order Customization

Requirement

We need to create a new button in the sales order and if the user clicks the button, a new sales order will open and the body fields will be populated from the parent sales order (Except some fields like date). User will enter the item lines manually and save the child sales orders. During the save operations, we need to check the parent sales order item lines and populated the line-level PO number and PO vendor reference to the child sales order

Solution

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


define(['N/currentRecord', 'N/record', 'N/runtime', 'N/search'],
    /**
 * @param{currentRecord} currentRecord
 * @param{record} record
 * @param{runtime} runtime
 * @param{search} search
 */
    (currentRecord, record, runtime, search) => {
        /**
         * Defines the function definition that is executed before record is loaded.
         * @param {Object} scriptContext
         * @param {Record} scriptContext.newRecord - New record
         * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
         * @param {Form} scriptContext.form - Current form
         * @param {ServletRequest} scriptContext.request - HTTP request information sent from the browser for a client action only.
         * @since 2015.2
         */
        const beforeLoad = (scriptContext) => {
            try{
                if(scriptContext.type=="view"){
                    scriptContext.form.clientScriptFileId=4965
                   
                    var salesRec = scriptContext.newRecord;
                    
                    var parentSoId = salesRec.id;
                    

                    //Adding a button labbeled Revise SO in sales order.
                    scriptContext.form.addButton({
                        id :'custpage_salesorderbtn',
                        label : 'Revise SO',
                        functionName:'openSalesOrder("'+parentSoId+'")'
                    })

                }

            }
            catch (e) {
                log.debug('Errror@BeforeLoad',e)
            }

        }

        /**
         * Defines the function definition that is executed before record is submitted.
         * @param {Object} scriptContext
         * @param {Record} scriptContext.newRecord - New record
         * @param {Record} scriptContext.oldRecord - Old record
         * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
         * @since 2015.2
         */

        const afterSubmit = (scriptContext) => {
            try{
                if(scriptContext.type==='create'){

                    //When a sales record is created
                    
                    var newRec=scriptContext.newRecord;
                    

                    //Get the id of the new record created
                    var parentId=newRec.id
                    
                    //Get the value of the related sales order id
                    var soid=newRec.getValue({
                        fieldId: 'custbody_jj_saleso_id'
                    });
                   

                    //If sales order id is present, load the sales order having that internal id
                    if(soid){
                        var objRecord = record.load({
                            type: record.Type.SALES_ORDER,
                            id: soid,
                            isDynamic: true,
                        });

                        //Set the values of the parent sales oder with this id
                        objRecord.setValue({
                            fieldId: 'custbody_jj_saleso_id',
                            value: parentId,
                            ignoreFieldChange: true
                        });
                        var obj=objRecord.save();
                       

                    }

                }

            }
            catch (e) {
                log.debug('Error@AfterSubmit',e)

            }


        }

        return {beforeLoad, beforeSubmit, afterSubmit}

    });
/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */




define(['N/currentRecord', 'N/record', 'N/search'],
    /**
     * @param{currentRecord} currentRecord
     * @param{record} record
     * @param{search} search
     */
    function (currentRecord, record, search) {

        /*  Open New Sales Order    */
        function openSalesOrder(soId) {
            try {
                //Get New Sales Order URL
               
                var newSOUrl = "https://6753382-rp.app.netsuite.com/app/accounting/transactions/salesord.nl?whence=";   //Custom function to get new standard Sales Order URL
                //Set Final URL for new Sales Order record
                var finalUrl = newSOUrl + '&parentsoid=' + soId;
               
                //Open Sales Order in new Tab
                window.open(finalUrl, "_blank");
                return true;
            } catch (e) {
                log.error("Error @openSalesOrder", e);
                return true;
            }
        }


        function pageInit(scriptContext) {
            try {
                console.log('In page init')

                //Get current record
                var currentRec = scriptContext.currentRecord

                //If script context mode = copy, set related sales order id to null
                if(scriptContext.mode==='copy') {
                    console.log('Copy context')
                    currentRec.setValue({fieldId: "custbody_jj_saleso_id", value: " "});
                }
                if(scriptContext.mode!='copy') {


                    //Get URL of the page
                    var params = window.location.href
                   
                    //Get parent soid from the URL
                    var getSoid = params.split('&parentsoid=')
                    var soId = getSoid[1]
                   
                    //If value for SOID is present , excute the following code

                    if (soId) {
                        
                        //Get Parent SO record field values
                        var fieldLookUp = search.lookupFields({
                            type: record.Type.SALES_ORDER,
                            id: soId,
                            columns: ["tranid", "subsidiary", "salesrep", "entity", "custbody6", "otherrefnum", "custbody9", "custbody_jj_unbilled_so_amt", "custbody_atlas_help_trans_lp_ref", "custbody_store_number", "custbody10", "custbody3", "department", "location", "custbody_dept_for_so"]
                        });
                       

                        var salesRec = record.load({
                            type: record.Type.SALES_ORDER,
                            id: soId,
                            isDynamic: true,
                        });
                        var discountItem=salesRec.getValue({
                            fieldId:"discountitem"
                        })
                       

                        var location=salesRec.getValue({
                            fieldId:"location"
                        })
                        

                        //Set the soid in page loaded
                        currentRec.setValue({fieldId: "custbody_jj_saleso_id", value: soId});


                        //If filedlookup is not null

                        if (fieldLookUp) {
                            //Setting the values to the current record
                            try {
                                if(fieldLookUp.custbody_dept_for_so) {
                                    currentRec.setValue({
                                        fieldId: "custbody_dept_for_so",
                                        value: fieldLookUp.custbody_dept_for_so
                                    });
                                }
                              
                                    currentRec.setValue({
                                        fieldId: "discountitem",
                                        value: discountItem
                                    });
                             
                                if (fieldLookUp.entity[0].value) {
                                    currentRec.setValue({fieldId: "entity", value: fieldLookUp.entity[0].value});

                                }
                                if (fieldLookUp.otherrefnum) {
                                    currentRec.setValue({fieldId: "otherrefnum", value: fieldLookUp.otherrefnum});
                                }
                                if (fieldLookUp.custbody6[0].value) {
                                    currentRec.setValue({fieldId: "custbody6", value: fieldLookUp.custbody6[0].value});
                                }
                                //
                                if (fieldLookUp.department[0].value) {
                                    currentRec.setValue({
                                        fieldId: "department",
                                        value: fieldLookUp.department[0].value || ""
                                    });
                                }
                              
                                   currentRec.setValue({fieldId: "location", value: location});


                        


                                if (fieldLookUp.custbody3[0].value) {
                                    currentRec.setValue({fieldId: "custbody3", value: fieldLookUp.custbody3[0].value});
                                }

                                currentRec.setValue({fieldId: "custbody9", value: fieldLookUp.custbody9});
                                if (fieldLookUp.custbody_jj_unbilled_so_amt) {
                                    currentRec.setValue({
                                        fieldId: "custbody_jj_unbilled_so_amt",
                                        value: fieldLookUp.custbody_jj_unbilled_so_amt
                                    });
                                }

                                if (fieldLookUp.custbody_atlas_help_trans_lp_ref[0].value) {
                                    currentRec.setValue({
                                        fieldId: "custbody_atlas_help_trans_lp_ref",
                                        value: fieldLookUp.custbody_atlas_help_trans_lp_ref[0].value
                                    });
                                }
                                if (fieldLookUp.custbody_store_number) {
                                    currentRec.setValue({
                                        fieldId: "custbody_store_number",
                                        value: fieldLookUp.custbody_store_number
                                    });
                                }

                                if (fieldLookUp.custbody10) {
                                    currentRec.setValue({fieldId: "custbody10", value: fieldLookUp.custbody10});
                                }

                            } catch (e) {
                                console.log('Error@Field value setvalue ', e)
                            }
                        }

                    }
                }
            } catch (e) {
                log.debug('Error@PageInit', e)

            }


        }




        /**
         * 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 {
                log.debug('In save record in')

                //Get current record
                var currentrecord = scriptContext.currentRecord
              
                //Get the current URL of the page
                var params1 = window.location.href
                log.debug('Parametes', params1)


                //Get the parent soid from the URL
                var getSoid = params1.split('&parentsoid=')

                //IF the parentsoid is present, execute the following code
                if (getSoid) {
                    var soId = getSoid[1]
                    log.debug('Soid in save record', soId)

                    //If soid is present
                    if (soId) {

                        var sales_order = record.load({
                            type: record.Type.SALES_ORDER,
                            id: soId,
                            isDynamic: true,
                        })
                      
                        //Get the line count of the item lines of current record
                        var lineCount = currentrecord.getLineCount({
                                sublistId: 'item'
                            }
                        )

                        //Get the line count of the parent sales order
                        var lineCountSalesOrder = sales_order.getLineCount({
                                sublistId: 'item'
                            }
                        )
                        log.debug('Line count', lineCount)
                        log.debug('Line count sales order', lineCountSalesOrder)



                        for (var i = 0; i < lineCount; i++)      //looping through each item line
                        {

                            currentrecord.selectLine({
                                sublistId: 'item',
                                line: i
                            });

                            var item_id_from_itemline = currentrecord.getCurrentSublistValue({ //id of item from item line
                                sublistId: 'item',
                                fieldId: 'item',

                            });
                            for (var j = 0; j < lineCountSalesOrder; j++) {
                                sales_order.selectLine({
                                    sublistId: 'item',
                                    line: j
                                });

                                var item_id_from_itemline_sales_order = sales_order.getCurrentSublistValue({ //id of item from item line
                                    sublistId: 'item',
                                    fieldId: 'item',

                                });

                                var currentRecordSetValue = sales_order.getCurrentSublistValue({ //po number field of item
                                    sublistId: 'item',
                                    fieldId: 'custcol_po_number',
                                });
                               
                                // If the item id in current record and item id in parent sales order matches, execute the following code
                                if (item_id_from_itemline == item_id_from_itemline_sales_order) {

                                    //Get the sublist value of po number field from the parent sales order
                                    var poNumberFromItemLine = sales_order.getCurrentSublistValue({ //id of item from item line
                                        sublistId: 'item',
                                        fieldId: 'custcol_po_number',

                                    });

                                    //If there is value in PO number field in parent sales order, set that value in PO Number line field in current record on the save of the record.
                                    if (poNumberFromItemLine) {
                                        var setPoCurrentRec = currentrecord.setCurrentSublistValue({ //rate field of item
                                            sublistId: 'item',
                                            fieldId: 'custcol_po_number',
                                            value: poNumberFromItemLine
                                        });
                                        log.debug('custcol_po_number set in current record', setPoCurrentRec)

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


                                }

                            }
                            log.debug('item id from itemline current record', item_id_from_itemline)
                        }
                    }
                }

                return true
            } catch (e) {
                log.debug('Error@Saverecord', e)
            }
        }

        return {
            pageInit: pageInit,
            saveRecord: saveRecord,
            openSalesOrder: openSalesOrder
        };

    });

Leave a comment

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