Script To Delete Duplicate Lines From TO

Clients have some duplicate lines in the TO. They need to remove the duplicated lines from the TO.

/**
 * @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 {
                var transferorderSearchObj = search.create({
                    type: "transferorder",
                    filters:
                        [
                            ["type", "anyof", "TrnfrOrd"],
                            "AND",
                            ["linesystemnotes.date", "on", "28.07.2023 23:59"],
                            "AND",
                            ["linesystemnotes.field", "anyof", "TRANLINE.RQTYSHIPRECV"],
                            "AND",
                            ["linesystemnotes.name", "anyof", "10065"],
                            "AND",
                            ["quantity", "greaterthanorequalto", "1"],
                            "AND",
                            ["transactionlinetype", "anyof", "ITEM"],
                          //  "AND",
                          //  ['internalid', 'anyof', '112681'],
                        ],
                    columns:
                        [
                            search.createColumn({ name: "trandate", label: "Date" }),
                            search.createColumn({ name: "postingperiod", label: "Period" }),
                            search.createColumn({ name: "taxperiod", label: "Tax Period" }),
                            search.createColumn({ name: "type", label: "Type" }),
                            search.createColumn({ name: "tranid", label: "Document Number" }),
                            search.createColumn({ name: "entity", label: "Name" }),
                            search.createColumn({ name: "account", label: "Account" }),
                            search.createColumn({ name: "memo", label: "Memo" }),
                            search.createColumn({ name: "amount", label: "Amount" }),
                            search.createColumn({ name: "item", label: "Item" }),
                            search.createColumn({ name: "quantity", label: "Quantity" }),
                            search.createColumn({ name: "line", label: "Line ID" }),
                            search.createColumn({ name: "line.cseg2", label: "Geography" }),
                            search.createColumn({ name: "custbody_rf_po_pur_reason", label: "Purchase Reason" }),
                            search.createColumn({ name: "custbody_rf_po_delivery_instructions", label: "Delivery Instructions" }),
                            search.createColumn({ name: "custbody_rf_so_full_payment_received", label: "Fulfillment Allowed" }),
                            search.createColumn({ name: "custbody_rf_bank_name", label: "Bank Name" }),
                            search.createColumn({ name: "custbody_rf_subsidiary_information", label: "Subsidiary Information" }),
                            search.createColumn({ name: "custbody_rf_swift_code", label: "Swift Code" }),
                            search.createColumn({ name: "custbody_rf_address_line1", label: "Address Line1" }),
                            search.createColumn({ name: "custbody_rf_address_line2", label: "Address Line2" }),
                            search.createColumn({ name: "custbody_rf_country", label: "Country" }),
                            search.createColumn({ name: "custbody_rf_state", label: "State" }),
                            search.createColumn({ name: "custbody_rf_currency", label: "Currency" }),
                            search.createColumn({ name: "custbody_rf_ach_routing_no", label: "ACH ROUTING NO" }),
                            search.createColumn({ name: "custbody_rf_account_name", label: "Account Name" }),
                            search.createColumn({ name: "custbody_rf_pro_inv_sale_rep_email", label: "RF Sales Rep Email" }),
                            search.createColumn({ name: "custbody_rf_subsidiary_log_proforma", label: "Subsidiary Logo for Proforma Invoice" }),
                            search.createColumn({ name: "custbody_rf_so_customer_category", label: "Customer Category" }),
                            search.createColumn({ name: "custbody_rf_transaction_created_by", label: "Transaction CreatedBy" }),
                            search.createColumn({ name: "custbody_rf_transaction_approver", label: "Transaction Approver" }),
                            search.createColumn({ name: "custbody_10184_customer_entity_bank", label: "Entity Bank (Customer)" }),
                            search.createColumn({ name: "custbody5", label: "DELETE ME" }),
                            search.createColumn({ name: "cseg1", label: "Marketplace" }),
                            search.createColumn({ name: "cseg2", label: "Geography" }),
                            search.createColumn({ name: "subsidiary", label: "Subsidiary" }),
                            search.createColumn({ name: "transferlocation", label: "To Location" }),
                            search.createColumn({
                                name: "name",
                                join: "fromLocation",
                                label: "Name"
                            }),
                            search.createColumn({ name: "firmed", label: "Firmed" }),
                            search.createColumn({ name: "custbody_jj_total_landed_cost", label: "Total Landed Cost" }),
                            search.createColumn({ name: "custbody_jj_landed_cost_perkg", label: "Total Landed Cost Per KG" }),
                            search.createColumn({ name: "custbody_jj_landedcost_error", label: "Landed Cost Error Field" }),
                            search.createColumn({ name: "custbody4", label: "Shipment Mode" }),
                            search.createColumn({ name: "incoterm", label: "Incoterm" }),
                            search.createColumn({ name: "istransferpricecosting", label: "Use Item Cost as Transfer Cost" }),
                            search.createColumn({ name: "custbody3", label: "Expected Receipt Date" }),
                            search.createColumn({ name: "department", label: "Cost Center" }),
                            search.createColumn({ name: "class", label: "Brand" }),
                            search.createColumn({ name: "custbody_in8_amzn_pkg_count", label: "In8 Amazon Package Count" }),
                            search.createColumn({ name: "custbody_in8_amzn_stg", label: "In8 Amazon Setting" }),
                            search.createColumn({ name: "custbody_in8_amzn_autosend_label", label: "In8 Amazon Auto Send Labels" }),
                            search.createColumn({ name: "custbody_in8_amzn_email_sent", label: "In8 Amazon Sent Labels" }),
                            search.createColumn({ name: "custbody_in8_amzn_shiplabel", label: "In8 Amazon Shipping Label" }),
                            search.createColumn({ name: "custcol_in8_amazon_id", label: "In8 Amazon Id" }),
                            search.createColumn({ name: "shipto", label: "Ship To" }),
                            search.createColumn({ name: "shipcomplete", label: "Ship Complete" }),
                            search.createColumn({ name: "shipaddress", label: "Shipping Address" }),
                            search.createColumn({ name: "shipcarrier", label: "Shipping Carrier" }),
                            search.createColumn({ name: "trackingnumbers", label: "Tracking Numbers" }),
                            search.createColumn({ name: "shipdate", label: "Ship Date" }),
                            search.createColumn({
                                name: "transferprice",
                                join: "item",
                                label: "Transfer Price"
                            }),
                            search.createColumn({ name: "custcol_jj_item_weight", label: "Item Weight Per Quantity" }),
                            search.createColumn({ name: "unit", label: "Units" }),
                            search.createColumn({ name: "amount", label: "Amount" }),
                            search.createColumn({
                                name: "salesdescription",
                                join: "item",
                                label: "Description"
                            }),
                            search.createColumn({
                                name: "cseg2",
                                join: "item",
                                label: "Geography"
                            }),
                            search.createColumn({ name: "closed", label: "Closed" }),
                            search.createColumn({
                                name: "cseg1",
                                join: "item",
                                label: "Marketplace"
                            }),
                            search.createColumn({
                                name: "class",
                                join: "item",
                                label: "Brand"
                            }),
                            search.createColumn({
                                name: "department",
                                join: "item",
                                label: "Cost Center"
                            }),
                            search.createColumn({ name: "options", label: "Options" }),
                            search.createColumn({ name: "orderpriority", label: "Order Priority" }),
                            search.createColumn({ name: "commitmentfirm", label: "Commitment Firm" }),
                            search.createColumn({ name: "commit", label: "Commit" }),
                            search.createColumn({ name: "shiprecvstatusline", label: "Fulfilled/Received (Line Level)" }),
                            search.createColumn({ name: "statusref", label: "Status" }),
                            search.createColumn({
                                name: "quantity",
                                join: "appliedToTransaction",
                                label: "Quantity"
                            }),
                            search.createColumn({ name: "quantitycommitted", label: "Quantity Committed" }),
                            search.createColumn({ name: "quantitybilled", label: "Quantity Billed" }),
                            search.createColumn({ name: "quantityshiprecv", label: "Quantity Fulfilled/Received" }),
                            search.createColumn({ name: "quantityuom", label: "Quantity in Transaction Units" }),
                            search.createColumn({ name: "quantityonshipments", label: "Quantity on Shipments" }),
                            search.createColumn({ name: "transactionlinetype", label: "Transaction Line Type" })
                        ]
                });
                var searchResultCount = transferorderSearchObj.runPaged().count;
                if (searchResultCount > 0) {
                    return transferorderSearchObj;
                } else {
                    return []
                }
            }
            catch (e) {
                log.error("error@getInput", 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) => {
            try {
                // log.debug("Result",JSON.parse(mapContext.value))
                let searchResultInMap = JSON.parse(mapContext.value)
                let internalId = searchResultInMap.id;
                mapContext.write({
                    key: internalId,
                    value: searchResultInMap
                });
            }
            catch (e) {
                log.error("error@map", 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) => {
            try {
                log.debug("Result In Reduce", reduceContext.values.map(JSON.parse))
                let searchResultInReduce = reduceContext.values.map(JSON.parse);
                let toRecord = record.load({
                    type: record.Type.TRANSFER_ORDER,
                    id: searchResultInReduce[0].id,
                    isDynamic: false,
                });
                log.debug("toRecord", toRecord);
                let lineCount = toRecord.getLineCount({ sublistId: 'item' });
                for (let i = lineCount; i > 0; i--) {
                    let itemTO = toRecord.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'item',
                        line: i
                    });
                    for (let j = 0; j < searchResultInReduce.length; j++) {
                        let itemInReduce = searchResultInReduce[j].values.item.value;
                        //log.debug("itemInReduce",itemInReduce)
                        if (itemTO == itemInReduce) {
                            //log.debug("Inside First If");
                            let quantity = toRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'quantity',
                                line: i
                            });
                            //log.debug("quantity",quantity)
                            let lineIdInItem = toRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'line',
                                line: i
                            });
                            let isClosed = toRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'isclosed',
                                line: i
                            });
                            let lineMemo = toRecord.getSublistValue({
                                sublistId: 'item',
                                fieldId: 'custcol_rf_to_memo_line_descrition',
                                line: i
                            });
                            //log.debug("lineIdInItem",lineIdInItem)
                            let lineIdInReduce = searchResultInReduce[j].values.line
                            //log.debug("lineIdInReduce",lineIdInReduce)
                            if (lineIdInItem == lineIdInReduce && quantity == 1 && isClosed && lineMemo == 'Duplicated Line') {
                                log.debug("Item & Quantity", itemInReduce + " Reduce Item " + itemTO + " Line Item " + lineIdInItem + " Line Reduce " + lineIdInReduce + " Item Quantity " + quantity);
                                // toRecord.setSublistValue({
                                //     sublistId: 'item',
                                //     fieldId: 'custcol_rf_to_memo_line_descrition',
                                //     value: 'Duplicated Line',
                                //     line : i
                                // });
                                // toRecord.setSublistValue({
                                //     sublistId: 'item',
                                //     fieldId: 'isclosed',
                                //     value: true,
                                //     line : i
                                // });
                                //isclosed
                               
                                // For removing the lines
                                toRecord.removeLine({
                                    sublistId: 'item',
                                    line: i,
                                    ignoreRecalc: true
                                });
                            }
                        }

                    }
                }
                toRecord.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, map, reduce, summarize }

    });

Leave a comment

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