Closing Sales Orders within 30 days

Close the sales order with a deposit of less than 50% and more than 10% in NetSuite will be closed in 30 days.

Consider the order with pending fulfillment status to close.

No need to close the orders which are already scheduled

/**
 * @NApiVersion 2.1
 * @NScriptType MapReduceScript
 */
/***************************************************************************
 * * Close Sales orders within 30 days which has customer
 *  deposit due greater than 10% and less than 50%
 * *************************************************************************
 *
 * Author: Jobin and Jismi IT Services
 *
 * Date Created :15-March-2023
 *
 * Created By: Aswathy,Jobin and Jismi IT Services
 *
 * Description : Close Sales orders within 30 days which has customer
 *  deposit due greater than 10% and less than 50%
 *
 * REVISION HISTORY
 *
 ***************************************************************************/
define(['N/record', 'N/search'],
    /**
 * @param{record} record
 * @param{search} search
 */
    (record, search) => {

        /**
         * Function to get the sales orders which created within 30 days ago
         * @returns {*[]}
         */
        function getSalesOrdersSearch()
        {
            try
            {
                let salesorderSearchObj = search.create({
                    type: "salesorder",
                    filters:
                        [
                            ["type","anyof","SalesOrd"],
                            "AND",
                            ["mainline","is","T"],
                            "AND",
                            ["status","anyof","SalesOrd:B"],
                            "AND",
                            ["customform","noneof","197"],
                            "AND",
                            ["custbody_jj_form_id","isnot","197"],
                            "AND",
                            ["datecreated","onorbefore","thirtydaysago"],

                        ],
                    columns:
                        [
                            search.createColumn({
                                name: "internalid",
                                summary: "GROUP",
                                sort: search.Sort.ASC,
                                label: "Internal ID"
                            }),
                            search.createColumn({
                                name: "netamount",
                                join: "applyingTransaction",
                                summary: "SUM",
                                label: "Amount (Net)"
                            }),
                            search.createColumn({
                                name: "netamount",
                                summary: "GROUP",
                                label: "Amount (Net)"
                            })
                        ]
                });
               let searchResultCount = salesorderSearchObj.runPaged().count;
                let salesOrderArray =[]
                if(searchResultCount > 0)
                {
                    salesorderSearchObj.run().each(function(result){
                        salesOrderObj = {}
                        salesOrderObj.internalId= result.getValue({
                            name: "internalid",
                            summary: "GROUP",
                            sort: search.Sort.ASC,
                            label: "Internal ID"
                        })
                        salesOrderObj.depositAmount = result.getValue({
                            name: "netamount",
                            join: "applyingTransaction",
                            summary: "SUM",
                            label: "Amount (Net)"
                        })
                        salesOrderObj.soAmount = result.getValue({
                            name: "netamount",
                            summary: "GROUP",
                            label: "Amount (Net)"
                        })

                       salesOrderArray.push(salesOrderObj)
                        return true;
                    });

                return salesOrderArray ;
                }
                else
                {
                    return []
                }



            }
            catch(err)
            {
                log.debug("error@getSalesOrdersSearch",err)
                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 salesOrderData = getSalesOrdersSearch();
                log.debug("salesOrderData",salesOrderData);
                let netSOAmount,depositAmount;
                let closingSalesOderArray =[];
                if(salesOrderData.length > 0)
                {
                    for(let i = 0; i <salesOrderData.length; i++)
                    {
                        let netSOAmount = parseFloat(salesOrderData[i].soAmount)
                        let depositAmount = parseFloat(salesOrderData[i].depositAmount)
                        log.debug("netSOAmount",netSOAmount)
                        log.debug("depositAmount",depositAmount)
                        if((depositAmount >(netSOAmount * 0.1)) && (depositAmount < (netSOAmount * 0.5)))
                        {
                            log.debug("if condition...")
                            closingSalesOderArray.push(salesOrderData[i].internalId)
                        }

                    }
                }

                return closingSalesOderArray;
            }
            catch(err)
            {

            }

        }


        /**
         * 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 dataObj=reduceContext.values.map(JSON.parse);
                let salesOrder = dataObj[0];
                log.debug("salesOrder",salesOrder);
                let salesOrderData= record.load({
                    type: record.Type.SALES_ORDER,
                    id: salesOrder,
                  // isDynamic: true
                });
                let depositDue = salesOrderData.getValue({fieldId: 'custbody_deposit_balance'});
                if (salesOrderData.getValue({fieldId: 'customform'}) != 197 && depositDue >0) {
                    let itemCounts = salesOrderData.getLineCount({sublistId: 'item'});
                    log.debug("itemCounts",itemCounts)

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

                        let item_closed = salesOrderData.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'isclosed',
                            line:i

                        });

                        let item_billed = salesOrderData.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantitybilled',
                            line:i

                        });

                        let item_fulfilled = salesOrderData.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantityfulfilled',
                            line:i

                        });
                        log.debug("item_fulfilled",item_fulfilled);
                        let item_pickpackship = salesOrderData.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'quantitypickpackship',
                            line:i

                        });

                        let dt_order = salesOrderData.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_dt_order',
                            line:i

                        });

                        let dt_account = salesOrderData.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_dt_acct',
                            line:i
                        });

                        let schedule_del_date= salesOrderData.getSublistValue({
                            sublistId: 'item',
                            fieldId: 'custcol_sched_del_date',
                            line:i
                        });

                        /**
                         * For closing the orders which are not fulfilled, billed, picked or packed and not scheduled
                         */
                        if (!item_closed) {
                            if (item_pickpackship <= 0 && item_fulfilled <= 0 && item_billed <= 0 && (!dt_order) && (!dt_account) && (!schedule_del_date)) {
                                log.debug("closing if condition...")
                                salesOrderData.setSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'custcol_jjreasonfordecommitahap237',
                                    value: 'Customer Deposit Value is less than 50% and greater than 10%',
                                    line:i,
                                    ignoreFieldChange: true
                                });
                                //  log.debug("Updated Reason Field");
                                let setclosed = salesOrderData.setSublistValue({
                                    sublistId: 'item',
                                    fieldId: 'isclosed',
                                    value: true,
                                    line:i,
                                    ignoreFieldChange: true
                                });

                            }
                        }
                     }
                    salesOrderData.save({
                        ignoreMandatoryFields: true,
                        enableSourcing: true
                    });
                    log.debug("Closed SO", salesOrder);
                }

            }
            catch(err)
            {
                log.debug("error@Reduce",err)
            }

        }

        return {getInputData, reduce}

    });

Leave a comment

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