Automatically pay the invoice using the credit memo, and categorize the remaining invoice amount as ‘Amount Due’.

define([‘N/record’, ‘N/search’, ‘N/email’],

    /**

 * @param{record} record

 * @param{search} search

 */

    (record, search, email) => {

        /**

         * Defines the function to search for a Credit Memo associated with a given RMA ID.

         * @param {*} rmaId

         * @returns {Array} creditMemoId

         * @since 2015.2

         */

        function searchCreditMemo(rmaId) { //Function to search for a Credit Memo associated with a given RMA ID.

            try {

                let creditmemoSearchObj = search.create({

                    type: “creditmemo”,

                    filters:

                        [

                            [“type”, “anyof”, “CustCred”],

                            “AND”,

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

                            “AND”,

                            [“createdfrom”, “anyof”, rmaId]

                        ],

                    columns:

                        [

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

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

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

                        ]

                });

                let searchCount = creditmemoSearchObj.runPaged().count;

                if (searchCount > 0) {

                    let amount = 0;

                    let applyAmount = 0;

                    let mainObj = {}

                    let creditMemoId = [];

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

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

                       

                        creditMemoId.push(result.getValue({

                            name: “tranid”, label: “Document Number”,

                           

                        }));

                        applyAmount = parseFloat(applyAmount) + parseFloat(result.getValue({ name: “amountremaining”, label: “Amount Remaining” }))

                       

                        return true;

                    });

                    mainObj[“document”] = creditMemoId;

                    mainObj[“amount”] = (amount * 1)

                    mainObj[“applyAmount”] = applyAmount

                    return mainObj;

                }

                else {

                    return {};

                }

            }

            catch (err) {

                log.error(“error@creditMemoSearch”, err);

                return [];

            }

        }

        /**

         * Defines the function to search for a Credit Memo and RMA associated with the sales order.

         * @param {*} salesOrderId

         * @returns cmId

         * @since 2015.2

         */

        function searchCm(filterArray) {

            try {

                log.debug(‘filterArray’,filterArray)

                let salesorderSearchObj = search.create({

                    type: “salesorder”,

                    filters:

                        filterArray,

                    columns:

                        [

                            search.createColumn({

                                name: “tranid”,

                                join: “CUSTBODY_JJ_RELATE_CRDT_MEMO_AHAP1831”,

                                summary: “GROUP”,

                                label: “Document Number”

                            }),

                            search.createColumn({

                                name: “internalid”,

                                summary: “GROUP”,

                                label: “Internal ID”

                            }),

                            search.createColumn({

                                name: “internalid”,

                                join: “CUSTBODY29”,

                                summary: “GROUP”,

                                label: “RMA Internal ID”

                             }),

                            search.createColumn({

                                name: “total”,

                                join: “CUSTBODY_JJ_RELATE_CRDT_MEMO_AHAP1831”,

                                summary: “GROUP”,

                                label: “Amount total”

                            }),

                            search.createColumn({

                                name: “amountremaining”,

                                join: “CUSTBODY_JJ_RELATE_CRDT_MEMO_AHAP1831”,

                                summary: “GROUP”,

                                label: “Amount Remaining”

                             })

                        ]

                });

                let searchResultCount = salesorderSearchObj.runPaged().count;

                let cmId = [];

                if (searchResultCount > 0) {

                    let applyAmount = 0

                    let totalAmount = 0

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

                        let obj = {};

                        obj.totalAmount = (parseFloat(totalAmount) + parseFloat(result.getValue({ name: “total”, join: “CUSTBODY_JJ_RELATE_CRDT_MEMO_AHAP1831”, summary: “GROUP”, label: “Amount total” }))) * 1

                        obj.credit = result.getValue({ name: “tranid”, join: “CUSTBODY_JJ_RELATE_CRDT_MEMO_AHAP1831”, summary: “GROUP”, label: “Document Number” });

                        obj.rma = result.getValue({ name: “internalid”, join: “CUSTBODY29”, summary: “GROUP”, label: “RMA Internal ID” });

                        obj.applyAmount = (parseFloat(applyAmount) + parseFloat(result.getValue({name: “amountremaining”, join: “CUSTBODY_JJ_RELATE_CRDT_MEMO_AHAP1831”, summary: “GROUP”, label: “Amount Remaining”})))

                        cmId.push(obj);

                        return true;

                    });

                    return cmId;

                }

                else {

                    return [];

                }

            }

            catch (err) {

                log.error(“error@searchCM”, err);

                return [];

            }

        }

        /**

        * Defines the function to pay the invoice using credit memo(creditMemoId).

        * @param {*} currentRecord

        * @param {*} salesLocation

        * @param {*} location

        * @param {*} creditMemoId

        * @since 2015.2

        */

        function createCustomerPayment(currentRecord, salesLocation, location, creditMemoId, amount, invAmount) { //Function to pay the invoice using credit memo.

            try {

                let paymentDate = new Date();

                let day = paymentDate.getDate().toString().padStart(2, ‘0’); // Get day and pad with leading zero if needed

                let year = paymentDate.getFullYear().toString(); // Get full year

                let formattedDate = day + year;

                let paymentRecord = record.transform({

                    fromType: record.Type.INVOICE,

                    fromId: currentRecord.id,

                    toType: record.Type.CUSTOMER_PAYMENT,

                    isDynamic: false

                });

                paymentRecord.setValue({

                    fieldId: ‘paymentmethod’,

                    value: 24

                });

                paymentRecord.setValue({

                    fieldId: ‘authcode’,

                    value: formattedDate

                });

                paymentRecord.setValue({

                    fieldId: ‘custbody_ccard_present’,

                    value: 1

                });

                paymentRecord.setValue({

                    fieldId: ‘custbody_aha_sales_location’,

                    value: salesLocation

                });

                paymentRecord.setValue({

                    fieldId: ‘location’,

                    value: location

                });

                let creditMemoLineCount = paymentRecord.getLineCount({

                    sublistId: ‘credit’

                });

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

                    let creditMemo = paymentRecord.getSublistValue({

                        sublistId: ‘credit’,

                        fieldId: ‘refnum’,

                        line: i

                    });

                    if (creditMemoId.includes(creditMemo)) {

                        paymentRecord.setSublistValue({

                            sublistId: ‘credit’,

                            fieldId: ‘apply’,

                            value: true,

                            line: i

                        });

                    }

                }

                if (invAmount > amount) {

                    let invLineCount = paymentRecord.getLineCount({

                        sublistId: ‘apply’

                    });

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

                        let apply = paymentRecord.getSublistValue({

                            sublistId: ‘apply’,

                            fieldId: ‘apply’,

                            line: i

                        });

                        if (apply == true || apply == ‘true’ || apply == ‘T’) {

                            paymentRecord.setSublistValue({

                                sublistId: ‘apply’,

                                fieldId: ‘amount’,

                                value: amount,

                                line: i

                            });

                        }

                    }

                }

                paymentRecord.save({

                    ignoreMandatoryFields: true,

                    enableSourcing: true

                });

            }

            catch (err) {

                log.error(“Error in customerPayment”, err);

             

            }

        }

   

        /**

         * Defines the function definition that is executed after record is submitted.

         * @param {Object} scriptContext

         * @param {Record} scriptContext.newRecord – New record

         * @param {Record} scriptContext.oldRecord – Old record

         * @param {string} scriptContext.type – Trigger type; use values from the context.UserEventType enum

         * @since 2015.2

         */

        const afterSubmit = (scriptContext) => {

            try {

                if (scriptContext.type === scriptContext.UserEventType.CREATE) {

                    let currentRecord = scriptContext.newRecord;

                    let salesOrderId = currentRecord.getValue({

                        fieldId: ‘createdfrom’

                    });

                    let salesLocation = currentRecord.getValue({

                        fieldId: ‘custbody_aha_sales_location’

                    });

                    let location = currentRecord.getValue({

                        fieldId: ‘location’

                    });

                    let customForm = currentRecord.getValue({

                        fieldId: ‘customform’

                    })

                    let invAmount = currentRecord.getValue({

                        fieldId: ‘total’

                    })

                    //script to retrieve the connected RMA and cm details and using the cm to pay the invoice

                    if (customForm == 199) {

                        if (salesOrderId) {

                            let fArray = [

                                [“type”, “anyof”, “SalesOrd”],

                                “AND”,

                                [“internalid”, “anyof”, salesOrderId],

                                “AND”,

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

                            ]

                            let cmId = searchCm(fArray);

                            if (cmId.length > 0) {

                                let rmaId = cmId[0].rma;

                                if (rmaId) {

                                    let creditMemoId = searchCreditMemo(rmaId);

                                    if (creditMemoId[“document”].length > 0) {

                                        createCustomerPayment(currentRecord, salesLocation, location, creditMemoId[“document”],creditMemoId[“applyAmount”], invAmount)

                                    }

                                }

                            }

                        }

                    }

                    //script to retrieve the connected cm details and using the cm to pay the invoice

                    else if (customForm == 244) {

                        if (salesOrderId) {

                            let filterArray = [

                                [“type”, “anyof”, “SalesOrd”],

                                “AND”,

                                [“internalid”, “anyof”, salesOrderId],

                                “AND”,

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

                            ]

                            let cmId = searchCm(filterArray);

                            if (cmId.length > 0) {

                                let creditId = cmId[0].credit;

                                let cmAmount = cmId[0].applyAmount

                                if (creditId) {

                                    createCustomerPayment(currentRecord, salesLocation, location, creditId, cmAmount, invAmount)

                                }

                            }

                        }

                    }

                }

                }

            // }

            catch (err) {

                log.error(“error detected”, err);

            }

        }

        return { afterSubmit }

    });

Leave a comment

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