Map reduce script to read the data from the API and create custom record in NetSuite

/**

 * @NApiVersion 2.1

 * @NScriptType MapReduceScript

 */

define([‘N/http’, ‘N/https’, ‘N/record’, ‘N/search’],

    /**

 * @param{http} http

 * @param{https} https

 * @param{record} record

 * @param{search} search

 */

    (http, https, record, search) => {

        /**

         * Function to convert date to desired format

         * @params {dateStr} – transaction date

         * @returns {formattedDate}

         *

         */

        function convertDateFormat(dateStr) {

            try {

                // Split the date and time parts

                const [datePart, timePart] = dateStr.split(‘ ‘);

                // Split the date part into day, month, and year

                const [day, month, year] = datePart.split(‘-‘).map(Number);

                // Split the time part into hour, minute, second

                const [hour, minute, second] = timePart.split(‘:’).map(Number);

                // Create a new Date object

                const date = new Date(year, month 1, day, hour, minute, second);

                // Format the date to “Month Day, Year HH:MM:SS AM/PM”

                const monthNames = [“January”, “February”, “March”, “April”, “May”, “June”,

                    “July”, “August”, “September”, “October”, “November”, “December”];

                const formattedDate = `${monthNames[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()} ` +

                    `${((date.getHours() + 11) % 12 + 1)}:${date.getMinutes().toString().padStart(2, ‘0’)}:` +

                    `${date.getSeconds().toString().padStart(2, ‘0’)} ` +

                    `${date.getHours() >= 12 ? ‘PM’ : ‘AM’}`;

                return formattedDate;

            } catch (e) {

                log.error(‘Error converting date format’, e);

                return null;

            }

        }

        /**

         * Function to create custom record

         * @params {parentData} -reduce Values

         * @params {transaction}

         *

         */

        function createCustomRecord(parentData, transaction) {

            try {

                let customRecord = record.create({

                    type: ‘customrecord_jj_transaction_details_gxin’,

                    isDynamic: true

                });

                log.debug(“transaction”, transaction);

                log.debug(“transaction.TXNDATE”, transaction.TXNDATE);

                convertedTxnDate = convertDateFormat(transaction.TXNDATE);

                log.debug(“convertedTxnDate”, convertedTxnDate);

                // Set transaction data fields

                customRecord.setValue({

                    fieldId: ‘custrecord_jj_bank_check_no’,

                    value: transaction.CHEQUENO

                });

                //let txnDate = new Date(“May 22, 2024 12:58:21 PM”);

                let txnDate = new Date(convertedTxnDate);

                customRecord.setValue({

                    fieldId: ‘custrecord_jj_bank_txn_date_gxin_650’,

                    value: txnDate

                });

                customRecord.setValue({

                    fieldId: ‘custrecord_jj_bank_memo_gxin_650’,

                    value: transaction.REMARKS

                });

                customRecord.setValue({

                    fieldId: ‘custrecord_jj_bank_amount_gxin_650’,

                    value: transaction.AMOUNT

                });

                customRecord.setValue({

                    fieldId: ‘custrecord_jj_balance_amount’,

                    value: transaction.BALANCE

                });

                customRecord.setValue({

                    fieldId: ‘custrecord_jj_bank_type_gxin_650’,

                    value: transaction.TYPE

                });

                customRecord.setValue({

                    fieldId: ‘custrecord_jj_bank_transaction_id’,

                    value: transaction.TRANSACTIONID

                });

                // Save the custom record

                let recordId = customRecord.save();

                log.debug(‘Custom record created with ID’, recordId);

            } catch (e) {

                log.error(‘Error creating custom record’, e);

            }

        }

        /**

        * Function to search the request body for Integration

        * @return {searchResults}

        */

        function getResponse() {

            try {

                let customrecord_jj_bank_config_gxin_650SearchObj = search.create({

                    type: “customrecord_jj_bank_config_gxin_650”,

                    filters:

                        [

                            [“isinactive”, “is”, “F”],

                            “AND”,

                            [“custrecord_jj_group_name”, “anyof”, “3”]

                        ],

                    columns:

                        [

                            search.createColumn({ name: “custrecord_jj_urn”, label: “URN” }),

                            search.createColumn({ name: “custrecord_jj_account_number”, label: “Account Number” }),

                            search.createColumn({ name: “custrecord_jj_bank_aggr_id”, label: “AGGR_ID” }),

                            search.createColumn({ name: “custrecord_jj_corp_id”, label: “CORP_ID” }),

                            search.createColumn({ name: “custrecord_jj_user_id”, label: “USER_ID” }),

                            search.createColumn({

                                name: “formuladate”,

                                formula: “{today}-1”,

                                label: “FROMDATE”

                            }),

                            search.createColumn({

                                name: “formuladate”,

                                formula: “{today}”,

                                label: “TODATE”

                            })

                        ]

                });

                let searchResultCount = customrecord_jj_bank_config_gxin_650SearchObj.runPaged().count;

                log.debug(“customrecord_jj_bank_config_gxin_650SearchObj result count”, searchResultCount);

                let searchResults = [];

                customrecord_jj_bank_config_gxin_650SearchObj.run().each(function (result) {

                    let responseObj = {};

                    responseObj.URN = result.getValue({ name: ‘custrecord_jj_urn’ });

                    responseObj.ACCOUNTNO = result.getValue({ name: ‘custrecord_jj_account_number’ });

                    responseObj.AGGRID = result.getValue({ name: ‘custrecord_jj_bank_aggr_id’ });

                    responseObj.CORPID = result.getValue({ name: ‘custrecord_jj_corp_id’ });

                    responseObj.USERID = result.getValue({ name: ‘custrecord_jj_user_id’ });

                    responseObj.FROMDATE = result.getValue({ name: ‘formuladate’, label: ‘FROMDATE’ });

                    responseObj.TODATE = result.getValue({ name: ‘formuladate’, label: ‘TODATE’ });

                    searchResults.push(responseObj);

                    return true;

                });

                return searchResults;

            } catch (e) {

                log.debug(“error @getResponse”, e);

                return []

            }

        }

        /**

         * 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 {

                let savedSearchResponse = getResponse()

                log.debug(“savedSearchResponse”, savedSearchResponse);

                let arraylen = savedSearchResponse.length;

                log.debug(“arraylen”, arraylen);

                let responseBodies = [];

                for (let i = 0; i < arraylen; i++) {

                    let body = savedSearchResponse[i];

                    log.debug(“body”, body);

                    let getApiBody = JSON.stringify(body);

                    let url = ‘https://finance.g10x.com/fetchStatement’;

                    let headerObj = {

                        ‘Content-Type’: ‘application/json’,

                        ‘Accept-Language’: ‘en-us’,

                        ‘name’: ‘Accept-Language’

                    }

                    let response = https.post({

                        url: url,

                        headers: headerObj,

                        body: getApiBody

                    });

                    log.debug(“response”, response);

                    if (response.code == 200) {

                        let responseBody = response.body;

                        log.debug(“responseBody”, responseBody);

                        // Push the responseBody to the responseBodies array

                        responseBodies.push(responseBody);

                        log.debug(“responseBodies”, responseBodies)

                        return responseBodies;

                    }

                    else {

                        log.debug(“Failed response”, response);

                    }

                }

            } 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 reduceValues = JSON.parse(reduceContext.values);

            log.debug(“reduceValues”, reduceValues);

            // let reduceArraylen = responseValues.length;

            // log.debug(“reduceArraylen”, reduceArraylen);

            let records = reduceValues.Record;

            log.debug(“records”, records);

            if (Array.isArray(records)) {

                records.forEach(function (transaction) {

                    // Create a custom record in NetSuite with the transaction data

                    createCustomRecord(reduceValues, transaction);

                });

            }

        }

     

        return { getInputData, reduce, }

    });

Leave a comment

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