Home  >   FAQs   >  How to write a server script to calculate the outstanding invoice amount?
FAQs in this section

How to write a server script to calculate the outstanding invoice amount?

Table of Contents
Consider that CompanyX provides marketing services to multiple organizations. They regularly get marketing projects from their client companies. To manage marketing invoices, they use CRM.
They have a certain set of fixed clients for whom they do marketing campaigns regularly. For each campaign, they generate an invoice for the client. At any point in time, they want to see for each client what is the outstanding invoice amount.
For this, they create a custom currency field in the Organization to store overdue invoice amounts. Next, they create a workflow to update this amount whenever the Invoice amount is changed or the status is changed.
 
async function main(record, user) {
    //Get organization id from invoice
var orgId = record.account_id ? record.account_id.id : false;
if(orgId) {
    try {
        //Fetch all related invoices for organization using rest api
        var relatedRes = await vtap.macro.ws.api('GET', 'retrieve_related', {
                 id: '3x'+orgId,
                 relatedLabel: 'Invoice',
                 relatedType: 'Invoice'
             });
             if(relatedRes && relatedRes.success) {
                 var overdueAmount = 0;
                 //For each related invoice, sum the balance amount
                 for(var index in relatedRes.result) {
                     var invoice = relatedRes.result[index];
                     var balance = parseFloat(invoice.balance);
                     if(balance && !isNaN(balance)) {
                         overdueAmount = overdueAmount + balance;
                     }
                 }
                 //Round off the amount to 8 decimal digits
                 overdueAmount = Math.round(overdueAmount * 100000000) / 100000000;
             
                 //Update outstanding amount to organization using rest api revise method
                 await vtap.macro.ws.revise({
                     id: '3x'+orgId,
                     cf_outstanding_invoice_amount: overdueAmount
                 });
             }
    } catch(error) {
        
    }
}
}

Explanation
  • From invoice getting organization id.
  • For that organization, getting all related invoices using the rest API method retrieve_related.
  • Summing the balance amount of each invoice.
  • Using the rest API revise method, the overdue amount of all related invoices is updated to the organization's custom currency field.
Was this FAQ helpful?
0  out of  0  found this helpful.
Comments 0
Be the first to comment
© Copyright 2023 Vtiger. All rights reserved.