Map reduce Script- Automatic credit notes generation

Requirements:

All the return authorizations which have the status Pending Refund, Pending Refund/Partially Received, and “Exclude Auto credit” unchecked will be taken and be creating credit notes through workflow/script. Return Authorization having the item “MISCSALE” will be excluded from the automatic credit note generation process.

An email notification will be sent to the corresponding customer on the creation of credit note.

ERROR HANDLING
A consolidated email will be sent as an error notification after the process if any credit note generation is failed.

/**
 * @NApiVersion 2.1
 * @NScriptType MapReduceScript
 */
/*******************************************************************************
 * CLIENTNAME: Flowco Ltd t/a Waterworks
 * FLTWN-182
 * Automatic credit Note creation.
 * **************************************************************************
 * Date : 20-10-2022
 * Author: Jobin & Jismi IT Services LLP
 * Script Description : Automatic credit Note creation.
 * Date created :20-10-2022
 ******************************************************************************/
define(['N/email', 'N/record', 'N/search','N/error'],
    /**
     * @param{email} email
     * @param{record} record
     * @param{search} search
     * @param {error} error
     */
    (email, record, search, error) => {
        /**
         * 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 transactionSearchObj = search.create({
                    type: "transaction",
                    filters:
                        [
                            ["status", "anyof", "RtnAuth:F", "RtnAuth:E"],
                        ],
                    columns:
                        [
                            search.createColumn({name: "internalid", summary: "GROUP", label: "Internal ID"}),
                            search.createColumn({
                                name: "formulanumeric",
                                summary: "SUM",
                                formula: "CASE  WHEN {item.internalid}= '7561' THEN 1 ELSE 0 END",    //7561 is the internal id of MISCSALE item
                                label: "Formula (Numeric)"
                            }),
                            search.createColumn({
                                name: "custbody_jj_exculde_auto_credit",
                                summary: "GROUP",
                                label: "Exclude From Auto Credit"
                            }),
                            search.createColumn({name: "email", join: "customerMain", summary: "GROUP", label: "Email"})
                        ]
                });
                return transactionSearchObj;
            }
            catch (e)
            {
                log.error({title: "error@getInputData", details: 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 raId;
            try
            {
                const data = JSON.parse(reduceContext.values);
                raId = data.values["GROUP(internalid)"]?.value;
                log.debug({title: "raId", details: raId});
                const excludeAutoCredit = data.values['GROUP(custbody_jj_exculde_auto_credit)'];
                const MISCSALECount = data.values['SUM(formulanumeric)'];
                const customerEmail = data.values['GROUP(email.customerMain)'];

                if( excludeAutoCredit === false || excludeAutoCredit === "F" || excludeAutoCredit === "false" || excludeAutoCredit === "False" || excludeAutoCredit === "FALSE")
                {
                    if (MISCSALECount === "0" || MISCSALECount === 0)
                    {
                        let creditNoteRecord =record.transform({
                            fromType:record.Type.RETURN_AUTHORIZATION,
                            fromId: raId,
                            toType: record.Type.CREDIT_MEMO,
                            isDynamic: true
                        });
                        creditNoteRecord.setValue({fieldId:"tobeemailed",value:true});
                        creditNoteRecord.setValue({fieldId:"email",value:customerEmail});
                        let creditNoteID = creditNoteRecord.save({ignoreMandatoryFields:true});
                        log.debug({title: "creditNoteID", details: creditNoteID});
                    }
                }
            }
            catch (e)
            {
                reduceContext.write({key:raId, value:e.message});
                log.error({title: "error in reduce", details: e});
            }
        }

        /**
         * Defines the function that is executed when the summarize entry point is triggered. This entry point is triggered
         * automatically when the associated reduce stage is complete. This function is applied to the entire result set.
         * @param {Object} summaryContext - Statistics about the execution of a map/reduce script
         * @param {number} summaryContext.concurrency - Maximum concurrency number when executing parallel tasks for the map/reduce
         *     script
         * @param {Date} summaryContext.dateCreated - The date and time when the map/reduce script began running
         * @param {boolean} summaryContext.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 {Iterator} summaryContext.output - Serialized keys and values that were saved as output during the reduce stage
         * @param {number} summaryContext.seconds - Total seconds elapsed when running the map/reduce script
         * @param {number} summaryContext.usage - Total number of governance usage units consumed when running the map/reduce
         *     script
         * @param {number} summaryContext.yields - Total number of yields when running the map/reduce script
         * @param {Object} summaryContext.inputSummary - Statistics about the input stage
         * @param {Object} summaryContext.mapSummary - Statistics about the map stage
         * @param {Object} summaryContext.reduceSummary - Statistics about the reduce stage
         * @since 2015.2
         */
        const summarize = (summaryContext) =>
        {
            try
            {
                let text = '';
                summaryContext.output.iterator().each(function(key, value) {
                    text += ( "Return Authorization ID:\t"+key + '\t  Error Message:\t' + value + '.\n');
                    return true;
                });
                if(text)
                {
                    let author = 22162;
                    let recipients = 'mariana.melo@waterworksnz.co.nz';
                    let subject = 'Error While Automatic Credit Note Creation';
                    email.send({
                        author: author,
                        recipients: recipients,
                        subject: subject,
                        body: text
                    });
                }
            }
            catch (err)
            {
                log.error({title: "error@summarize", details: err});
            }
        }
        return {getInputData, reduce, summarize}
    });

Leave a comment

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