Auto-apply Credit Memos to Invoices

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 */
/*************************************************************************************
* Auto-apply Credit Memos to Invoices
* Description : UserEvent Script to auto-apply Credit Memos to Invoices
**************************************************************************************/
define(['N/record', 'N/search'],
    /**
 * @param{format} format
 * @param{record} record
 * @param{search} search
 * @param{commonLibrary} commonLibrary
 */
    (record, search) => {
        /**
         * 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 || scriptContext.type === scriptContext.UserEventType.COPY){
                    let invRec = scriptContext.newRecord;
                    let invRecId = invRec.id;
                    let invoiceBatchNo = invRec.getValue({
                        fieldId: 'custbody_ota_invoicebatchcustomer'
                    });
                    log.debug("invoiceBatchNo",invoiceBatchNo);
                    if(invoiceBatchNo){
                        let invBatchCustomRec = search.lookupFields({
                            type: 'customrecord_grw_005_inv_batch_mapping',
                            id: invoiceBatchNo,
                            columns: ['custrecord_grw_015_auto_apply_cm_to_inv']
                        });
                        let invBatchApplyCredit = invBatchCustomRec.custrecord_grw_015_auto_apply_cm_to_inv;
                        log.debug("invBatchApplyCredit",invBatchApplyCredit);
    
                        if(invBatchApplyCredit == true){
                            let invTotalAmount = invRec.getValue({
                                fieldId: 'total'
                            });
                            let customerPaymentRec = record.transform({
                                fromType: record.Type.INVOICE,
                                fromId: invRecId,
                                toType: record.Type.CUSTOMER_PAYMENT,
                                isDynamic: false
                            });
        
                            applyCreditMemoToInvoice(customerPaymentRec,invTotalAmount);
                        }

                    }
                    
                    

                }
               
            } catch (e) {
                log.error("error@afterSubmit", e);
            }
        }

        /**
         * @description auto apply credit memo to invoice
         * @param {*} customerPaymentRec 
         * @param {*} invTotalAmount 
         */
        function applyCreditMemoToInvoice(customerPaymentRec,invTotalAmount){
            try{
                
                let applyLineCount = customerPaymentRec.getLineCount({
                    sublistId: 'apply'
          
                });
                log.debug("applyLineCount", applyLineCount)
                let creditLineCount = customerPaymentRec.getLineCount({
                    sublistId: 'credit'
          
                });
                log.debug("creditLineCount", creditLineCount);

                let creditAppliedArray = [];
                let totalCreditApplied = 0;
                if(creditLineCount > 0){
                    for (let line = 0; line < creditLineCount; line++){
                        let creditInternalId = customerPaymentRec.getSublistValue({
                            sublistId: 'credit',
                            fieldId: 'internalid',
                            line: line
                        });
                        let creditLineAmount = customerPaymentRec.getSublistValue({
                            sublistId: 'credit',
                            fieldId: 'due',
                            line: line
                        });
                        totalCreditApplied += creditLineAmount;
                        creditAppliedArray.push({
                            line: line,
                            dueFieldValue: creditInternalId
                        });

                    }

                }
                log.debug("creditAppliedArray", creditAppliedArray);
                creditAppliedArray.sort(function (a, b) {
                    return a.dueFieldValue - b.dueFieldValue;
                });
                log.debug("creditAppliedArray-sorted", creditAppliedArray);

                let creditAppliedAmount =0;
                if(creditLineCount >0){
                    
                    for (let i = 0; i < creditLineCount; i++){
                        let originalLine = creditAppliedArray[i].line;
                        let creditApplied = customerPaymentRec.getSublistValue({
                            sublistId: 'credit',
                            fieldId: 'apply',
                            line: originalLine
                        });
                        creditAppliedAmount += customerPaymentRec.getSublistValue({
                            sublistId: 'credit',
                            fieldId: 'due',
                            line: originalLine
                        });
                        log.debug("creditAppliedAmount", creditAppliedAmount);

                        let isCreditApplied = customerPaymentRec.setSublistValue({
                            sublistId: 'credit',
                            fieldId: 'apply',
                            line: originalLine,
                            value: true
                        });

                        if(creditAppliedAmount <invTotalAmount){

                        }
                        else{
                            break;
                        }

                    }

                }
                if(applyLineCount >0){
                    let lineNumber = customerPaymentRec.findSublistLineWithValue({
                        sublistId: 'apply',
                        fieldId: 'apply',
                        value: true
                    });
                    //for (let j = 0; j < applyLineCount; j++) {
                        let isApplied = customerPaymentRec.getSublistValue({
                          sublistId: 'apply',
                          fieldId: 'apply',
                          line: lineNumber
                        });
                        log.debug("isApplied", isApplied);
                        if(isApplied == true){

                            log.debug("creditAppliedAmount", creditAppliedAmount);
                            if(creditAppliedAmount){
                                customerPaymentRec.setSublistValue({
                                    sublistId: 'apply',
                                    fieldId: 'apply',
                                    line: lineNumber,
                                    value: false
                                });
                                let updatedInvLineAmount = customerPaymentRec.setSublistValue({
                                    sublistId: 'apply',
                                    fieldId: 'amount',
                                    line: lineNumber,
                                    value: creditAppliedAmount
                                });
                                
                                log.debug("updatedInvLineAmount", updatedInvLineAmount);
                              

                                customerPaymentRec.setSublistValue({
                                    sublistId: 'apply',
                                    fieldId: 'apply',
                                    line: lineNumber,
                                    value: true
                                });

                            }

                        }
                    //}
                    
                }
                
                if(creditAppliedAmount){
                    customerPaymentRec.save();
                }
                

            }
            catch (e) {
                
                applyCreditMemoToInvoice(customerPaymentRec,invTotalAmount);
                log.error("error@applyCreditMemoToInvoice", e);
                
            }
        }
        return {afterSubmit}
    });

Leave a comment

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