Related records of a sales order

        /**

         * @description get related customer payments

         * @param {integer} salesOrderRecordId

         * @returns

         */

        function getCustomerPayment(salesOrderRecordId) {

            try {

                let customerPayment = [];

                let invoiceSearchObj = search.create({

                    type: “invoice”,

                    filters:

                        [

                            [“type”, “anyof”, “CustInvc”],

                            “AND”,

                            [“createdfrom”, “anyof”, salesOrderRecordId],

                            “AND”,

                            [“taxline”, “is”, “F”],

                            “AND”,

                            [“shipping”, “is”, “F”],

                            “AND”,

                            [“cogs”, “is”, “F”],

                            “AND”,

                            [“mainline”, “is”, “T”],

                            “AND”,

                            [“applyingtransaction.type”, “anyof”, “CustPymt”]

                        ],

                    columns:

                        [

                            search.createColumn({ name: “applyingtransaction”, label: “Applying Transaction” }),

                            search.createColumn({

                                name: “trandate”,

                                join: “applyingTransaction”,

                                label: “Date”

                            }),

                            search.createColumn({

                                name: “amount”,

                                join: “applyingTransaction”,

                                label: “Amount”

                            }),

                            search.createColumn({ name: “tranid”, label: “Document Number” }),

                            search.createColumn({ name: “amount”, label: “Amount” })

                        ]

                });

                let applySum = 0;

                let searchResultCount = invoiceSearchObj.runPaged().count;

                log.debug(“invoiceSearchObj result count”, searchResultCount);

                let invoiceArray = [];

                let invoiceSum = 0;

                invoiceSearchObj.run().each(function (result) {

                    let invoiceId = result.getValue({ name: “tranid”, label: “Document Number” });

                    let invoiceAmount = Number(result.getValue({ name: “amount”, label: “Amount” }));

                    // Check if the invoiceId already exists in the invoiceArray

                    let isDuplicate = invoiceArray.some(function (invoice) {

                        return invoice.document === invoiceId;

                    });

                    let custDeposit = {

                        document: result.getValue({ name: “applyingtransaction”, label: “Applying Transaction” }),

                        date: result.getValue({ name: “trandate”, join: “applyingTransaction”, label: “Date” }),

                        amount: result.getValue({ name: “amount”, join: “applyingTransaction”, label: “Amount” })

                    };

                    applySum = applySum + Number(result.getValue({ name: “amount”, join: “applyingTransaction”, label: “Amount” }))

                    if (!isDuplicate) {

                        // If it’s not a duplicate, sum the amount and add to the invoiceArray

                        invoiceSum += invoiceAmount;

                        let invObj = {

                            document: invoiceId,

                            date: result.getValue({ name: “trandate”, join: “applyingTransaction”, label: “Date” }),

                            amount: invoiceAmount

                        };

                        invoiceArray.push(invObj);

                    } else {

                        log.debug(“Duplicate Invoice Skipped”, invoiceId);

                    }

                    log.debug(“custDeposit”, custDeposit);

                    customerPayment.push(custDeposit);

                    return true;

                });

                log.debug(“applySum….”, applySum);

                log.debug(“Total Invoice Sum”, invoiceSum);

                let difference = invoiceSum + applySum;

                difference = difference.toFixed(2);

                log.debug(“difference……….”, difference)

                return { customerPayment: customerPayment, difference: difference };

            } catch (e) {

                log.error(“error@getCustomerPayment”, e);

            }

        }

/**

         * @description get the related return authorizations

         * @param {integer} salesOrderRecordId

         * @returns

         */

        function getReturnAuthorization(salesOrderRecordId) {

            try {

                let returnAuthorization = [];

                let returnauthorizationSearchObj = search.create({

                    type: “returnauthorization”,

                    filters:

                        [

                            [“type”, “anyof”, “RtnAuth”],

                            “AND”,

                            [“taxline”, “is”, “F”],

                            “AND”,

                            [“shipping”, “is”, “F”],

                            “AND”,

                            [“cogs”, “is”, “F”],

                            “AND”,

                            [“mainline”, “is”, “T”],

                            “AND”,

                            [[“createdfrom.internalid”, “anyof”, salesOrderRecordId], “OR”, [“appliedtotransaction.createdfrom”, “anyof”, salesOrderRecordId]]

                        ],

                    columns:

                        [

                            search.createColumn({ name: “tranid”, label: “Document Number” }),

                            search.createColumn({ name: “trandate”, label: “Date” }),

                            search.createColumn({ name: “amount”, label: “Amount” })

                        ]

                });

                let searchResultCount = returnauthorizationSearchObj.runPaged().count;

                log.debug(“returnauthorizationSearchObj result count”, searchResultCount);

                returnauthorizationSearchObj.run().each(function (result) {

                    let returnAuth = {

                        document: result.getValue({ name: “tranid”, label: “Document Number” }),

                        date: result.getValue({ name: “trandate”, label: “Date” }),

                        amount: result.getValue({ name: “amount”, label: “Amount” })

                    };

                    returnAuthorization.push(returnAuth);

                    return true;

                });

                return returnAuthorization;

            } catch (e) {

                log.error(“error@getReturnAuthorization”, e);

            }

        }

        /**

         * @description get related customer deposits

         * @param {integer} salesOrderRecordId

         * @returns

         */

        function getCustomerDeposits(salesOrderRecordId) {

            try {

                let customerDeposits = [];

                let customerdepositSearchObj = search.create({

                    type: “transaction”,

                    filters: [

                        [“type”, “anyof”, ‘CustDep’],

                        “AND”,

                        [“createdfrom.internalid”, “anyof”, salesOrderRecordId],

                        “AND”,

                        [“mainline”, “is”, “T”]

                    ],

                    columns: [

                        search.createColumn({ name: “tranid”, label: “Document Number” }),

                        search.createColumn({ name: “trandate”, label: “Date” }),

                        search.createColumn({ name: “amount”, label: “Amount” })

                    ]

                });

                customerdepositSearchObj.run().each(function (result) {

                    let deposit = {

                        document: result.getValue({ name: “tranid”, label: “Document Number” }),

                        date: result.getValue({ name: “trandate”, label: “Date” }),

                        amount: result.getValue({ name: “amount”, label: “Amount” })

                    };

                    customerDeposits.push(deposit);

                    return true;

                });

                return customerDeposits;

            } catch (e) {

                log.error(“error@getCustomerDeposits”, e);

            }

        }

      function removeDuplicatesAndEmpty(creditOrRefund) {

            // Create a Set to track unique entries

            let seen = new Set();

           

            // Filter the array to remove empty objects and duplicates

            return creditOrRefund.filter(item => {

                // Check if the object is empty

                if (Object.keys(item).length === 0) {

                    return false;

                }

               

                // Create a unique key from the object values to identify duplicates

                let key = `${item.document}${item.date}${item.applyAmount}`;

               

                // Check if the key has been seen before

                if (seen.has(key)) {

                    return false;

                } else {

                    // Add the key to the Set and keep the object

                    seen.add(key);

                    return true;

                }

            });

        }

        /**

         * @description get related credit memos/Refunds

         * @param {integer} salesOrderRecordId

         * @returns

         */

        function creditRefund(salesOrderRecordId) {

            try {

                let creditorRefundArray = [];

                let invoiceSearchObj = search.create({

                    type: “transaction”,

                    filters:

                        [

                            [“type”, “anyof”, “CustInvc”, “RtnAuth”],

                            “AND”,

                            [“appliedtotransaction.internalid”, “anyof”, salesOrderRecordId],

                            “AND”,

                            [“mainline”, “is”, “F”],

                            “AND”,

                            [“applyingtransaction.type”, “anyof”, “CustCred”, “CashRfnd”, “CustRfnd”, “CardRfnd”,“RtnAuth”]

                        ],

                    columns:

                        [

                            search.createColumn({ name: “appliedtotransaction”, label: “Applied To Transaction” }),

                            search.createColumn({ name: “applyingtransaction”, label: “Applying Transaction” }),

                            search.createColumn({name: “type”, label: “Type”}),

                            search.createColumn({

                                name: “amount”,

                                join: “applyingTransaction”,

                                label: “Amount”

                            }),

                            search.createColumn({

                                name: “tranid”,

                                join: “applyingTransaction”,

                                label: “Document Number”

                            }),

                            search.createColumn({

                                name: “trandate”,

                                join: “applyingTransaction”,

                                label: “Date”

                            }),

                            search.createColumn({

                                name: “applyingtransaction”,

                                join: “applyingTransaction”,

                                label: “Applying Transaction”

                            })

                        ]

                });

                let searchResultCount = invoiceSearchObj.runPaged().count;

                log.debug(“Credit/refund count”, searchResultCount);

                let sumCreditOrRefund = 0;

                let applyingArray = [];

                var processedApplyings = [];

invoiceSearchObj.run().each(function (result) {

    let credit = {};

    let applying = result.getValue({

        name: “applyingtransaction”,

        join: “applyingTransaction”,

        label: “Applying Transaction”

    });

   

    log.debug(“applying….”, applying);

    // Check if ‘applying’ is not empty and hasn’t been processed before

    if (applying && !processedApplyings.includes(applying)) {

        // Add ‘applying’ to the processed array to avoid duplicates

        processedApplyings.push(applying);

        var lookUpApplyingType = search.lookupFields({

            type: ‘transaction’,

            id: applying,

            columns: [‘type’, ‘amount’, ‘tranid’, ‘trandate’]

        });

        let applyingType = lookUpApplyingType.type;

        let applyAmount = lookUpApplyingType.amount;

       

        log.debug(“applyingType…….”, applyingType);

       

        if (applyingType && (applyingType[0].value == “CustCred” || applyingType[0].value == “CashRfnd” || applyingType[0].value == “CustRfnd” || applyingType[0].value == “CardRfnd”)) {

         

            credit.document = lookUpApplyingType.tranid;

            credit.date = lookUpApplyingType.trandate;

            credit.applyAmount = applyAmount

        }

    } else {

        log.debug(“Skipping duplicate applying transaction…”, applying);

    }

    log.debug(“lookUpApplyingType”,lookUpApplyingType);

                    let typeMain = result.getValue({

                         name: “applyingtransaction”, label: “Applying Transaction”

                    });

                    log.debug(“typeMain…”,typeMain);

                    var lookUptypeMainType = search.lookupFields({

                        type: ‘transaction’,

                        id: typeMain,

                        columns: [‘type’, ‘amount’, ‘tranid’, ‘trandate’]

                    });

                    if(typeMain && (lookUptypeMainType.type[0].value == “CustCred” || lookUptypeMainType.type[0].value == “CashRfnd” || lookUptypeMainType.type[0].value == “CustRfnd” || lookUptypeMainType.type[0].value == “CardRfnd”)){

                        credit.document =  lookUptypeMainType.tranid;

            credit.date = lookUptypeMainType.trandate

            credit.applyAmount = lookUptypeMainType.amount

                     

                    }

                    log.debug(“lookUptypeMainType”,lookUptypeMainType)

                    creditorRefundArray.push(credit);

                   

                    return true;

                });

                log.debug(“applyingArray.after.”,applyingArray);

                log.debug(“creditorRefundArray…….”,creditorRefundArray)

                creditorRefundArray = removeDuplicatesAndEmpty(creditorRefundArray);

               

                return creditorRefundArray;

            } catch (e) {

                log.error(“error@creditRefund”, e);

            }

        }

Leave a comment

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