Function-4: Get the total quantity, taxes and discounts for a record at a glance!

Function-4: Get the total quantity, taxes and discounts for a record at a glance!




Welcome back folks!

Last week, we learnt about auto-update of account information across CRM. This week, let's look at a custom function that makes accounting and report generation easier by automatically calculating the amount of tax, discounts and the quantity of items for a particular record in a quote, invoice, purchase order or sales order.

Business scenario:

I'm sure you agree that meticulous tracking and management is critical for your business to hold up and flourish. You need to keep an inventory of items and products you have or deal with. The other important aspects of the transactions that need keeping a tab on, are taxes and discounts associated with records in a quote, purchase order or sales order. Do you want to manually do that on your own? Of course not. This custom function helps automate just that. It sums up the total amount of tax to be paid and the discount given to the customer, and lists the total quantity of products involved in the deal.

The quotes, sales order, purchase order and invoices of a deal are tracked in your CRM solution. Add this custom function to any or all of the four modules. See the total taxes, discounts, and quantity of products against the records.
Let's assume an example of calculating the taxes and discounts for a record in the Quotes module.



The above record displays the products involved in the deal in the "Product details" section and the "Line Item totals" section is where the total tax, discounts, and total quantity of products are displayed.

Pre-requisite: Create the custom fields, "Total Tax at line item level", "Total discount at line item level" and "Total quantity".

Getting started with the custom function:

  • Go to Setup>Automations>Actions >Custom Functions > Configure Custom Function > Write your own.
  • Provide a name for the Custom function. For example: “Sumup line items field values”.
  • Select the module as Quotes. Add a description(optional).
  • Click “Free flow scripting”.
  • Copy the code given below.
  • Click “Edit arguments”.
  • Enter the name as “quoteId” and select the value as “Quote Id”.
  • Save the changes.

The script:

Code for Version 2.0 API:
 
1) For total tax: 

respMap = zoho.crm.getRecordById("Quotes", input.quoteId.toLong());
productDet = ifnull(respMap.get("Product_Details"),"");
linetaxes = 0.0;
for each eachProd in productDet
{
linetax = (ifnull(eachProd.get("Tax"),"0.0")).toDecimal();
linetaxes = (linetaxes + linetax);
}
paramap = map();
paramap.put("Total_Tax_at_line_item_level", linetaxes);
updateResp = zoho.crm.updateRecord("Quotes", quoteId.toLong(), paramap);
info paramap;
info updateResp;

2) For total discount : 

quoteIdStr = input.quoteId.toString();
respMap = zoho.crm.getRecordById("Quotes", input.quoteId.toLong());
productDet = ifnull(respMap.get("Product_Details"),"");
linediscount = 0.0;
for each eachProd in productDet
{
linedis = (ifnull(eachProd.get("Discount"),"0.0")).toDecimal();
info linedis;
linediscount = (linediscount + linedis);
}
paramap = map();
paramap.put("Total_Discount_at_line_item_level", linediscount);
updateResp = zoho.crm.update("Quotes", quoteId.toLong(), paramap);
info paramap;
info updateResp;

3) For total quantity : 

quoteIdStr = input.quoteId.toString();
quoteMap = zoho.crm.getRecordById("Quotes", input.quoteId.toLong());
productDet = ifnull(quoteMap.get("Product_Details"),"");
value = 0;
for each eachProd in productDet
{
qty = (ifnull(eachProd.get("quantity"),"0")).toLong();
value = value + qty ;
}
params = map();
params.put("Total_Quantity", value);
updateResp = zoho.crm.update("Quotes", quoteId.toLong(), params);
info params;
info updateResp;

Code for Version 1.0 API:

1) For total tax:

quoteIdStr = input.quoteId.toString();
respMap = zoho.crm.getRecordById("Quotes", input.quoteId);
productDet = ifnull(respMap.get("product"),"");
productList = productDet.toJSONList();
linetaxes = 0.0;
for each eachProd in productList
{
eachProdDet = eachProd.toMap();
linetax = (ifnull(eachProdDet.get("Tax"),"0.0")).toDecimal();
linetaxes = (linetaxes + linetax);
}
paramap = map();
paramap.put("Total Tax at line item level", linetaxes);
updateResp = zoho.crm.updateRecord("Quotes", quoteIdStr, paramap);
info paramap;
info updateResp;

2) For total discount :

quoteIdStr = input.quoteId.toString();
respMap = zoho.crm.getRecordById("Quotes", input.quoteId);
productDet = ifnull(respMap.get("product"),"");
productList = productDet.toJSONList();
linediscount = 0.0;
for each eachProd in productList
{
eachProdDet = eachProd.toMap();
linedis = (ifnull(eachProdDet.get("Discount"),"0.0")).toDecimal();
info linedis;
linediscount = (linediscount + linedis);
}
paramap = map();
paramap.put("Total Discount at line-item level", linediscount);
updateResp = zoho.crm.updateRecord("Quotes", quoteIdStr, paramap);
info paramap;
info updateResp;


3) For total quantity :

quoteIdStr = input.quoteId.toString();
quoteMap = zoho.crm.getRecordById("Quotes", input.quoteId);
productDet = ifnull(quoteMap.get("product"),"");
productList = productDet.toJSONList();
value = 0;
for each eachProd in productList
{
eachProdDet = eachProd.toMap();
qty = (ifnull(eachProdDet.get("Quantity"),"0")).toLong();
value = value + qty ;
}
params = map();
params.put("Total Quantity", value);
updateResp = zoho.crm.updateRecord("Quotes", quoteIdStr, params);
info params;
info updateResp;

Note:

  • To add this custom function to the other modules such as SalesOrders, Invoices, or PurchaseOrders, make sure you replace the module name Quote to the desired module name in the snippet above.

Found this useful? Try and let me know how it works! If you have questions, do not hesitate to ask! Share this with your team if you find it useful. See you all next week with another interesting custom function. Ciao!

Update: As you must be aware, API V1.0 will be deprecated and support for version 1.0 API will be available only till Dec 31, 2018. Version 1.0 compatible Functions will continue to work until Dec 31, 2019. You're advised to migrated to API Version 2.0 at the earliest. Check this announcement for more. We've updated the post to include the Version 2.0 compatible Function.

    Access your files securely from anywhere







                            Zoho Developer Community




                                                  • Desk Community Learning Series


                                                  • Digest


                                                  • Functions


                                                  • Meetups


                                                  • Kbase


                                                  • Resources


                                                  • Glossary


                                                  • Desk Marketplace


                                                  • MVP Corner


                                                  • Word of the Day


                                                  • Ask the Experts



                                                            • Sticky Posts

                                                            • Function #46: Auto-Calculate Sales Margin on a Quote

                                                              Welcome back everyone! Last week's function was about displaying the discount amount in words. This week, it's going to be about automatically calculating the sales margin for a particular quote, sales order or an invoice. Business scenario Where there is sales, there's also evaluation and competition between sales reps. A healthy rivalry helps to better motivate your employees to do smart work and close deals faster and more efficiently. But how does a sales rep get evaluated? 90% of the time, it's
                                                            • Zoho CRM Functions 53: Automatically name your Deals during lead conversion.

                                                              Welcome back everyone! Last week's function was about automatically updating the recent Event date in the Accounts module. This week, it's going to be about automatically giving a custom Deal name whenever a lead is converted. Business scenario Deals are the most important records in CRM. After successful prospecting, the sales cycle is followed by deal creation, follow-up, and its subsequent closure. Being a critical function of your sales cycle, it's good to follow certain best practices. One such
                                                            • User Tips: Auto-Create Opportunity/Deal upon Quote Save (PART 1)

                                                              Problem: We use quotes which convert to sales orders but Users / Sales Reps do not create opportunities / deals and go straight to creating a quote. This leads to poor reporting. Implementing this solution improves reporting and makes it easier for users.
                                                            • Custom Function : Automatically send the Quote to the related contact

                                                              Scenario: Automatically send the Quote to the related contact.  We create Quotes for customers regularly and when we want to send the quote to the customer, we have to send it manually. We can automate this, using Custom Functions. Based on a criteria, you can trigger a workflow rule and the custom function associated to the rule and automatically send the quote to customer through an email. Please note that the quote will be sent as an inline email content and not as a PDF attachment. Please follow
                                                            • Function #50: Schedule Calls to records

                                                              Welcome back everyone! Last week's function was about changing ownership of multiple records concurrently. This week, it's going to be about scheduling calls for records in various modules. Business scenario Calls are an integral part of most sales routines.. Sales, Management, Support, all the branches of the business structure would work in cohesion only through calls. You could say they are akin to engine oil, which is required by the engine to make all of it's components function perfectly. CRM


                                                            Manage your brands on social media



                                                                  Zoho TeamInbox Resources



                                                                      Zoho CRM Plus Resources

                                                                        Zoho Books Resources


                                                                          Zoho Subscriptions Resources

                                                                            Zoho Projects Resources


                                                                              Zoho Sprints Resources


                                                                                Qntrl Resources


                                                                                  Zoho Creator Resources



                                                                                      Zoho CRM Resources

                                                                                      • CRM Community Learning Series

                                                                                        CRM Community Learning Series


                                                                                      • Kaizen

                                                                                        Kaizen

                                                                                      • Functions

                                                                                        Functions

                                                                                      • Meetups

                                                                                        Meetups

                                                                                      • Kbase

                                                                                        Kbase

                                                                                      • Resources

                                                                                        Resources

                                                                                      • Digest

                                                                                        Digest

                                                                                      • CRM Marketplace

                                                                                        CRM Marketplace

                                                                                      • MVP Corner

                                                                                        MVP Corner







                                                                                          Design. Discuss. Deliver.

                                                                                          Create visually engaging stories with Zoho Show.

                                                                                          Get Started Now


                                                                                            Zoho Show Resources

                                                                                              Zoho Writer

                                                                                              Get Started. Write Away!

                                                                                              Writer is a powerful online word processor, designed for collaborative work.

                                                                                                Zoho CRM コンテンツ




                                                                                                  Nederlandse Hulpbronnen


                                                                                                      ご検討中の方







                                                                                                              • Recent Topics

                                                                                                              • Is it possible to adjust the web browser tab title (when a ZoHo Desk ticket is opened)

                                                                                                                Hi All, When I open a ZoHo Desk ticket in a web browser, the tab title (text that appears at the top of the browser tab) uses the logic: *company icon picture* (xxxx) #ticket number - company name See below (highlighted in red) for reference. Company
                                                                                                              • Add Attachment Support to Zoho Flow Mailhook / Email Trigger Module

                                                                                                                Dear Zoho Support Team, We hope you are well. We would like to kindly request a feature enhancement for the Mailhook module in Zoho Flow. Currently, the email trigger in Zoho Flow provides access to the message body, subject, from address, and to address,
                                                                                                              • Collections Management: #7 Common Mistakes during Payment Collection

                                                                                                                Payment collection may appear straightforward in most cases. Still, as your customer base expands and transaction volume increases, it becomes clear that even small inefficiencies can lead to delayed payments, increased support load, or even revenue loss.
                                                                                                              • Recruit paid support?

                                                                                                                Hi all, Could anyone who has paid support package advise if it provides value for money with regards to support response times? Exploring the idea as unfortunately when we have faced issues with Recruit it has been a 7+ day timescale from reporting to
                                                                                                              • Unusual activity detected from this IP. Please try again after some time

                                                                                                                When i try to create new addresses on my account i am getting this error, it has been 24 hours now and i am still getting this error can anyone help
                                                                                                              • Read webpage - MSXML2.ServerXMLHTTP

                                                                                                                I have the following VBA script, put together from various sources (mainly zoho forum/help/support, so it once worked, I guess): private Sub GetListOfSheets() Dim url As String Dim xmlhttp As Object Dim parameters As String Dim html As String range("B1").value
                                                                                                              • Sortie de Zoho TABLE ??

                                                                                                                Bonjour, Depuis bientôt 2 ans l'application zoho table est sortie en dehors de l'UE ? Depuis un an elle est annoncée en Europe Mais en vrai, c'est pour quand exactement ??
                                                                                                              • Rename Record Summary PDF in SendMail task

                                                                                                                So I've been tasked with renaming a record summary PDF to be sent as part of a sendmail task. Normally I would offer the manual solution, a user exports the PDF and uploads it to a file upload field, however this is not acceptable to the client in this
                                                                                                              • Limitation with Dynamic Email Attachment Capture

                                                                                                                I've discovered a flaw in how Zoho Creator handles email attachments when using the Email-to-Form feature, and I'm hoping the Zoho team can address this in a future update. The Issue According to the official documentation, capturing email attachments
                                                                                                              • Recruit API search

                                                                                                                Hi all, Attempting to call the search api endpoint from Postman using the word element as mentioned in api docs Search Records - APIs | Online Help - Zoho Recruit When making the call to /v2/Candidates/search?word=Saudi receive response of { "code": "MANDATORY_NOT_FOUND",
                                                                                                              • Text/SMS With Zoho Desk

                                                                                                                Hi Guys- Considering using SMS to get faster responses from customers that we are helping.  Have a bunch of questions; 1) Which provider is better ClickaTell or Screen Magic.  Screen Magic seems easier to setup, but appears to be 2x as expensive for United States.  I cannot find the sender id for Clickatell to even complete the configuration. 2) Can customer's reply to text messages?  If so are responses linked back to the zoho ticket?  If not, how are you handling this, a simple "DO NOT REPLY" as
                                                                                                              • Custom Field in Zoho Projects pulling into Analytics

                                                                                                                We have a client that we have built our their new business process using Zoho Projects, and we have build a lot of custom fields with their their Projects where they are capturing specific data points that we want to be able to track and pull data, as
                                                                                                              • Marketer's Space - Holiday season email marketing tips you should know

                                                                                                                Hello Marketers! Welcome back to another post in Marketer's Space! 'Tis the season—that time of the year everyone eagerly anticipates. While most look forward to relaxing, marketers will be super-busy from late November to early January. Mistakes can
                                                                                                              • Zia Competitor Alerts made easy with Zia's suggestions

                                                                                                                Hi everyone, In addition to the existing manually added competitors, Zia will now find your competitors for you - instantly. Earlier, you had to identify competitors through research manually, support tickets, or tradeshows—a time-consuming process that
                                                                                                              • Add Custom Field Inside Parts Section

                                                                                                                How to Add Custom Field Inside Parts Section in Workorder like Category and Sub- Category
                                                                                                              • Zoho CRM Community Digest October 2025 | Part 2

                                                                                                                Hello Everyone! From new mobile capabilities and smarter integrations to real-world workflow fixes and developer insights, all the highlights from the second half of October is covered right here. Let’s dive in. Product Updates: Zoho CRM Mobile Updates:
                                                                                                              • Understanding Zoho Contracts

                                                                                                                Effective contract management relies on systems that are structured, organized, and reliable. Every feature, workflow, rule, and restriction in Zoho Contracts are designed the way they are to ensure consistency, compliance, and control across every stage
                                                                                                              • Tip of the Week #76– Automate your inbox during vacation in Zoho TeamInbox

                                                                                                                When you're on vacation or away from your desk, the last thing you want is for important emails to be missed or left unanswered. The good news is, you can easily set up rules in Zoho TeamInbox to assign incoming messages automatically to a teammate who's
                                                                                                              • Domain restriction for User Management actions in Zoho One

                                                                                                                Greetings, Zoho One Admins! To strengthen account security further and safeguard user management settings, we are imposing domain-based restrictions for user account-focused admin actions in Zoho One. In addition to password reset of user, organization
                                                                                                              • Zoho Mail iOS app update: Signature

                                                                                                                Hello everyone! In the latest version(3.1.7) of the Zoho Mail app update, we have brought in support to create, edit and remove signature within the app. You can create signature from the compose screen as well as from within the Settings module(inside
                                                                                                              • Copy paste from word document deletes random spaces

                                                                                                                Hello Dear Zoho Team, When copying from a word document into Notebook, often I face a problem of the program deleting random spaces between words, the document become terribly faulty, eventhough it is perfect in its original source document (and without
                                                                                                              • Desktop app doesn't support notecards created on Android

                                                                                                                Hi, Does anybody have same problem? Some of last notecards created on Android app (v. 6.6) doesn't show in desktop app (v. 3.5.5). I see these note cards but whith they appear with exclamation mark in yellow triangle (see screenshot) and when I try to
                                                                                                              • Approval Button in Subform

                                                                                                                Hi Team, I’m working on a subform-based requirement where users will submit requests, and these requests must go through approval by multiple team managers. Each line item in the subform needs to be individually approved or declined based on the user's
                                                                                                              • Reporting Limitation on Lead–Product Relation in Zoho CRM

                                                                                                                I noticed that Zoho CRM has a default Products related list under Leads. However, when I try to create a report for Lead–Product association, I’m facing some limitations. To fix this, I’m considering adding a multi-lookup field along with a custom related
                                                                                                              • Setting checkbox value on template in Sign from Creator

                                                                                                                Good day, Please help me understand how do I set a tick from a checkbox in Creator into a checkbox on a Sign template. Below is the only values on the Sign template and the code from Creator, "field_boolean_data": {}, "field_date_data": {}, "field_radio_data":
                                                                                                              • Zoho Projects - Unread Comment Icon

                                                                                                                Hi Projects Team, It would be great if there was a notification I con on the comments icon so it's easy to see which tasks have new comments. Something like a red circle with a number of unread comments would be great. Thanks for considering my feed
                                                                                                              • Zoho Projects - Update Feed via API

                                                                                                                Hi Projects Team, Please consider adding an API to allow update and retrieval of messages to the Feed. Thank you
                                                                                                              • Automated log-out/session end

                                                                                                                I'm concerned about security of our data. Is it possible to set an automatic time-out for user sessions on Zoho CRM, after a certain period of inactivity or when the session reaches a certain duration (12 hours perhaps)? 
                                                                                                              • Subform auto populate values

                                                                                                                Hi Team, I’m trying to retrieve values from Zoho People using API functions and dynamically populate them into a subform. For example, I’ve created a form with several fields that users will fill out. Based on their input, I need to fetch records from
                                                                                                              • What is New in CRM Functions?

                                                                                                                What is New in CRM Functions? Hello everyone! We're delighted to share that Functions in Zoho CRM have had a few upgrades that would happen in phases. Phase 1 An all new built-in editor for better user experience and ease of use. ETA: In a couple of days.
                                                                                                              • Gantt Chart - Zoho Analytics

                                                                                                                Are there any plans to add Gantt Charts capabilities to Zoho Analytics?
                                                                                                              • WhatsApp Calling Integration via Zoho Desk

                                                                                                                Dear Zoho Desk Team, I would like to request a feature that allows users to call WhatsApp numbers directly via Zoho Desk. This integration would enable sending and receiving calls to and from WhatsApp numbers over the internet, without the need for traditional
                                                                                                              • Request for Auto PO - Min–Max based Automated Purchase Feature

                                                                                                                Dear Zoho POS Team, I’m writing to request a feature enhancement that would significantly streamline inventory management for businesses using Zoho POS — particularly supermarkets, FMCG retail, and multi-store operations like ours. Feature Requested:
                                                                                                              • Identify long running sync jobs/tables

                                                                                                                My sync process causes strain on my production database and I'd love some tools/alerts to help me identify which tables are taking the longest. The current screen only shows 3 tables at a time and truncates the last fetch time so that it is very cumbersome
                                                                                                              • Temporarily rate limited due to IP reputation.

                                                                                                                We have suddenly started receiving the following Mail Delivery Status Notification: Diagnostic-Code: 4.7.650 The mail server [136.143.184.12] has been temporarily rate limited due to IP reputation. For e-mail delivery information, see https://aka.ms/postmaster
                                                                                                              • Zoho Analytics Regex Support

                                                                                                                When can we expect full regex support in Zoho Analytics SQL such as REGEXP_REPLACE? Sometimes I need to clean the data and using regex functions is the easiest way to achieve this.
                                                                                                              • Automatically CC an address using Zoho CRM Email Templates

                                                                                                                Hi all - have searched but can't see a definitive answer. We have built multiple email templates in CRM. Every time we send this we want it to CC a particular address (the same address for every email sent) so that it populates the reply back into our
                                                                                                              • Solution to Import PST File into Office 365.

                                                                                                                MailsDaddy OST to Office 365 Migration Tool is an outstanding solution to recover OST files and migrate them into Office 365 without any hassle. Using this software users can multiple OST files into Office 365 with complete data security. It offers users
                                                                                                              • Series Label in the Legend

                                                                                                                My legend reads 'Series 1' and 'Series 2'. From everything I read online, Zoho is supposed to change the data names if it's formatted correctly. I have the proper labels on the top of the columns and the right range selected. I assume it's something in
                                                                                                              • Associate emails from both primary and secondary contacts to deal

                                                                                                                We need to associate emails from multiple contacts to a deal. Please advise how this can be achieved. At present, only emails from primary contacts can be associated. Thanks
                                                                                                              • Next Page