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

    Nederlandse Hulpbronnen


      • Recent Topics

      • Power up your Kiosk Studio with Real-Time Data Capture, Client Scripts & More!

        Hello Everyone, We’re thrilled to announce a powerful set of enhancements to Kiosk Studio in Zoho CRM. These new updates give you more flexibility, faster record handling, and real-time data capture, making your Kiosk flows smarter and more efficient
      • Release Notes | January 2026

        We have rolled out a set of powerful new enhancements across Zoho Vertical Studio that bring several long-awaited capabilities to your applications. These updates focus on deeper customization, smarter automation, better reporting, and improved usability
      • [Free Webinar] Zoho RPA - OCR, PDF Automation, & More

        Hello Everyone! Greetings from the Zoho RPA Training Team! We’re excited to invite you to our upcoming webinar on the latest release updates for Zoho RPA, where we’ll unveil powerful new capabilities designed to make your automation journey smarter, faster,
      • Zobot Execution Logs & Run History (Similar to Zoho Flow)

        Dear Zoho SalesIQ Team, We would like to request an enhancement for Zoho SalesIQ Zobot: adding an execution log / run history, similar to what already exists in Zoho Flow. Reference: Zoho Flow In Zoho Flow, every execution is recorded in the History tab,
      • Capture Last check-in date & days since

        I have two custom fields on my Account form, these are "Date of Last Check-In" and "Days Since Last Contact" Using a custom function how can I pull the date from the last check-in and display it in the field "Date of Last Check-In"? and then also display the number of days since last check-in in the "Days SInce Last Contact" field? I tried following a couple of examples but got myself into a bit of a muddle!
      • Global Search Settings

        I'd love a way to remove some modules from being included in the global search. This would allow use to provide a better user experience, limiting the global search to only those modules that are regularly used removing any models used for background
      • Card Location in Zobot

        Hello, when using the “Location” card in a codeless builder Zobot, the behavior in WhatsApp is inconsistent. When asking the user to share their location, they can type a message, which will return the message “Sorry, the entered location is invalid.
      • Automation Series: Auto-create Dependent Task on Status Change

        In Zoho Projects, you can automatically create and assign a dependent task when a task’s status is updated. This helps teams stay aligned, ensures reviews happen on time, and reduces manual effort. In this post, we’ll walk through an easy setup using
      • Zoho CRM || Unable to Bulk Assignment of Territories for Contacts

        Dear Zoho CRM Support Team, I hope this email finds you well. We recently performed a bulk upload of Contacts into Zoho CRM using the official sample Excel template downloaded from the CRM. The upload itself was completed successfully; however, we encountered
      • Languages in Zobot

        Hello, I have found a list of supported languages for the Zobot. The information specifies the languages are supported in the following 3 features: SalesIQ supports 34 different languages in the following features. Resources (Articles, FAQs, Small Talks)
      • Sync your Products Module for better context.

        In customer support, context is everything. The integration between Zoho Desk and Zoho CRM helps your sales and support teams function as one, delivering better customer experiences. With the latest update to this integration, you can now sync the Product module in your Zoho CRM with your Zoho Desk portal. This feature enables products from Zoho CRM to reflect in the "product" field in Zoho Desk. This can save your support team valuable time and effort.    Some things to note when syncing the two:
      • Composite items inside of composite items; bill of materials needed

        Hi Zoho and Everyone, I am evaluating whether Zoho Inventory will work for my small business. I grow and harvest herbs and spices but also get from wholesalers. I use all these items to make herbal teas, but also sell them as individual items on my Shopify store and Etsy. I discovered the composite item bundling and am wondering if I could get some assistance since there is no bill of materials: Our herbal company's best selling tea is a sleepytime tea. Sleepytime Tea can be purchased in three weights
      • Action required: Reauthorizing your Google account for automatic cloud backup to Google Drive

        This is applicable to users who have already configured automatic cloud backup to Google Drive. Hi there! Google has mandated reauthorization of all preconfigured third-party integrations to ensure only the necessary scopes are shared as an improved security
      • Zoho CRM Layouts

        I have customised all our modules, Leads, Contacts and deals, and within them, I have created lots of different layouts depending on the type of Lead or contact, for example. Since the new Zoho UI came out, they have all disappeared. I have gone into
      • Zoho Desk API - Send Reply to CUSTOMERPORTAL

        Hello! I'll try to send a reply to Customer Portal, But the response is 500 (INTERNAL_SERVER_ERROR in service response). {"Error":"{\"errorCode\":\"INTERNAL_SERVER_ERROR\",\"message\":\"An internal server error occurred while performing this operation.\"}"}
      • Zoho CRM for Everyone's NextGen UI Gets an Upgrade

        Hello Everyone We've made improvements to Zoho CRM for Everyone's Nextgen UI. These changes are the result of valuable feedback from you where we’ve focused on improving usability, providing wider screen space, and making navigation smoother so everything
      • WhatsApp IM in Zoho Desk always routes to Admin instead of assigned agent

        Hello Zoho Experts, I connected WhatsApp IM to my Zoho Desk account. I only assigned my Customer Service (CS) agent to the WhatsApp channel, and I did NOT include Admin in this channel. However, every new WhatsApp conversation automatically gets assigned
      • hide resolution from help centre

        to my surprise, i just found out that the resolution text is public in the helpcenter, even if 'notify customer' is off. is there a workaround to that? how do others deal with this? How zoho support does this and I don't think its used by Zoho in the first place. the resolution is meant to be private, not public
      • Multiple Cover Letters

        We are using the staffing firm edition of Recruit and we have noticed that candidates cannot add more than one cover letter. This is a problem as they might be applying for multiple jobs on our career site and when we submit their application to a client,
      • Zoho Analytics + Facebook Ads: Performance Alerts for Active Campaigns

        Is it possible with integration of Zoho Analytics with Facebook Ads and set up alerts or notifications for active campaigns when performance drops? For example, triggering a notification if CTR goes below a defined threshold or if other key metrics (like
      • Multiple upload field CRM

        I desperately need the functionality to add more than one upload field to web to contacts form. How can I do this?
      • Workdrive Oauth2 Token Isn't Refreshing

        I have set up oauth for a bunch of zoho apis and have never had a problem with oauth. With workdrive i am using the exact same template i usually use for the other zoho apps and it is not working. All requests will work for the first hour then stops so
      • Sort by age

        It would be very helpful if there was a way to sort by age in the Age column. Please add this function if possible. Thanks!
      • Lookup Field Option Not Available in Customization

        Hello, I am trying to customize different modules (e.g., Work Orders, Systems, and others), but I am unable to find the Lookup field option in the layout customization. When I go to: Setup → Customization → Modules and Fields → Add Field The Lookup field
      • Stage History previous stage to new stage

        We are looking for a way to display deals that have changed stages the previous week. We want to see what stage it was previously and what it was changed to, as well as salespersons names if possible. I've tried to create a report as well as looked into
      • Snapchat

        Are there any plans to add Snapchat to Zoho Social or is there any API that we can use to integrate into Zoho.
      • Scheduled sending of a poll and its results

        Is there a way to schedule sending a poll to all my users and have the results sent separately to the team?
      • Canvas View bug

        I would like to report a bug. When clone a canvas view from an existing canvas view, if the original canvas view have canvas button with client script. Then the new create canvas view will have canvas button, it is make sense. But when I try to delete
      • How can I import OLM to Yandex Mail easily?

        For migrating Mac Outlook OLM data to Yandex Mail efficiently, the Aryson OLM Converter is a reliable professional tool that ensures complete data integrity throughout the process. Unlike manual methods, which can risk inconsistent formatting or missing
      • Zoho recruit's blueprint configuration is not functioning as mapped

        Current Status: Zoho Blueprint is not functioning as configured. Issue: We are moving a Candidate status in Zoho Recruit "for active file" but we encountered: "Status cannot be changed for records involved in Blueprint." This happens to various client
      • CRM x WorkDrive: We're rolling out the WorkDrive-powered file storage experience for existing users

        Release plan: Gradual rollout to customers without file storage add-ons, in this order: 1. Standalone CRM 2. CRM Plus and Zoho One DCs: All | Editions: All Available now for: - Standalone CRM accounts in Free and Standard editions without file storage
      • validation rules doesn't work in Blueprint when it is validated using function?

        I have tried to create a validation rule in the deal module. it works if I try to create a deal manually or if I try to update the empty field inside a deal. but when I try to update the field via the blueprint mandatory field, it seems the validation
      • Bulk Delete Attachments

        Is there a way to bulk delete attachments on the form entries? our storage is full and deleting files one by one is pain taking process.
      • Integrating Zoho Suite and apps more with Linux

        I just got introduced with Zoho just couple of months ago, and I've already planned to contribute to it, even though it's not an open-source software. Still I have found it's potential to beat the tech giants and still being respective towards data privacy
      • How do I edit the Calendar Invite notifications for Interviews in Recruit?

        I'm setting up the Zoho Recruit Interview Calendar system but there's some notifications I don't have any control over. I've turned off all Workflows and Automations related to the Calendar Scheduling and it seems that it's the notification that is sent
      • Store Submitted Forms as PDF

        Hi there, Is there a method to store Form submissions as a PDF in workdrive for archival? I set the form to email the submission to the user and an internal inbox but I'd really love to store the final form as PDF in workdrive automatically. I can't seem
      • How can Data Enrichment be automatically triggered when a new Lead is created in Zoho CRM?

        Hi, I have a pipeline where a Lead is created automatically through the Zoho API and I've been trying to look for a way to automatically apply Data Enrichment on this created lead. 1) I did not find any way to do this through the Zoho API; it seems like
      • Important Update: Google Ads & YouTube Ads API Migration

        To maintain platform performance and align with Google's newest requirements, we are updating the Google Ads and YouTube Ads integrations by migrating from API v19 to the newer v22, before the official deprecation of v19 on February 11, 2026. Reference:
      • Separate Items & Services

        Hi, please separate items and services into different categories. Thank you
      • How to list services on quote instead of products

        I need to create a customer facing estimate that displays our services. The default quote layout only allows products to be listed. Is there a way to correct this?
      • Next Page