Item fulfillment Sync

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 */
/*******************************************************************
 *   UserEvent Script
 ****************************************************************
 *
 * Date: 28/01/2021
 *
 *
 *
 * REVISION HISTORY
 *
 * Revision
 *
 * Description: Sync the item fulfillment to Shopify.
 *
 ***************************************************************/

define(['N/record','N/currentRecord', 'N/search', 'N/https', '../Common Library/JJ Shopify Common Library.js'],
    /**
     * @param{record} record
     * @param{search} search
     *  @param{https} https
     */

    (record,currentRecord, search, https, shopifyLib) => {
        const shopifyLibrary = shopifyLib.Library;
        const dataSets = {
            /**
             * @description the fuctcion to create a search for checking whether the IF is synced
             * @param IF_ID - Item Fulfillment internal id
             */
            isIFIsSynced(IF_ID) {
                try {
                    var internalId;
                    //1.search
                    var customrecord_cl_shopify_integ_cl_468SearchObj = search.create({
                        type: "customrecord_cl_shopify_integ_cl_468",
                        filters:
                            [
                                ["custrecord_cl_item_fulfillment", "anyof", IF_ID]
                            ],
                        columns:
                            [
                                search.createColumn({ name: "internalid", label: "Internal ID" }),

                                search.createColumn({ name: "custrecord_cl_sales_order", label: "SALES ORDER" })
                            ],
                    });
                    //1.search
                    let searchResultCount = customrecord_cl_shopify_integ_cl_468SearchObj.runPaged().count;
                    //1.search
                    let resultSet = customrecord_cl_shopify_integ_cl_468SearchObj.run();
                    //log.debug("searchResultCount", searchResultCount);
                    //  var results = resultSet.getRange({ start: 0, end: 1 });
                    if (searchResultCount != 0) {
                        return false;

                    } else {
                        return true;
                    }
                } catch (e) {
                    // log.debug("error@function", e);
                }
            },
            shopifyCustomRecordSearch(soId) {
                var myCustomListSearch = search.create({
                    //2.custrecord
                    type: "customrecord_cl_shopify_integ_cl_468",
                    filters:
                        [
                            //2.custrecord fld
                            ["custrecord_cl_sales_order", "anyof", soId]
                        ],
                    columns:
                        [
                            search.createColumn({ name: "internalid", label: "Internal ID" })
                        ]
                });
                var resultSet = myCustomListSearch.run();
                //log.debug(resultSet);
                var results = resultSet.getRange({ start: 0, end: 1 });
                let internalId;
                for (var i in results) {
                    internalId = results[i].getValue({ name: "internalid", label: "Internal ID" });
                };
                //log.debug("internalId", internalId);
                return internalId;
            }
        }

        const exports = {
            /**
             * Defines the function definition that is executed after 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
             */
            afterSubmit(scriptContext) {
                let shopifyRecordID;
                try {
                    let contextMode = scriptContext.type;
                    log.debug("contextMode", contextMode);
                    if (contextMode === scriptContext.UserEventType.CREATE || contextMode === scriptContext.UserEventType.EDIT || contextMode === scriptContext.UserEventType.SHIP) {
                        var newRecord = scriptContext.newRecord;
                        var newIfStatus = scriptContext.newRecord.getValue({
                            fieldId: "shipstatus"
                        });
                        var oldIfStatus;
                        if (contextMode === scriptContext.UserEventType.EDIT)
                            oldIfStatus = scriptContext.oldRecord.getValue({
                                fieldId: "shipstatus"
                            });
                        if (newIfStatus == "C" && oldIfStatus != "C") {
                            //get the sales order id from the item fulfillment record
                            var soId = scriptContext.newRecord.getValue({
                                fieldId: 'createdfrom'
                            });
                            log.debug("soId", soId);
                            // function to check whether IF is synced or not
                            let isSynced = dataSets.isIFIsSynced(newRecord.id);
                            //log.debug("isSynced", isSynced)
                            //if IF is not synced then return
                            if (isSynced == false) {
                                return true;
                            }
                            shopifyRecordID = dataSets.shopifyCustomRecordSearch(soId);
                            log.debug("shopifyRecordID", shopifyRecordID);
                            // var trackingNumber = newRecord.getSublistValue({
                            //     sublistId: "package",
                            //     fieldId: "packagetrackingnumber",
                            //     line: 0
                            // });
                            var trackingNumber =scriptContext.newRecord.getSublistValue({
                                sublistId: 'package',
                                fieldId: 'packagetrackingnumber',
                                line: 0

                            });

                            log.debug("trackingNumber", trackingNumber)
                            //look up field function to get the value of shopify order id
                            var fieldLookUp = search.lookupFields({
                                type: search.Type.SALES_ORDER,
                                id: soId,
                                columns: ['custbody_cl_shopify_order_id']
                            });
                            //3.orderid
                            var orderId = fieldLookUp.custbody_cl_shopify_order_id;
                            log.debug("orderId", orderId)

                            var line_items=[];
                            if (orderId) {
                                var PAYLOAD_OBJECT = {
                                    fulfillment: {
                                        "location_id": 67651928322,
                                        "trackingNumber": trackingNumber ? trackingNumber : null,
                                        "tracking_url": trackingNumber ? 'https://www.fedex.com/fedextrack/?trknbr='+trackingNumber : null,
                                        line_items:''
                                    },
                                };

                                let numLines = newRecord.getLineCount({
                                    sublistId: 'item'
                                });
                                // log.debug("numLines", numLines);
                                ///get the item ID and quantity of each item to be fulfilled
                                var lineItemsArray = [];
                                // get the line count of item sublist
                                for (let i = 0; i < numLines; i++) {
                                    let tempObj = {}
                                    let isFulfill = newRecord.getSublistValue({
                                        fieldId: 'itemreceive',
                                        sublistId: 'item',
                                        line: i
                                    });
                                    if (isFulfill === true) {
                                        tempObj.id = newRecord.getSublistValue({
                                            fieldId: 'custcol_shopify_line_id',
                                            sublistId: 'item',
                                            line: i
                                        });
                                        tempObj.quantity = newRecord.getSublistValue({
                                            fieldId: 'quantity',
                                            sublistId: 'item',
                                            line: i
                                        });

                                        lineItemsArray.push(tempObj)
                                    }
                                }
                                PAYLOAD_OBJECT.fulfillment.line_items=lineItemsArray
                                //creatting API request for fulfillment

                                let apiCredentials = shopifyLibrary.SHOPIFY_API_REQUESTS.CREATE_FULFILLMENT;
                                log.debug("apiCredentials", apiCredentials)
                                apiCredentials = apiCredentials.replace("{order_id}", orderId);
                                log.debug("apiCredentials", apiCredentials)
                                log.debug("PAYLOAD_OBJECT", PAYLOAD_OBJECT)

                                let Response = shopifyLibrary.requestShopify(
                                    apiCredentials,
                                    "POST",
                                    PAYLOAD_OBJECT
                                );
                                log.debug("Response", Response);
                                //getting the IF id from the response
                                var newIFID = Response.fulfillment.id.toString()
                                //log.debug("newIFID", newIFID);
                                //setting the IF id to a field in the IF record
                                record.submitFields({
                                    type: record.Type.ITEM_FULFILLMENT,
                                    id: newRecord.id,
                                    values: {
                                        //4.bodyfld
                                        'custbody_cl_fulfillment_id': newIFID
                                    }
                                });
                                //on the successful sync attach item fulfillment to custom record
                                var customRecord = record.load({
                                    //2.custrecord
                                    type: 'customrecord_cl_shopify_integ_cl_468',
                                    id: shopifyRecordID
                                    //id:8
                                });
                                var itemFulfillmentId = scriptContext.newRecord.id;

                                if (newIFID !== '') {
                                    //log.debug("itemFulfillmentId", itemFulfillmentId);
                                    var IF_array = customRecord.getValue('custrecord_cl_item_fulfillment');
                                    IF_array.push(itemFulfillmentId);
                                    //log.debug("IF_array", IF_array);
                                    // customRecord.setValue({ fieldId: 'custrecord_cl_item_fulfillment', value: IF_array });
                                    record.submitFields({
                                        type: "customrecord_cl_shopify_integ_cl_468",
                                        id: shopifyRecordID,
                                        values: {
                                            custrecord_cl_item_fulfillment: IF_array
                                        },
                                        options: { enableSourcing: true, ignoreMandatoryFields: true }
                                    });
                                }

                                //else, display the error message on a field in custom record
                                // else if (Response.code === 400 || Response.code === 401 || Response.code === 404 || Response.code === 500) {
                                //     customRecord.setValue('custrecord_jj_err_if_sync', Response.type.toString() + "_ERROR");
                                // } else {
                                //     customRecord.setValue('custrecord_jj_err_if_sync', Response.type.toString() + "_ERROR");
                                // }


                            }

                        }
                    }
                } catch (e) {

                    log.debug('error@afterSubmit ', e);

                    record.submitFields({
                        //2.custom record
                        type: 'customrecord_cl_shopify_integ_cl_468',
                        id: shopifyRecordID,
                        values: {
                            custrecord_jj_err_if_sync: JSON.stringify({status: "FAILURE", reason: "ERROR", error: {name: e.name, message: e.message}})
                        },
                        options: {
                            enablesourcing: true, ignoreMandatoryFields: true
                        }
                    });
                    return false;
                }

                    //delete the item fulfillment record in netsuite which in turn deletes the IF in shopify
                     let contextMode = scriptContext.type;
                    if (contextMode === scriptContext.UserEventType.DELETE) {
                        var itemFulfillmentId = scriptContext.oldRecord.getValue({
                            //4.bodyfld
                            fieldId: 'custbody_cl_fulfillment_id'
                        });
                        //setting the API for canceling the fulfillments
                        let apiCredentials = "/admin/api/{version}/fulfillments/" + itemFulfillmentId + "/cancel.json";
                        log.debug("apiCredentials", apiCredentials);
                        // log.debug("PAYLOAD_OBJECT", PAYLOAD_OBJECT)
                        let Response = shopifyLibrary.requestShopify(
                            apiCredentials,
                            "POST",
                            PAYLOAD_OBJECT,
                        );
                    }


            }
        }
        return exports
    });

Leave a comment

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