Auto-applying Credit memo when an invoice is created.

User event script with afterSubmit entry point is used.

if(scriptContext.type=='create') {
   let currentRec = scriptContext.newRecord;
 
   let createdFrom = currentRec.getValue({
      fieldId: 'createdfrom'              // "created from" field in invoice.
   });        


   let cmRecord = record.load({
      type: record.Type.SALES_ORDER,
      id: createdFrom,
      isDynamic: false
   })
   let related_cm = cmRecord.getValue({
      fieldId: 'custbodyjj_credit_memo'   //"Related credit memo" field in sales order
   });
   
   if (checkForParameter(related_cm)) {
      let paymentRecord = record.transform({
         fromType: record.Type.INVOICE,
         fromId: currentRec.id,
         toType: record.Type.CUSTOMER_PAYMENT,
         isDynamic: false
      });
      paymentRecord.setValue({
         fieldId: 'paymentmethod',       //setting a payment method
         value: 23
      });
      paymentRecord.setValue({
         fieldId: 'authcode',            //setting auth code
         value: '06201G'
      });
      let credMemoLineCount = paymentRecord.getLineCount({
         sublistId: 'credit'
      });

      for (let i = 0; i < credMemoLineCount; i++) {
         let doc = paymentRecord.getSublistValue({
            sublistId: 'credit',
            fieldId: 'doc',
            line: i
         });
         
         if (doc == related_cm) {
            paymentRecord.setSublistValue({
               sublistId: 'credit',
               fieldId: 'apply',
               value: true,
               line: i
           })
         }
      }
      paymentRecord.save({
         ignoreMandatoryFields: true,
         enableSourcing: true
      })
    }
 }		

Leave a comment

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