Get Customers from Big Commerce through API

Below Code is defined to get the customers from Big Commerce and create them in NetSuite if not exists

Script: Map-Reduce

/**
 * @NApiVersion 2.1
 * @NScriptType MapReduceScript
 * 
 * * The Nutty Company, Inc - USA-NS
 *
 * NUTC-46 : Existing Customer Sync From Big Commerce
 *
 *
 **************************************************************************************
 ********
 *
 * Author: Jobin and Jismi IT Services
 *
 * Date Created : 15-May-2023
 *
 * Description : This is a Scheduled script to sync the customer from Big Commerce
 *
 * REVISION HISTORY
 *
 * @version 1.0 NUTC-46 : 15-May-2023 : Created the initial build by JJ0131
 * **************************************************************************************
 * 
 */
define(["N/https", "N/record", "N/search", "../NUTC 40 Big Commerce Common Library/jj_big_commerce_common_library_nutc40.js"],
    /**
     * @param{https} https
     * @param{record} record
     * @param{search} search
     */
    (https, record, search, bigComLibrary) => {



        /**
         * Defines the function that is executed at the beginning of the map/reduce process and generates the input data.
         * @param {Object} inputContext
         * @param {boolean} inputContext.isRestarted - Indicates whether the current invocation of this function is the first
         *     invocation (if true, the current invocation is not the first invocation and this function has been restarted)
         * @param {Object} inputContext.ObjectRef - Object that references the input data
         * @typedef {Object} ObjectRef
         * @property {string|number} ObjectRef.id - Internal ID of the record instance that contains the input data
         * @property {string} ObjectRef.type - Type of the record instance that contains the input data
         * @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process
         * @since 2015.2
         */

        const getInputData = (inputContext) => {
            try {
                /*For developers using Live API,
                *Use Filtered API to create set of customers to avoid governance issues.
                *Use date_created:max and date_created:min as filters
                *Use '&page=' filter to include next page of customers if API contains > 50 customer data
                *let cusFilterAPI = '/v3/customers?date_created:max=2018-11-1&date_created:min=2018-9-1'; - live API
                */
                let cusFilterAPI = '/v3/customers?include=addresses&limit=3'; // for testing purpose only
                let response = bigComLibrary.commonFunctions.sendGetAPIRequest(cusFilterAPI);
                let getCustomers = JSON.parse(response.body);
                return getCustomers;

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

            }

        }

        /**
         * Defines the function that is executed when the reduce entry point is triggered. This entry point is triggered
         * automatically when the associated map stage is complete. This function is applied to each group in the provided context.
         * @param {Object} reduceContext - Data collection containing the groups to process in the reduce stage. This parameter is
         *     provided automatically based on the results of the map stage.
         * @param {Iterator} reduceContext.errors - Serialized errors that were thrown during previous attempts to execute the
         *     reduce function on the current group
         * @param {number} reduceContext.executionNo - Number of times the reduce function has been executed on the current group
         * @param {boolean} reduceContext.isRestarted - Indicates whether the current invocation of this function is the first
         *     invocation (if true, the current invocation is not the first invocation and this function has been restarted)
         * @param {string} reduceContext.key - Key to be processed during the reduce stage
         * @param {List<String>} reduceContext.values - All values associated with a unique key that was passed to the reduce stage
         *     for processing
         * @since 2015.2
         */
        const reduce = (reduceContext) => {
            let cusData = JSON.parse(reduceContext.values[0]);

            for (let i = 0; i < cusData.length; i++) {
                try {
                    //if no email on data, move to next customer
                    if (!cusData[i].email) {
                        continue;
                    }
                    let cusEmail = cusData[i].email;
                    let cusAddress = cusData[i].addresses
                    let cusSearch = bigComLibrary.savedSearch.fetchCustomerByEmail(cusEmail)
                    if (cusSearch.count == 0) {
                        //Customer record creation with neccessary values
                        let cusRecord = record.create({
                            type: 'customer',
                            isDynamic: true
                        });
                        if (cusData[i].company) {
                            cusRecord.setValue({
                                fieldId: 'companyname',
                                value: cusData[i].company
                            })
                        }
                        if (cusData[i].first_name && cusData[i].last_name) {
                            cusRecord.setValue({
                                fieldId: 'isperson',
                                value: "T"
                            });
                            cusRecord.setValue({
                                fieldId: 'companyname',
                                value: cusData[i].company
                            })
                            cusRecord.setValue({
                                fieldId: 'firstname',
                                value: cusData[i].first_name 
                            });
                            cusRecord.setValue({
                                fieldId: 'lastname',
                                value: cusData[i].last_name
                            });
                        }
                        cusRecord.setValue({
                            fieldId: 'email',
                            value: cusEmail
                        })
                        cusRecord.setValue({
                            fieldId: 'subsidiary',
                            value: "1"
                        })
                        cusRecord.setValue({
                            fieldId: 'phone',
                            value: cusData[i].phone
                        });
                        cusRecord.setValue({
                            fieldId: 'custentity_jj_big_com_customer_id',
                            value: cusData[i].id
                        });
                        let addressLineCount = cusAddress.length;
                        for (j = 0; j < addressLineCount; j++) {
                            cusRecord.selectLine({
                                sublistId: 'addressbook',
                                line: j
                            });
                            if (cusAddress[j].address_type == "residential") {
                                cusRecord.setCurrentSublistValue({
                                    sublistId: 'addressbook',
                                    fieldId: 'isresidential',
                                    value: true,
                                    line: j
                                })
                            }
                            let addressBook = cusRecord.getCurrentSublistSubrecord({
                                sublistId: 'addressbook',
                                fieldId: 'addressbookaddress'
                            });
                            addressBook.setValue({
                                fieldId: 'country',
                                value: cusAddress[j].country_code,
                            });
                            addressBook.setValue({
                                fieldId: 'addressee',
                                value: cusData[i].company || cusData[i].first_name + ' ' + cusData[i].last_name,
                            });
                            addressBook.setValue({
                                fieldId: 'addr1',
                                value: cusAddress[j].address1,
                            });
                            addressBook.setValue({
                                fieldId: 'addr2',
                                value: cusAddress[j].address2,
                            });
                            addressBook.setValue({
                                fieldId: 'addrphone',
                                value: cusAddress[j].phone,
                            });
                            addressBook.setValue({
                                fieldId: 'state',
                                value: cusAddress[j].state_or_province,
                            });
                            addressBook.setValue({
                                fieldId: 'zip',
                                value: cusAddress[j].postal_code,
                            });
                            cusRecord.commitLine({
                                sublistId: 'addressbook',
                            });
                        }
                        let cusRecId = cusRecord.save({ ignoreMandatoryFields: true });
                        log.debug("CustomerRecordID", cusRecId)
                    }
                    //if the customer exists in netsuite but if Big Commerce ID is null
                    else if (cusSearch.customerBigComId == "" || cusSearch.customerBigComId == null) {
                        record.submitFields({
                            type: 'customer',
                            id: cusSearch.customerNSId,
                            values: {
                                'custentity_jj_big_com_customer_id': cusData[i].id
                            },
                            options: {
                                ignoreMandatoryFields: true
                            }
                        });
                    }
                } catch (e) {
                    //Create error custom record if any error occurs on creation of customer
                    let cusErrRecord = record.create({
                        type: 'customrecord_jj_cr_bgcmrc_cus_syc_nutc46',
                    })
                    cusErrRecord.setValue({
                        fieldId: 'custrecord_jj_cus_sync_err',
                        value: e
                    });
                    cusErrRecord.setValue({
                        fieldId: 'custrecord_jj_bg_com_cus_id',
                        value: cusData[i].id
                    });
                    cusErrRecord.setValue({
                        fieldId: 'custrecord_jj_bg_com_cus_name',
                        value: cusData[i].company
                    });
                    cusErrRecord.setValue({
                        fieldId: 'custrecord_jj_bg_com_cus_email',
                        value: cusData[i].email
                    });
                    cusErrRecord.setValue({
                        fieldId: 'custrecord_jj_api_response_body',
                        value: cusData[i]
                    });
                    let errRecordId = cusErrRecord.save({ ignoreMandatoryFields: true });
                    log.error("Error Record ID", errRecordId);
                    log.error("error @ reduce", e);
                }
            }
        }
        
        return { getInputData, reduce }

    });

Leave a comment

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