Home  >   VTAP Platform   >  Server Scripts Example - Calculate Organization Outstanding Invoice Amount

Server Scripts Example - Calculate Organization Outstanding Invoice Amount

This article gives you an example of how you can calculate Organization outstanding invoice amount using Service Scripts.
A
Abdul Sameer
19 Apr, 2024 - Updated 8 months ago
Table of Contents

Organization Outstanding Invoice Amoun

Consider 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.

To achieve this, you must 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 article helpful?
0  out of  0  found this helpful.
Comments 0
Be the first to comment
© Copyright 2023 Vtiger. All rights reserved.