Push Sales Order Data to Numerik

Solution

The below script summarizes on sending sales order data to numerik if the status is in pending fulfilment

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 */
/******************************************************************************
 * Date : 19 July 2021
 *
 * Author: Jobin & Jismi IT Services LLP
 * Script Description : Pushing sales data to numerik if So status is in pending fulfillment
 *
 ******************************************************************************
 * DEPLOYMENT: SALES ORDER
 * This script summarises on pushing sales data to numerik if So status is in pending fulfillment
 *
 * SCENARIO: When SO is created in netsuite, if the status is in pending fulfillment and on Hold is false, the SO is pushed to numerik
 * If any staus change happens on On hold status is changed, the SO is deleted from nuemrik
 * When SO is updated the same is updated from nuemrik, When deletd the same is deleted from numerik.
 * Only line items which have qty committed > 0 is pushed
 * If SO customer is not is numerik, the customer is also pushed to numerik
 *
 * *****************************************************************************
 * REVISION HISTORY
 *
 * Revision 1.0 ${19 July 2021} JJ0131 : created
 * Revision 2.0 ${28 Sep 2021}  JJ0131 : Updated
 */
define(['N/https', 'N/record', 'N/search', 'N/email', 'N/runtime'],
    /**
     * @param{https} https
     * @param{record} record
     */
    (https, record, search, email, runtime) => {


        const beforeLoad = (scriptContext) => {
            try {
                if (scriptContext.type === scriptContext.UserEventType.VIEW) {
                    var editSorecord = scriptContext.newRecord;
                    var status = editSorecord.getValue({fieldId: 'status'});
                    var tranid = editSorecord.getValue({fieldId: 'tranid'});
                    log.debug("Tranid", tranid);
                    var header = [];
                    //SB Api kEy
                    //header['ApiKey']='Q6TZntaMU2rf2zFv1uBYtjk1AvvM5OT2rjkCieTJKN0=';
                    header['ApiKey'] = 'GcKVrpepGj1kwkIKNi5eNBNdnLuHgdEp3e972WrJ+qo=';
                    header['Content-Type'] = 'application/json';
                    //On before Load, is SO status is closed, So is deleted from numerik
                    if (status == 'Closed') {
                        SODelete(tranid, header);
                    }


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


        }
        const afterSubmit = (scriptContext) => {
            try {
                var SOrecord = scriptContext.newRecord;
                var Soid = SOrecord.id;
                //Canad Subsidiaries Internalid
                var CASUB = 11, CASUB2 = 14;
                var STATUS = 'Pending Fulfillment';
                var header = [];
                header['ApiKey'] = 'GcKVrpepGj1kwkIKNi5eNBNdnLuHgdEp3e972WrJ+qo=';
                header['Content-Type'] = 'application/json';
                if (scriptContext.type === scriptContext.UserEventType.CREATE) {
                    //On create, SO is pushed to numerik
                    var SO_record = record.load({
                        type: record.Type.SALES_ORDER,
                        id: Soid,
                        isDynamic: true
                    });
                    DataSales(header, CASUB, CASUB2, STATUS, SO_record);


                }
                if (scriptContext.type === scriptContext.UserEventType.APPROVE) {
                    //On Approval, SO is pushed to numerik
                    var SO_record = record.load({
                        type: record.Type.SALES_ORDER,
                        id: Soid,
                        isDynamic: true
                    });
                    DataSales(header, CASUB, CASUB2, STATUS, SO_record);
                }
                if (scriptContext.type === scriptContext.UserEventType.EDIT) {
                    var SO_record = record.load({
                        type: record.Type.SALES_ORDER,
                        id: Soid,
                        isDynamic: true
                    });
                    var sub = SO_record.getValue({fieldId: 'subsidiary'});
                    var hold = SO_record.getValue({fieldId: 'custbody_hold'});
                    var status = SO_record.getValue({fieldId: 'status'});


                    var tranid = SO_record.getValue({fieldId: 'tranid'});
                    /*****If SO status is not in pending fulfillment or On Hold status is chnaged, the SO is deleted from numerik*****/
                    if (status !== STATUS) {


                        SODelete(tranid, header);
                    } else if (hold == true) {
                        SODelete(tranid, header);
                    } else {
                        //If no chnages are made, SO is deleted and repushed to numerik
                        SODelete(tranid, header);


                        DataSales(header, CASUB, CASUB2, STATUS, SO_record);


                    }
                }
                if (scriptContext.type === scriptContext.UserEventType.DELETE) {
                    //When deleting from Netsuite, the same will be deleted from numerik
                    var editSorecord = scriptContext.newRecord;
                    var tranid = editSorecord.getValue({fieldId: 'tranid'});
                    SODelete(tranid, header);


                }



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


            }



        }


        /****Funtion to delete Sales order from numerik*****/


        function SODelete(tranid, header) {
            try {
                var Soresponse = https.get({
                    url: 'https://numerik-publicapi-prod.azurewebsites.net/api/SalesData/TransactionId/' + tranid,
                    headers: header
                });


                if (Soresponse.code == 200) {
                    var Sodelete = https.delete({
                        url: 'https://numerik-publicapi-prod.azurewebsites.net/api/SalesData/TransactionId/' + tranid,
                        headers: header
                    });
                    log.debug("CODE", Sodelete.code);
                }


            } catch (e) {


                log.debug({title: "error@SOdelete", details: e.message});
                log.error({title: "Error@Sodelete", details: e.message});
            }
        }


        /****Function to push Sales Data to numerik****/
        function DataSales(header, CASUB, CASUB2, STATUS, SO_record) {
            try {


                var tranid = SO_record.getValue({fieldId: 'tranid'});
                //log.debug("Tranid",tranid)
                var tranDate = SO_record.getText({fieldId: 'trandate'});
                var salesrep = SO_record.getText({fieldId: 'salesrep'});
                var subsid = SO_record.getValue({
                    fieldId: 'subsidiary'
                });


                var hold = SO_record.getValue({
                    fieldId: 'custbody_hold'
                });


                var status = SO_record.getValue({
                    fieldId: 'status'
                });



                /**If status is pending fulfillment, On hold is false and Subsidiary is Canada, The sales order is pushed to numerik**/
                if ((subsid == CASUB || subsid == CASUB2) && hold == false && status == STATUS) {
                    var custid, cuname;


                    /**Pushing Customer to numerik, if the customer is not in numerik*/
                    function Customer() {
                        try {
                            custid = SO_record.getValue({fieldId: 'entity'});
                            cuname = SO_record.getText({fieldId: 'entity'});
                            var cusrecord = record.load({
                                type: record.Type.CUSTOMER,
                                id: custid,
                                isDynamic: true
                            });
                            var cusrecordid = cusrecord.id;
                            var cussub = cusrecord.getValue({fieldId: 'subsidiary'});
                            var cusresponse = https.get({
                                url: 'https://numerik-publicapi-prod.azurewebsites.net/api/Customers',
                                headers: header
                            });
                            var obj = JSON.parse(cusresponse.body);
                            var present = false;
                            for (var i = 0; i < obj.length; i++) {
                                if (obj[i].id == cusrecordid) {
                                    log.debug("Customer is present in numerik");
                                    present = true;
                                    return present;
                                }
                            }
                            if (present == false) {
                                if (cussub == CASUB || cussub == CASUB2) {
                                    var cusname = cusrecord.getValue({fieldId: 'companyname'});
                                    log.debug("NAME", cusname);
                                    var cusadr1 = cusrecord.getValue({fieldId: 'billaddr1'});
                                    var cusadr2 = cusrecord.getValue({fieldId: 'billaddr2'});
                                    var cusadr3 = cusrecord.getValue({fieldId: 'billaddr3'});
                                    var cusemail = cusrecord.getValue({fieldId: 'email'});
                                    log.debug("EMAIL", cusemail);
                                    var cusphone = cusrecord.getValue({fieldId: 'phone'});
                                    log.debug("PHONE", cusphone);
                                    var postcode = cusrecord.getValue({fieldId: 'billzip'});
                                    log.debug("ZIP", postcode);
                                    var cuscity = cusrecord.getValue({fieldId: 'billcity'});
                                    log.debug("CITY", cuscity);
                                    var cuscountry = cusrecord.getValue({fieldId: 'billcountry'});
                                    log.debug("COUNTRY", cuscountry);
                                    var primarycontact = cusrecord.getValue('contact');
                                    log.debug("CONTACT", primarycontact);
                                    var cusalesrep = cusrecord.getText({fieldId: 'salesrep'});
                                    log.debug("SALESREP", cusalesrep);
                                    var cusgrp1 = cusrecord.getText('custentity32');
                                    var cusgrp2 = cusrecord.getText('custentity_distribution_channel');
                                    var cusgrp4 = cusrecord.getText('custentity43');
                                    var cusgrp6 = cusrecord.getValue('custentity44');
                                    var cusgrp7 = cusrecord.getValue('parent');
                                    var cusgrp8 = cusrecord.getText('custentity2');
                                    var cusgrp9 = cusrecord.getText('custentity_rep_run');


                                    var cusobj = [{}];


                                    cusobj[0]["numerikId"] = 0;
                                    cusobj[0]["id"] = custid.toString();
                                    cusobj[0]["name"] = cusname;
                                    cusobj[0]["address1"] = cusadr1;
                                    cusobj[0]["address2"] = cusadr2;
                                    cusobj[0]["address3"] = cusadr3;
                                    cusobj[0]["billToCity"] = cuscity;
                                    cusobj[0]["postCode"] = postcode;
                                    cusobj[0]["billToCountry"] = cuscountry;
                                    cusobj[0]["email"] = cusemail;
                                    cusobj[0]["phoneNumber"] = cusphone;
                                    cusobj[0]["platinum"] = true;
                                    cusobj[0]["consultant"] = primarycontact;
                                    cusobj[0]["salesRep"] = cusalesrep;
                                    cusobj[0]["customerGroup1"] = cusgrp1;
                                    cusobj[0]["customerGroup2"] = cusgrp2; ////DISTRIBUTION CHANNEL
                                    cusobj[0]["customerGroup3"] = '';
                                    cusobj[0]["customerGroup4"] = cusgrp4;// Primary Group
                                    cusobj[0]["customerGroup5"] = '';
                                    cusobj[0]["customerGroup6"] = cusgrp6; //INSIDE SALES REP
                                    cusobj[0]["customerGroup7"] = cusgrp7;// PARENT COMPANY
                                    cusobj[0]["customerGroup8"] = cusgrp8;//Industry
                                    cusobj[0]["customerGroup9"] = cusgrp9;


                                    var response = https.post({
                                        url: 'https://numerik-publicapi-prod.azurewebsites.net/api/Customers',
                                        body: JSON.stringify(cusobj),
                                        headers: header
                                    });
                                    //log.debug("CUS OBJ", response.body);
                                    log.debug("CODE", response.code);
                                }


                            }


                        } catch (e) {
                            log.debug("e@Customer", e.message);
                            log.error("e@Customer", e.message);
                        }
                    }


                    Customer();



                    /**** Pushing sales data to numerik******/


                    try {
                        var numLines = SO_record.getLineCount({
                            sublistId: 'item'
                        });
                        log.debug("Lines", numLines);
                        var productObj = [];
                        var salesDataObj = [];
                        for (var i = 0; i < numLines; i++) {
                            var itemtype = SO_record.getSublistValue({sublistId: 'item', fieldId: 'itemtype', line: i});
                            if (itemtype !== 'Group' && itemtype !== 'EndGroup') {
                                var qtycommit = SO_record.getSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'quantitycommitted',
                                    line: i
                                });
                                log.debug("Qty", qtycommit);
                                if (qtycommit == null || qtycommit == '') {
                                    qtycommit = 0;
                                }


                                if (qtycommit > 0) {
                                    var item = SO_record.getSublistValue({sublistId: 'item', fieldId: 'item', line: i});
                                    log.debug("ITEM", item);
                                    var quantity = SO_record.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'quantity',
                                        line: i
                                    });
                                    var rate = SO_record.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'rate',
                                        line: i
                                    });
                                    var line = SO_record.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'line',
                                        line: i
                                    });
                                    log.debug("line", line)
                                    if (line == null || line == "")
                                        line = i + 1;
                                    log.debug('line', line);
                                    var amount = SO_record.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'amount',
                                        line: i
                                    });
                                    if (amount == null || amount == "") {
                                        amount = 0;
                                    }
                                    var costestimate = SO_record.getSublistValue({
                                        sublistId: 'item',
                                        fieldId: 'costestimate',
                                        line: i
                                    });


                                    if (rate == null || rate == '') {
                                        rate = 0;
                                    }


                                    if (costestimate == null || costestimate == '')
                                        costestimate = 0;
                                    var estgrossprofict = amount - costestimate;
                                    var gross = estgrossprofict.toFixed(2);
                                    var itemfields = search.lookupFields({
                                        type: 'item',
                                        id: item,
                                        columns: ['itemid', 'displayname', 'custitem19', 'internalid']
                                    });
                                    var itemgroup = '';
                                    if (itemfields.custitem19[0]) {
                                        itemgroup = itemfields.custitem19[0].text;
                                    }
                                    var intid = itemfields.internalid;
                                    log.debug('itemid', intid);
                                    var itemid = itemfields.itemid;
                                    log.debug('itemname', itemid);
                                    var itemdesc = itemfields.displayname;
                                    var Obj = {};
                                    Obj[i] = {};
                                    Obj[i].numerikId = 0;
                                    Obj[i].id = item.toString();
                                    Obj[i].name = itemid;
                                    Obj[i].description = itemdesc;
                                    Obj[i].productGroup = itemgroup;
                                    Obj[i].productManager = '';
                                    //log.debug("Productobj",Obj)
                                    productObj.push(Obj[i]);
                                    var salesObj = {};
                                    salesObj[i] = {};
                                    salesObj[i].numerikId = 0;
                                    salesObj[i].transactionId = tranid;
                                    salesObj[i].dateOfTransaction = tranDate;
                                    salesObj[i].lineId = line.toString();
                                    salesObj[i].quantity = qtycommit;
                                    salesObj[i].unitSalesPrice = rate;
                                    salesObj[i].lineTotal = amount;
                                    salesObj[i].grossProfitDollars = gross;
                                    salesObj[i].customerId = custid;
                                    salesObj[i].customerName = cuname;
                                    salesObj[i].productId = itemid;
                                    salesObj[i].productDescription = itemdesc;
                                    salesObj[i].productGroup = itemgroup;
                                    salesObj[i].salesRep = salesrep;
                                    salesObj[i].consultant = ''; //transType
                                    salesObj[i].projectId = '';
                                    salesObj[i].projectName = '';
                                    salesDataObj.push(salesObj[i]);
                                }
                            }
                        }
                        /**posting item data and sales data****/
                        var prodresponse = https.post({
                            url: 'https://numerik-publicapi-prod.azurewebsites.net/api/Products',
                            body: JSON.stringify(productObj),
                            headers: header
                        });
                        log.debug("PRDCODE", prodresponse.code);



                        var salesresponse = https.post({
                            url: 'https://numerik-publicapi-prod.azurewebsites.net/api/SalesData',
                            body: JSON.stringify(salesDataObj),
                            headers: header
                        });
                        log.debug("SALECODE", salesresponse.code)
                    } catch (e) {
                        log.debug("e@Sales", e.message);
                        log.error("e@Sales", e.message);
                    }


                }
            } catch (e) {


                log.debug({title: "error@DataSale", details: e.message});
                log.error({title: "Error@DataSale", details: e.message});
                var script = runtime.getCurrentScript();
                var rec = script.getParameter({
                    name: 'custscript_jj_so_err_email'
                });
                var user = runtime.getCurrentUser();
                var auth = user.id;
                var env = runtime.envType;
                var acnt = runtime.accountId;
                var scriptid = script.id;


                email.send({
                    author: auth,
                    recipients: rec,
                    subject: 'Numerik Sync Failure: Sales Order #' + tranid,
                    body: 'Account ID: ' + acnt + 'n' +
                        'Environment: ' + env + 'n' +
                        'Script: ' + scriptid + 'n' +
                        'Error Details: ' + e.name + 'n' +
                        'Error Message: ' + e.message
                });
            }
        }


        return {beforeLoad, afterSubmit}


    });


Leave a comment

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