Updating Rebate Records In Invoice Records.

/**
 * @NApiVersion 2.1
 * @NScriptType MapReduceScript
 */
define(['N/record', 'N/search'],
    /**
 * @param{record} record
 * @param{search} search
 */
    (record, search) => {
        /**
         * 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{
                return transactionSearchObj = search.create({
                    type: "transaction",
                    filters:
                    [
                        ["type","anyof","SalesOrd"], 
                        "AND", 
                        ["applyingtransaction.trandate","within","6/1/2024","7/30/2024"], 
                        "AND", 
                        ["applyingtransaction.type","anyof","CustInvc"], 
                        "AND", 
                        // ["formulanumeric: CASE WHEN ({custcol_nsts_rm_purchase_rebate} IS NULL OR {custcol_nsts_rm_purchase_rebate} = 0)  AND ({applyingtransaction.custcol_nsts_rm_purchase_rebate} IS NULL OR {applyingtransaction.custcol_nsts_rm_purchase_rebate} = 0)        THEN 0        ELSE 1 END","equalto","1"], 
                        // "AND", 
                        ["mainline","is","F"], 
                        "AND", 
                        ["cogs","is","F"], 
                        "AND", 
                        ["taxline","is","F"], 
                        "AND", 
                        ["shipping","is","F"], 
                        // "AND", 
                        // ["applyingtransaction.internalidnumber","equalto","7031515"]
                     ],
                    columns:
                    [
                       search.createColumn({
                          name: "applyingtransaction",
                          summary: "GROUP",
                          label: "INV"
                       })
                    ]
                 });
            }
            catch(e){
                log.error("error@getInputData", e);
                return [];
            }
        }

        /**
         * Defines the function that is executed when the map entry point is triggered. This entry point is triggered automatically
         * when the associated getInputData stage is complete. This function is applied to each key-value pair in the provided
         * context.
         * @param {Object} mapContext - Data collection containing the key-value pairs to process in the map stage. This parameter
         *     is provided automatically based on the results of the getInputData stage.
         * @param {Iterator} mapContext.errors - Serialized errors that were thrown during previous attempts to execute the map
         *     function on the current key-value pair
         * @param {number} mapContext.executionNo - Number of times the map function has been executed on the current key-value
         *     pair
         * @param {boolean} mapContext.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} mapContext.key - Key to be processed during the map stage
         * @param {string} mapContext.value - Value to be processed during the map stage
         * @since 2015.2
         */

        // const map = (mapContext) => {

        // }

        /**
         * 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) => {
            try{
                let searchResult = JSON.parse(reduceContext.values);
                log.debug("searchResult", searchResult);

                let invoiceRecord = record.load({ type:'invoice', id: searchResult.values[ "GROUP(applyingtransaction)"]['value']});
                let SalesOrdRec= record.load({ type:'salesorder', id: invoiceRecord.getValue({fieldId: 'createdfrom'})});

                let invLineCount = invoiceRecord.getLineCount({ sublistId: 'item' });
                let salesLineCount = SalesOrdRec.getLineCount({ sublistId: 'item' });

                for (let i = 0; i < invLineCount; i++) {
                    let orderLine = invoiceRecord.getSublistValue({ sublistId: 'item', fieldId: 'orderline', line: i });
                    for(let j=0; j<salesLineCount; j++){
                        let soLine = SalesOrdRec.getSublistValue({ sublistId: 'item', fieldId: 'line', line: j });
                        if(orderLine == soLine){
                            let rebateAmount = SalesOrdRec.getSublistValue({ sublistId: 'item', fieldId: 'custcol_nsts_rm_purchase_rebate', line: j });
                            let totalRebate = SalesOrdRec.getSublistValue({ sublistId: 'item', fieldId: 'custcol_nsts_rm_purchase_rebate_total', line: j });
                            let rebateSelected =  SalesOrdRec.getSublistValue({ sublistId: 'item', fieldId: 'custcol_nsts_rm_selected_rebates', line: j });
                            let gpAmount = SalesOrdRec.getSublistValue({ sublistId: 'item', fieldId: 'custcol_nsts_rm_gpamt_after_rebate', line: j });
                            let gpPercent = SalesOrdRec.getSublistValue({ sublistId: 'item', fieldId: 'custcol_nsts_rm_gppct_after_rebate', line: j });

                            log.debug("rebateAmount", rebateAmount);
                            log.debug("totalRebate", totalRebate);
                            log.debug("rebateSelected", rebateSelected);
                            log.debug("gpAmount", gpAmount);
                            log.debug("gpPercent", gpPercent);

                            invoiceRecord.setSublistValue({ sublistId: 'item', fieldId: 'custcol_nsts_rm_purchase_rebate', line: i, value: parseFloat(rebateAmount) });
                            invoiceRecord.setSublistValue({ sublistId: 'item', fieldId: 'custcol_nsts_rm_purchase_rebate_total', line: i, value: parseFloat(totalRebate) });
                            invoiceRecord.setSublistValue({ sublistId: 'item', fieldId: 'custcol_nsts_rm_selected_rebates', line: i, value: rebateSelected });
                            invoiceRecord.setSublistValue({ sublistId: 'item', fieldId: 'custcol_nsts_rm_gpamt_after_rebate', line: i, value: parseFloat(gpAmount) });
                            invoiceRecord.setSublistValue({ sublistId: 'item', fieldId: 'custcol_nsts_rm_gppct_after_rebate', line: i, value: parseFloat(gpPercent) });
                        }
                    }
                    
                            
                }
                invoiceRecord.save();

            }
            catch(e){
                log.error("error@reduce", 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) => {

        }

        return {getInputData,  reduce, summarize}

    });

Leave a comment

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