Create a pickup request in Daylight

NDAZ-31

When an  Item Fulfillment is created in NetSuite, a UserEvent Script runs in the background, which then generates the Access Token for authorization. Once the access token is generated, calls a POST pickup API request which creates a pickup request in Daylight for corresponding Item fulfilment in Daylight. Once a Pickup request is created in Daylight, collects the response which returns booking number. The booking number is then set to the Package Tracking Number field under packages Subtab. Once the booking number is set in the item fulfilment field, an email is sent to the customer mentioning the Tracking Number. 

Once a Pickup request is created in Daylight, collects the response which returns Booking Number. The Booking number is then set to the Package Tracking Number field under packages Subtab. Once the booking number is set in the item fulfilment field, an email is sent to the customer mentioning the Tracking Number.

1.1) Fetch the Booking number from response and set as the tracking number

When a POST Pickup Request is sent and a pickup is created in Daylight, as a response for the API call we will get a booking number. We then set this number as a tracking number in the item fulfilment.

Booking Number set as tracking number in the item fulfillment.

1.2) Send an email notification

Once the booking number set as a tracking number in the item fulfilment sends an email notification to the customer with a tracking number.

Note:

For successful creation of pickup request in Daylight following fields are mandatory:

  1. Pickupenddate field of IF.
  2. Set Shipping Method in IF as Daylight.
/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * DAZ-33 UE Script to create pickup when item fulfillment with Shipping Method Daylight is created/edited  
 * **************************************************************************
 * 
 * Date: 16-05-2019
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 *****************************************************************************
 **/
define(['N/format', 'N/url', 'N/search', 'N/runtime', 'N/record', 'N/https', 'N/ui/serverWidget', 'N/email'],

    function(format, url, search, runtime, record, https, serverWidget, email) {
        var ITEM_OBJ = {};

        var main = {
            afterSubmit: function(scriptContext) {
                log.debug("scriptContext", scriptContext);
                var newRecId = scriptContext.newRecord.id;
                if (scriptContext.type == "create" || scriptContext.type == "edit") {
                    var shipmentMethod = scriptContext.newRecord.getValue({
                        fieldId: 'shipmethod'
                    });
                    if (shipmentMethod == "6418") {
                        ITEM_OBJ.shipmentMethod = shipmentMethod;

                        var customer_Id = scriptContext.newRecord.getValue({
                            fieldId: 'entity'
                        });
                        ITEM_OBJ.customer_Id = customer_Id;

                        var shipmentID = scriptContext.newRecord.getValue({
                            fieldId: 'createdfrom'
                        });
                        ITEM_OBJ.shipmentID = shipmentID;

                        var userObj = runtime.getCurrentUser();
                        ITEM_OBJ.senderId = userObj.id

                        var pickupStartDate = scriptContext.newRecord.getValue({
                            fieldId: 'trandate'
                        });
                        var event_1 = new Date(pickupStartDate).toISOString();
                        pickupStartDate = event_1.split("T")[0].trim();
                        pickupStartTime = event_1.split("T")[1].split(".")[0].trim();
                        ITEM_OBJ.pickupStartDate = pickupStartDate;
                        ITEM_OBJ.pickupStartTime = pickupStartTime;

                        var pickupEndDate = scriptContext.newRecord.getValue({
                            fieldId: 'custbody__pickupendate'
                        });
                        var event_2 = new Date(pickupEndDate).toISOString();
                        pickupEndDate = event_2.split("T")[0].trim();
                        pickupEndTime = event_2.split("T")[1].split(".")[0].trim();
                        ITEM_OBJ.pickupEndDate = pickupEndDate;
                        ITEM_OBJ.pickupEndTime = pickupEndTime;

                        var pallets = scriptContext.newRecord.getValue({
                            fieldId: 'custbody__totalpalletcount'
                        });
                        ITEM_OBJ.pallets = pallets;

                        var N_lines = scriptContext.newRecord.getLineCount({
                            sublistId: 'item'
                        });


                        var item_Array = [];
                        for (var i = 0; i < N_lines; i++) {
                            var item = {};
                            item.id = scriptContext.newRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'item',
                                line: i
                            });
                            item.pcs = scriptContext.newRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'quantity',
                                line: i
                            });
                            item.checkbox = scriptContext.newRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'itemreceive',
                                line: i
                            });

                            item_Array.push(item);

                        }
                        ITEM_OBJ.accountNumber = "20636998";
                        ITEM_OBJ.userName = "7daze";
                        ITEM_OBJ.password = "12346valley";
                        ITEM_OBJ.shipperName = "7 DAZE MFG";
                        ITEM_OBJ.shipperAddress1 = "13170 SPRING ST";
                        ITEM_OBJ.shipperCity = "BALDWIN PARK";
                        ITEM_OBJ.shipperState = "CA";
                        ITEM_OBJ.shipperZip = "91706";
                        ITEM_OBJ.shipperContactName = "Fullfillment Team";
                        ITEM_OBJ.shipperContactNumber = "866-447-3293";
                        ITEM_OBJ.actualClass = "65";
                        ITEM_OBJ.description = "GLYCOLS CL65";
                        ITEM_OBJ.nmfcNumber = "44620"
                        ITEM_OBJ.nmfcSubNumber = "0"
                        ITEM_OBJ.items = item_Array;
                        main.search_details("Customers", ITEM_OBJ.customer_Id);
                        main.search_details("Trans", ITEM_OBJ.shipmentID);
                        main.search_details("Inv_items", ITEM_OBJ.items);
                        /*log.debug("ITEM_OBJ.items.length",ITEM_OBJ.items.length);*/
                        if (ITEM_OBJ.items.length > 0) {
                            var access_Token = main.gettoken_request();
                            log.debug("access_Token", access_Token);
                            var booking_No = main.create_Pickup(access_Token, ITEM_OBJ);
                            main.load_IF(newRecId,booking_No,ITEM_OBJ);
                            main.send_email(ITEM_OBJ);
                            log.debug("ITEM_OBJ", ITEM_OBJ);
                        }
                    }
                }

            },
            /*function to fetch customer, SO and item details*/
            search_details: function(type, type_Id) {
                if (type == "Customers") {
                    var itemRec = record.load({
                        type: record.Type.CUSTOMER,
                        id: type_Id,
                        isDynamic: false
                    });
                    var consigneeName = itemRec.getText({
                        fieldId: 'companyname'
                    });
                    ITEM_OBJ.consigneeName = consigneeName;

                    var email = itemRec.getText({
                        fieldId: 'email'
                    });
                    ITEM_OBJ.email = email;

                    var itemRec_addrsubrecord = itemRec.getSublistSubrecord({
                        sublistId: 'addressbook',
                        fieldId: 'addressbookaddress',
                        line: 0
                    });

                    var consigneeAddress1 = itemRec_addrsubrecord.getText({
                        fieldId: 'addr1'
                    });
                    ITEM_OBJ.consigneeAddress1 = consigneeAddress1;

                    var consigneeCity = itemRec_addrsubrecord.getText({
                        fieldId: 'city',
                    });
                    ITEM_OBJ.consigneeCity = consigneeCity;

                    var consigneeState = itemRec_addrsubrecord.getValue({
                        fieldId: 'state',
                    });
                    ITEM_OBJ.consigneeState = consigneeState;

                    var consigneeZip = itemRec_addrsubrecord.getValue({
                        fieldId: 'zip',
                    });
                    ITEM_OBJ.consigneeZip = consigneeZip;

                    var cont_Id = itemRec.getSublistValue({
                        sublistId: 'contactroles',
                        fieldId: 'contact',
                        line: 0
                    });
                    ITEM_OBJ.cont_Id = cont_Id;

                    var consigneeContactName;
                    var consigneeContactNumber;
                    var custSearch = search.create({
                        type: search.Type.CONTACT,
                        columns: [{
                                name: 'entityid',
                            },
                            {
                                name: 'phone',
                            }
                        ],
                        filters: [{
                            name: 'internalid',
                            operator: 'is',
                            values: cont_Id
                        }]
                    });
                    custSearch.run().each(function(result) {
                        consigneeContactName = result.getValue({
                            name: 'entityid',
                        });
                        consigneeContactNumber = result.getValue({
                            name: 'phone',
                        });
                        return false;
                    });
                    ITEM_OBJ.consigneeContactName = consigneeContactName;
                    ITEM_OBJ.consigneeContactNumber = consigneeContactNumber;
                } else if (type == "Trans") {
                    var billTerms;
                    var so_Search = search.create({
                        type: search.Type.SALES_ORDER,
                        columns: [{
                            name: 'paymentmethod',
                        }],
                        filters: [{
                            name: 'internalid',
                            operator: 'is',
                            values: type_Id
                        }]
                    });
                    so_Search.run().each(function(result) {
                        billTerms = result.getText({
                            name: 'paymentmethod',
                        });
                        return false;
                    });
                    ITEM_OBJ.billTerms = billTerms;
                } else if (type == "Inv_items") {
                    item_searcharray = [];
                    var pcs_sum = 0;
                    var weight_sum = 0;
                    for (var i = 0; i < type_Id.length; i++) {
                        var inv_Items = {};
                        if (type_Id[i].checkbox == true) {
                            /*log.debug("entered2");*/
                            inv_Items.id = type_Id[i].id;

                            inv_Items.pcs = type_Id[i].pcs;
                            /*inv_Items.pallets = type_Id[i].pallets;*/
                            inv_Items.checkbox = type_Id[i].checkbox;
                            var item_Search = search.create({
                                type: search.Type.ITEM,
                                columns: [{
                                    name: 'weight'
                                },
                                {
                                    name: 'weightunit'
                                }
                                ],
                                filters: [{
                                    name: 'internalid',
                                    operator: 'is',
                                    values: type_Id[i].id
                                }]
                            });
                           /* log.debug("item_Search", item_Search);*/
                            item_Search.run().each(function(result) {
                                inv_Items.weight = result.getValue(item_Search.columns[0]);
                                inv_Items.weightunit = result.getValue(item_Search.columns[1]);
                                return true;
                            });

                            item_searcharray.push(inv_Items);
                            pcs_sum = pcs_sum + inv_Items.pcs;
                            if(inv_Items.weightunit==1){
                            weight_sum = Number(weight_sum) + (Number(inv_Items.weight*inv_Items.pcs));
                            }
                            else if(inv_Items.weightunit==2){
                                weight_sum = Number(weight_sum) + ((Number(inv_Items.weight*inv_Items.pcs))/16);
                            }
                                else if(inv_Items.weightunit==3){
                                  weight_sum = Number(weight_sum) + ((Number(inv_Items.weight*inv_Items.pcs))*2.205);
                                }
                                    else if(inv_Items.weightunit==4){
                                      weight_sum = Number(weight_sum) + ((Number(inv_Items.weight*inv_Items.pcs))/453.592);
                                    }
                        }
                    }          
                    ITEM_OBJ.items = item_searcharray;
                    ITEM_OBJ.pcs_sum = pcs_sum;
                    ITEM_OBJ.weight_sum = Math.ceil(weight_sum);
                    /*ITEM_OBJ.weight_sum1=weight_sum;*/
                }
            },
            /*fuction to request to fetch token for post request*/
            gettoken_request: function() {
                var gettoken_response = https.post({
                    url: 'https://api.dylt.com/oauth/client_credential/accesstoken?grant_type=client_credentials',
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body: "client_secret=aXdNTGT2bcAv25Gd&grant_type=client_credentials&client_id=oSrwLmUyecfd34rvnEBphAiZFOZBhb2G"
                });
                var gettoken_content = JSON.parse(gettoken_response.body);
                log.debug("gettoken_content", gettoken_content);
                return gettoken_content.access_token;
            },
            /*function to create pickup in daylight*/
            create_Pickup: function(request_Token, ITEM_OBJ) {
              /*  var line_items = [];
                for (var i = 0; i < ITEM_OBJ.items.length; i++) {
                    line_items.push({
                        "description": ITEM_OBJ.description,
                        "pcs": main.checkForParameter(ITEM_OBJ.items[i].pcs),
                        "pallets": main.checkForParameter(ITEM_OBJ.pallets),
                        "weight": main.checkForParameter((ITEM_OBJ.items[i].pcs * ITEM_OBJ.items[i].weight) / 16),
                    });
                    log.debug("line_items", line_items);
                }*/
                var createpickup_response = https.post({
                        url: 'https://api.dylt.com/pickup',
                        headers: {
                            "Authorization": 'Bearer ' +request_Token,
                            "Accept": "application/json",
                            "Content-Type": "application/json"
                        },
                        body:JSON.stringify({
                                           "dyltPickupReqs":
                                            {
                                                "dyltPickupReq":
                                                {
                                                    "accountNumber": ITEM_OBJ.accountNumber,
                                                    "userName": ITEM_OBJ.userName,
                                                    "password": ITEM_OBJ.password,
                                                    "shipmentID":main.checkForParameter(ITEM_OBJ.shipmentID),
                                                    "billTerms": "Prepaid",
                                                    "serviceType": "LTL",
                                                    "shipperName": ITEM_OBJ.shipperName,
                                                    "shipperAddress1": ITEM_OBJ.shipperAddress1,
                                                    "shipperCity": ITEM_OBJ.shipperCity,
                                                    "shipperState": ITEM_OBJ.shipperState,
                                                    "shipperZip": ITEM_OBJ.shipperZip,
                                                    "shipperContactName": ITEM_OBJ.shipperContactName,
                                                    "shipperContactNumber": ITEM_OBJ.shipperContactNumber,
                                                    "consigneeName": main.checkForParameter(ITEM_OBJ.consigneeName),
                                                    "consigneeAddress1":main.checkForParameter(ITEM_OBJ. consigneeAddress1),
                                                    "consigneeCity": main.checkForParameter(ITEM_OBJ.consigneeCity),
                                                    "consigneeState":main.checkForParameter(ITEM_OBJ.consigneeState),
                                                    "consigneeZip":main.checkForParameter(ITEM_OBJ.consigneeZip),
                                                    "consigneeContactName": main.checkForParameter(ITEM_OBJ.consigneeContactName),
                                                    "consigneeContactNumber": main.checkForParameter(ITEM_OBJ.consigneeContactNumber),
                                                    "pickupStartDate": main.checkForParameter(ITEM_OBJ.pickupStartDate),
                                                    "pickupStartTime": main.checkForParameter(ITEM_OBJ.pickupStartTime),
                                                    "pickupEndDate": main.checkForParameter(ITEM_OBJ.pickupEndDate),
                                                    "pickupEndTime": main.checkForParameter(ITEM_OBJ.pickupEndTime),
                                                    "items":
                                                    {
                                                        "item":
                                                        {
                                                        "description": ITEM_OBJ.description,
                                                        "nmfcNumber":ITEM_OBJ.nmfcNumber,
                                                        "nmfcSubNumber": ITEM_OBJ.nmfcSubNumber,   
                                                        "pcs": main.checkForParameter(ITEM_OBJ.pcs_sum),
                                                        "pallets": main.checkForParameter(ITEM_OBJ.pallets),
                                                        "weight": main.checkForParameter(ITEM_OBJ.weight_sum),
                                                        "actualClass":ITEM_OBJ.actualClass
                                                        }
                                                       
                                                    }
                                                }
                                            }
                                      })
                    });
                var createpickup_content =JSON.parse(createpickup_response.body);
                log.debug("createpickup_content",createpickup_content);
                return createpickup_content.dyltPickupResps.dyltPickupResp.bookingNumber;
            },
            /*function to  load IF to save tracking number*/
            load_IF: function(if_Id, booking_No,ITEM_OBJ) {
                var ifRec = record.load({
                    type: record.Type.ITEM_FULFILLMENT,
                    id: if_Id,
                    isDynamic: false
                });

                log.debug("booking_No IF", booking_No);
                var pieces_dayl = ifRec.setValue({
                            fieldId: 'custbody__totalboxcount',
                            value:ITEM_OBJ.pcs_sum
                        });
                var weight_dayl = ifRec.setValue({
                            fieldId: 'custbody__totalweight',
                            value:ITEM_OBJ.weight_sum
                        });
                var tracking_No = ifRec.setSublistText({
                    sublistId: 'package',
                    fieldId: 'packagetrackingnumber',
                    line: 0,
                    text: booking_No
                });
                ITEM_OBJ.tracking_No = booking_No;
                var ifrecId = ifRec.save({
                    enableSourcing: true,
                    ignoreMandatoryFields: true
                });
                log.debug("ifrecId", ifrecId);

            },
            /*function to send email to customer with tracking number*/
            send_email: function(ITEM_OBJ) {
                email.send({
                    author: ITEM_OBJ.senderId,
                    recipients: ITEM_OBJ.email,
                    subject: 'Daylight Tracking Details',
                    body: 'Hi ' + ITEM_OBJ.consigneeName + '\n\nYour order was shipped. Here is your tracking number:' + ITEM_OBJ.tracking_No + '\n\nThank You\n\n7 Daze Fulfillment Team'
                });

            },
            //To check whether a value exists in parameter and set empty
            checkForParameter: function(parameter) {
                if (parameter != "" && parameter !== null && parameter !== undefined && parameter !== false && parameter !== "null" && parameter !== "undefined" && parameter !== 'false' && parameter != " ") {
                    return parameter;
                } else {
                    parameter = "";
                    return parameter;
                }
            }


        }
        for (var key in main) {
            if (typeof main[key] === 'function') {
                main[key] = trycatch(main[key], key);
            }
        };

        function trycatch(myfunction, key) {
            return function() {
                try {
                    return myfunction.apply(this, arguments);
                } catch (e) {
                    log.debug("e in  " + key, e);
                }
            }
        };
        return main;

    });

Leave a comment

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