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

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 by calculating the sales margin of a deal. Sales Margins are calculated and displayed either in the Quotes, Sales Orders or the Invoices. Basically anything that gives a summary of the deal.

Sales Margin = [(Unit Price x Quantity) - Discount]

This sales margin also be used in Reports to gauge the company's profit for the particular period of time. That's like hitting multiple birds with a single stone and this method of evaluation and report generation has been the norm for several companies for quite a while now. Alternatively, you can set up a 'dashboard' in your CRM to get live updates of the sales margin.

Recently, one of our customer's put forth the request to facilitate this feature in our CRM. Hence, this week's function is about calculating the sales margin and displaying them in either the sales order, quote or the invoice module, in dashboards and reports.

One more thing that you can do with the sales margin is to use workflow rules to trigger whenever the discount amount is below or above a particular value. In that case, set up a notification to be sent to the Admin/CEO or any one for that matter. Since "Margin" is useful in a lot of ways, make the most of it.

Pre-requisites

  • Create a custom field named "Margin" or "Sales Margin" in the required module.

Getting started with the function

  1. Go to Setup > Automation > Actions > Functions > Configure Function > Write your own.
  2. Provide a name for the function. For example: "Create Invoice". Add a description (optional).
  3. Copy the code given below.
  4. Click “Edit arguments”.
  5. Enter the name as “quotId” and select the value as “Quote Id”.
  6. Click Save&Execute Script to check the code.
  7. Save the function.

The Code

-----------------------------------------------------------------------------------------------------------------------

quoteDetails = zoho.crm.getRecordById("Quotes",Id.toLong());
//info quoteDetails;
productDet = ifnull(quoteDetails.get("Product_Details"),"");
totalmargin = 0.0;
for each eachProd in productDet
{
productname = eachProd.get("product").get("name");
id = eachProd.get("product").get("id");
disc = ifnull(eachProd.get("Discount"),"0.0").toDecimal();
quantity = ifnull(eachProd.get("quantity"),"0.0").toLong();
productdetails = zoho.crm.getRecordById("Products",id);
costprice = ifnull(productdetails.get("Unit_Price"),"0.0").toDecimal();
costpricequantity = (costprice * quantity) - disc;
totalmargin = totalmargin + costpricequantity;
}
params = Map();
params.put("Margin",totalmargin);
update = zoho.crm.update("Quotes",Id.toLong(),params);
info params;
info update;

-----------------------------------------------------------------------------------------------------------------------

Note

  • The code given above works only for V2 version of Zoho APIs. Please note that the code WILL NOT work for Version 1.0 APIs.
  • You can tweak the code a bit and use it for the Sales Order and the Invoice module as well.

Found this useful? Try it out and let me know how it works! If you have questions, do not hesitate to ask! Do check out other functions shared in this series here.

See you all next week with another interesting function. Ciao!

    • 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
      • Recent Topics

      • Data Subject Requests in Zoho Mail: Retrieve and export email data for legal and compliance needs

        Organizations are often required to retrieve specific email communication data in response to legal investigations or compliance audits. The Data Subject Requests (DSR) feature in the Zoho Mail Admin Console allows administrators to search for all email
      • Introducing live chat for Zoho CommunitySpaces

        Hello everyone, We’re happy to announce that your community members now have a direct line to you. Zoho CommunitySpaces now has a live chat widget, powered by Zoho SalesIQ, so a member can open a chat from your community and get a quick one-to-one answer
      • Moving software

        I need someone to customize zoho for my moving business I need to do the following . 1. Quote comes in from ezemove website or we enter customer details into the system 2. Email quote to customer based on hourly rate 3. Customer accepts quote deposit is taken 4. We convert the quote into a confirmation email and add job to the diary and assign resources to the job 5. Job gets completed and we enter invoice amount into the system and email the invoice Budget : neg | Duration : 1 month To leave a private
      • How To Create a Report with Subforms from Two Modules

        I want to create a report based on data in subforms over 2 separate modules. Can this be done? I tried to do it in Analytics, but one is a date field that needs to be grouped by month, and it doesn't look like Analytics can do this.
      • Introducing Zoho Commerce 2.0 — It's more than just selling!

        Hello! We are proud to launch Zoho Commerce 2.0, a reimagination of how online businesses look, feel, and function. This launch is both timely and symbolic, as we reaffirm our commitment to empowering small and medium enterprises with powerful, yet simple-to-use
      • Domain sparkylab.co.kr still linked to an old Zoho account after ownership verification - release pending 2+ days

        Hello Zoho team, I own the domain sparkylab.co.kr (registered and managed through Gabia, a Korean registrar) and I am trying to add it to my own Zoho organization (SparkyLab) on the Forever Free plan. When I add the domain at mailadmin.zoho.com/hosting?plan=free,
      • Vendor payment unexpectedly routed through Prepaid Expenses instead of Accounts Payable

        Hello, We are investigating an unexpected accounting behavior in Zoho Books. We created vendor bills and vendor payments for two suppliers using what appears to be the same workflow, but the journal entries are different. Vendor 1 – UZ Store (works correctly)
      • What's New in Zoho Billing | September 2026

        September brings new capabilities to Zoho Billing across subscriptions, payments, reports, and the product catalog. From managing subscriptions through the Play Store and App Store to setting usage limits for Hosted Payment Page links and configuring
      • Columns in Reports Showing Count instead of Amounts

        I have a table in a modular where we can add our bill claims. I want to show these in the attached table. The dates are right, but they are grouped by Row Count. I want the amounts showing where the row count numbers are. Anyone know how to do this? I
      • Widget Height were destroyed

        All widget heights in the Details Canvas view are broken. Moderation Update: This issue with widget heights in Client Script popups and flyouts has been resolved. Widgets should now display at their expected heights.
      • Zoho Mail iOS app updates - Shared Mailboxes, Calendly Integration and other enhancements

        Hello everyone! We're excited to announce the features and enhancements available for the Zoho Mail iOS app. Shared Mailboxes and Calendly integration are now available in the Zoho Mail iOS app, along with a few other enhancements. Let's dive into the
      • Zoho Extensions 101: Building extensions for Zoho People

        Hello developers! Welcome to our new video series on building extensions for Zoho People! If you're new to extension development or looking for guidance on building extensions for Zoho People, you're in the right place. We've curated a series of videos
      • Tags on individual ticket comments and replies, with color coding and a filter

        In Zoho Desk you can tag a ticket, but you can’t tag the individual comments and replies inside it. For teams with long, structured ticket threads, that’s a big gap. The problem Our tickets can easily reach 50+ comments and replies. Many of them are specific,
      • Merge Tickets Directly from Contact Page in Zoho Desk

        Dear Zoho Desk Support Team, We are writing to request a new feature that would allow users to easily merge tickets directly from the contact page in Zoho Desk. Currently, the only option to merge tickets is from the Tickets list view page, which can
      • GrassHopper VOIP Integration

        Does Zoho Plan to integrate with Grasshopper to allow the Telephony hookup in Zoho Desk?  If not, Can this be passed along for consideration 
      • How Do I Refund a Customer Directly to Their Credit Card?

        Hi, I use books to auto-charge my customers credit card. But when I create a credit note there doesn't seem to be a way to directly refund the amount back to their credit card. Is the only way to refund a credit note by doing it "offline" - or manually-
      • Enhancement Request – Allow cashiers to collect payments and partial payments for outstanding credit invoices directly from Zoho POS Billing App

        We are testing Zoho POS for a retail business with multiple physical stores and have identified an important limitation in the cashier workflow. When a sale is completed using Credit Sale, Zoho POS correctly creates an unpaid invoice and the outstanding
      • How Can I Collect Payments for Credit Sales Directly from Zoho POS Billing App?

        We are currently testing Zoho POS for a retail business and have encountered an issue with collecting payments on outstanding invoices from customers who purchase on credit. When we process a Credit Sale, Zoho POS correctly creates an Unpaid Invoice.
      • Zoho POS Mobile Sales Price Conflicts & Pricing Discrepancies

        We are seeing recurring Zoho POS Mobile conflicts tied to the Sales Price field, even though drivers are not manually changing item pricing. We have also noticed small price differences between POS transactions and Books, sometimes only a few cents. Devices
      • Creator -Dynamic addition of Customer Portal User Licenses

        Hi, We have a Creator App for B2C about to get released. We are experiencing the Portal User license challenge. Unable to predict the number of users who will download and Subscribe. When a User is about Subscribe and the portal licenses does not exists,
      • Reminder Settings - Time Tracker

        On the time tracker in Reminder Settings I created a reminder according to the Zoho manual. But a manager asked me to change the message that goes in the email. Is it possible to change the message? I didn't find that in the Zoho manual. Another question: I configured to receive the reminder everyone who logged in less than 40 hours. Does Zoho consider less than 40 hours of the current week or the whole month? Another situation, I put it so that I and another specific user would receive the notification,
      • New in Cadences: WhatsApp follow-ups, upgraded limits, and options for add-ons

        Hello everyone, We're rolling out two key updates to help you engage better and scale smarter with Cadences in Zoho CRM. Reach customers on WhatsApp, directly from Cadences Previously, Cadences have enabled you to automate follow-ups through emails, calls,
      • Specific ListView Canvas on Canvas Home Page Always Loads Most Recent ListView, Not the One Specified

        I had mentioned this to ZOHO, but I mainly wanted to see if others in the Community are also facing this problem. I created a Canvas ListView for a Custom Module, and then created a Canvas Home page (technically on a tab item, but I'm not sure if that
      • Zoho Mail not updating contacts

        We renamed a large number of users in Zoho Mail Admin Console. The updated names appear correctly in the Admin Console and in the users’ Zoho Account profiles, but Organization Contacts still contain the previous display names. As a result, compose autocomplete
      • This user is not allowed to add in Zoho. Please contact support-as@zohocorp.com for further details

        Hello, I am the Super Administrator of the Zoho Mail organization for carrytrail.com. The domain has already been verified, but when I try to create the user. I receive the following error: “This user is not allowed to add in Zoho. Please contact support-as@zohocorp.com
      • Tip #92 – Organize your support operations with Departments – ‘Insider Insights’

        Hello Zoho Assist Community! As a support team grows, so does the complexity. Different customers, different products, technicians spread across regions, and each group needing its own way of working. When everyone operates from a single shared space,
      • Introducing Zoho Office Desktop

        Hi users, We are excited to announce Zoho Office Desktop, a single app to install, update, and open Zoho Writer, Sheet, Show, and PDF Editor on Windows and macOS. It includes: One home for every app: Choose the apps you want, and a guided installation
      • How Can You Find Broken Internal Links Without Checking Every Page Manually?

        Broken internal links are a common technical SEO issue. They can send visitors to missing pages, interrupt navigation, and make website maintenance more difficult. On a large website, checking every link manually is simply not practical. So, how can you
      • Zoho Writer for Android: Q2 2026 updates

        Hi users, We are excited to announce the Q2 2026 updates for Zoho Writer for Android. This includes: Formatting parity with the web app: Choose from multiple ordered and unordered list styles, adjust line spacing, apply your custom paragraph styles, change
      • ZohoBooks - "Account transactions" report doesn't have any "Desciptions"

        Hi, I'd like to push for this to be included in ZohoBooks: In a "account transactions" report all the numbers are right, but I'd really like to see the "Description" as part of this report, i.e. the line-item-description as I would see it in the bank statement. Essentially all you see is a list of numbers adding up to the total. It is very difficult to see if things are right without being able to see what exactly each transaction refers to. Going into each transaction one-by-one is not a workable
      • Zoho Projects | Q3 Updates

        Hello everyone, Here's a roundup of everything we released from July to September. We have added some new features as well as improved some of the existing ones. Project Financials Finance Integration Integrate your Project with Zoho Books, Zoho Invoice,
      • Meet your customers on Arattai, from inside Zoho CRM

        Hello everyone, Your customers reach you on the apps they already use. Zoho CRM now supports one more: our very own Arattai! When someone messages your Arattai Business number, the conversation arrives in the Messages module in CRM, right beside your
      • Running Balance

        Please add automatically Running balance in ledger view. Taking lot of time, every time to add manually
      • MAKING ENTRY TIME MORE USER FRIENDLY AND FASTER O PREVENT TAB TIME

        I AM CURIOUS TO KNOW IF WE CAN MAKE IT MORE USER FRIENDLY WHILE MAKING BILLS , I MAJORLY USE OVER DESKTOP SO I AM SUGGESTING TO REMOVE TAB TIME WHILE ENTERING BILL OR MAKING INVOICE DIRECT JUMP TO ONLY REGULAR PARTS OF THE BILL . YOURS RAKESH 782866
      • Add Payment Information (like Bank details)

        I am using the Free plan of Zoho Books. I need to add the bank details/ UPI details on the invoice. How can I do that. I have added the details in the Bank Section.
      • account access nahi kar pa raha hoo

        hello sir/maddam, mera naam Indrasen Lodhi hai meri zoho mail id "indrasenlodhi@zohomail.in" hai. main iska authenticator app bhul gaya hu, mere pass bachup code bhi nahi hai. kripya meri madad kijiye.
      • Keep Sensitive Customer Data Private with Field Masking in Zoho CRM

        Hello CRM community, Customer records in your CRM are often accessible across multiple teams, but not every team needs visibility into every field. A non-sales team, for instance, has no real need to see a contact's mobile number, and a support agent
      • E-invoicing setup not completed in Zoho Books

        My status on the EmaraTax portal appears as linked with Zoho. However, when I try to complete the setup on the E-invoicing tab in Zoho Books settings, I receive an error saying: "E-Invoicing could not be enabled as the FTA portal is currently unreachable.
      • Notes - Reaction Buttons

        Using the native notes option within CRM is fine, it works and the RTF features are great, however, would it be possible - if there isnt already something in place, where we can add a reactions button, similar to teams/whatsapp to show that its been read
      • Generate a link for Zoho Sign we can copy and use in a separate email

        Please consider adding functionality that would all a user to copy a reminder link so that we can include it in a personalized email instead of sending a Zoho reminder. Or, allow us to customize the reminder email. Use Case: We have clients we need to
      • Next Page