Customer Statement using Mapreduce script

Jira Code: MAR-33

Description

We will have to write a MapReduce script which will be run at 8 am PST on the first Monday of every month. The proposed script will generate the customer statement of each customer by using the system preferred Template. And that statement will be emailed to the corresponding customer’s contacts that have “Email Invoices” checkbox checked if there is a balance for that customer.
On creating the Statement, we can set the Statement Date as Current Date (I.e. Date on which the email is scheduled) and leave the Start Date as empty
The statement should be consolidated and it should show only the open transactions
If there will not be any contact with “Email Invoices” checkbox checked or Email is missing on the contact, we can exclude those customers from sending emails

/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * MAR-33 MapReduceScript for sending the statement to the contact of customer 
 * **************************************************************************
 * 
 * Date: 26-07-2019
 * created on 26-07-2019 by AB
 * Author: Jobin & Jismi IT Services LLP
 * 
 *****************************************************************************
 **/
define(['N/email', 'N/record', 'N/file', 'N/render', 'N/search', 'N/runtime'],
    function(email, record, file, render, search, runtime) {

        /**
         * Marks the beginning of the Map/Reduce process and generates input data.
         *
         * @typedef {Object} ObjectRef
         * @property {number} id - Internal ID of the record instance
         * @property {string} type - Record type id
         *
         * @return {Array|Object|Search|RecordRef} inputSummary
         * @since 2015.1
         */
        var main = {
            getInputData: function() {
                var custArray = [];
                var customerSearchObj = search.create({
                    type: "customer",
                    filters: [
                        ["balance", "greaterthan", "0.00"],
                        /*"AND",
                        ["internalidnumber", "equalto", 2921]*/
                    ],
                    columns: [
                        search.createColumn({ name: "internalid", label: "Internal ID" }),
                        search.createColumn({
                            name: "entityid",
                            sort: search.Sort.ASC,
                            label: "Name"
                        })
                    ]
                });
                var searchResultCount = customerSearchObj.runPaged().count;
                log.debug("customerSearchObj result count", searchResultCount);
                customerSearchObj.run().each(function(result) {
                    // .run().each has a limit of 4,000 results
                    var customerId = result.getValue(customerSearchObj.columns[0]);
                    var custName = result.getValue(customerSearchObj.columns[1]);
                    custArray.push({
                        customerId: customerId,
                        custName: custName
                    });
                    return true;
                });
                log.debug('custArray', custArray);
                return custArray
            },

            /**
             * Executes when the map entry point is triggered and applies to each key/value pair.
             *
             * @param {MapSummary} context - Data collection containing the key/value pairs to process through the map stage
             * @since 2015.1
             */
            /*map: function(context) {

            },*/

            /**
             * Executes when the reduce entry point is triggered and applies to each group.
             *
             * @param {ReduceSummary} context - Data collection containing the groups to process through the reduce stage
             * @since 2015.1
             */
            reduce: function(params) {
                log.debug('params', JSON.parse(params.values[0]));
                var listCust = JSON.parse(params.values[0])
                var contactEmailArr = main.searchContact(listCust.customerId); // the array of contact that the check box is ticked
                log.debug('params.values[0]', listCust.customerId);
                //var EntID = 16014 //parseInt(params.values[0]);

                var date = main.DateNow()
                log.debug('date', JSON.stringify(date))

                var userObj = listCust.custName // name of the customer

                var senderId = 22175 //sender id that mail that send from, it must be an employee
                log.debug('senderId', senderId)

                if (contactEmailArr.length > 0) {
                    var transactionFile = render.statement({
                        entityId: JSON.parse(listCust.customerId), //16014,
                        printMode: render.PrintMode.PDF,
                        openTransactionsOnly: true,
                        statementDate: date,
                        inCustLocale: true
                    });
                    transactionFile.folder = 81669; // the pdf is store
                    var fileId = transactionFile.save();
                    email.send({
                        author: senderId,
                        recipients: contactEmailArr,
                        subject: 'Estatement',
                        body: 'Hello' + ' ' + ',' + '\n\nPlease find attached your current statement.' + '\n\nThank you,' + '\n\nAccounting A/R' + '\n310-333-0606 x1189' + '\n800-800-6608' + '\n\nMarshall Electronics, Inc.' + '\n20608 Madrona Avenue' + '\nTorrance, CA 90503' + '\nwww.Marshall-USA.com',
                        attachments: [transactionFile]
                    });
                    log.debug('test', 'test');
                }
                log.debug('test123', 'tert234');

            },


            /**
             * Executes when the summarize entry point is triggered and applies to the result set.
             *
             * @param {Summary} summary - Holds statistics regarding the execution of a map/reduce script
             * @since 2015.1
             */
            /*summarize: function(summary) {

            },*/
            DateNow: function() {
                var today = new Date();
                var dd = today.getDate();
                var mm = today.getMonth() + 1;
                var yyyy = today.getFullYear();
                today = mm + '/' + dd + '/' + yyyy; // change the format depending on the date format preferences set on your account
                return today;
            },
            searchContact: function(internalId) {
                var listArray = []
                var list = []
                var customerContactSearchObj = search.create({
                    type: "customer",
                    filters: [
                        ["contact.custentity_cck_email_invoices", "is", "T"],
                        "AND",
                        ["internalidnumber", "equalto", internalId],
                        "AND",
                        ["contact.email", "isnotempty", ""]
                    ],
                    columns: [
                        search.createColumn({
                            name: "entityid",
                            sort: search.Sort.ASC,
                            label: "Name"
                        }),
                        search.createColumn({ name: "email", label: "Email" }),
                        search.createColumn({ name: "phone", label: "Phone" }),
                        search.createColumn({ name: "contact", label: "Primary Contact" }),
                        search.createColumn({ name: "altemail", label: "Alt. Email" }),
                        search.createColumn({
                            name: "email",
                            join: "contact",
                            label: "Email"
                        }),
                        search.createColumn({
                            name: "internalid",
                            join: "contact",
                            label: "Internal ID"
                        })
                    ]
                });
                var searchResultCount = customerContactSearchObj.runPaged().count;

                if (searchResultCount > 0) {

                    log.debug("customerContactSearchObj result count", searchResultCount);
                    customerContactSearchObj.run().each(function(result) {
                        // .run().each has a limit of 4,000 results
                        var contactId = result.getValue(customerContactSearchObj.columns[6]);
                        var contactEmailId = result.getValue(customerContactSearchObj.columns[5]);
                        //emailid of the contact


                        listArray.push(contactEmailId);
                        list.push(contactId);
                        log.debug(listArray, list);
                        return true;
                    });
                }
                return list //the array of contacts of the customer
            }

        }


        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 false
                }
            }
        };
        return main;

    });

Leave a comment

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