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

      • Early Preview for an Upcoming Enhancement to Zoho One - App Adoption and Feature Discovery

        Hello, Enterprise Support Community, We're excited to give you an early sneak peak at an upcoming enhancement to the Zoho One platform: new App Adoption & Feature Discovery components, designed to help our customers adopt the right tools to enhance their
      • You cannot send this email campaign as it doesn't have any eligible contacts in the selected mailing list. You can try adding contacts or choose other mailing lists.

        please help
      • Add Days In Stage to Filter Options for Pipeline

        We use the days in stage to see how long a ticket has been in a certain stage. But there is no option to see this via filters. eg if i wanted to see how many tickets over 5 days in a stage, there no way to do this. Currently we have to export a report
      • Integration problem between zoho crm and zoho forms for an update in zcrm, with two mapped custom fields

        Hello everyone, I need to correct an existing integration between Zoho CRM and Zoho Forms: the use case is that a user needs to send an email to a contact, who will click on a button in this email, redirecting to a Zoho Forms. The contact can update or
      • Purchase Order Quantity Validation Not Enforced During Bill Approval

        Hello Team, I would like to report a potential issue in the Purchase Order to Bill workflow. Steps to reproduce: Create a Purchase Order for an item with Quantity = 100. Approve/sign the Purchase Order. Convert the Purchase Order into a Bill. Change the
      • How do I add multiple contacts in a deal

        How do I add multiple contacts in a deal
      • Blueprint Not Triggering When Lead Status Is Updated by Workflow (IndiaMART Integration)

        I have set up a blueprint that triggers when a lead’s status is “New Lead.” Our CRM is integrated with IndiaMART, and when leads are created from IndiaMART, their Lead Status is initially set to None. To handle this, I created a workflow that automatically
      • Add multiple users to a task

        When I´m assigning a task it is almost always related to more than one person. Practical situation: When a client request some improvement the related department opens the task with the situation and people related to it as the client itself, the salesman
      • Journey vs Campaign Confusions

        Hi there! I hope you're all doing great! I'm new to the Zoho MA and I'm confused between Journey and Campaigns. I'm not sure if these two work together or not. I hope you can enlighten me. What I'm trying to do is setting up a Newsletter. 1. We have a
      • The 3.1 biggest problems with Kiosk right now

        I can see a lot of promise in Kiosk, but it currently has limited functionality that makes it a bit of an ugly duckling. It's great at some things, but woeful at others, meaning people must rely on multiple tools within CRM for their business processes.
      • Zoho Webinar not sending calendar entry into Outlook or other calendars

        Dear All, I am using Zoho Webinar for last few months and noted that when a attendee registers at the webinar link he gets an email will intimating his registration and link to webinar. He also get few file ( for Outlook, Google calendar etc) which he
      • Deleted User Emails

        I need to delete a user as I need to re-use their license, but I'd like to keep all their emails that are attached to various contacts in the CRM. Their emails are hosted externally on an M365 license. Anyone any idea how best to engineer this? TIA
      • Ticket Status

        HI, Any idea on how to create other options for this header??? I want to add an "Ordered" status. Its under "tickets" in Overview, I need a new status created (see second picture)
      • Turning off the recorded welcome in Zoho Webinar

        Is there a way to turn off the recorded voice that comes up at the beginning of every webinar session? It devalues the experience for attendees from feedback, interrupting their connection with our brand and delaying webinar start unnecessarily.
      • Client Script | Update - Client Script Support For Custom Buttons

        Hello everyone! We are excited to announce one of the most requested features - Client Script support for Custom Buttons. This enhancement lets you run custom logic on button actions, giving you greater flexibility and control over your user interactions.
      • Save embed widget personalizations

        Ok, Zoho, Great work on providing PRICING TABLES via the embed widget. Thanks so much. This changed the game for me Only one slight problem....I can't seem to save my widget settings. I'm still building my products and plans but I'm testing how they look
      • Problem with UTM Parameters: Zoho Forms - Zoho Desk Integration

        Hi Zoho Support Team, I want to automatically capture UTM Parameters from my website URLs and pass it from Zoho Forms into Zoho Desk. I have activated the UTM tracking feature. I've integrated the UTM Tracking code in my website footer on all pages. I've
      • Team folder not created when creating project using zoho flow

        When I try to automate project creation using zoho flow, and I have enabled workdrive integration to automatically create team folders to attach to the project, this only works when I create a new project through the UI. But I am trying to automate project
      • Add an option to deactivate Zoho Meeting "Welcome" message

        My request is to provide an option to deactivate the annoying Zoho Meeting "Welcome" voice when participants join meetings... or remove it all together. First impressions count, especially with new clients. This notification reminds me of the AOL "You've
      • Service line items

        Hello Latha, Could you please let me know the maximum number of service line items that can be added to a single work order? Thanks, Chethiya.
      • SalesIQ > My Chat sort by Unread or Follow-up

        Hi Zoho SalesIQ Team, I would like to submit a feature request regarding the My Chat > Sorting in the SalesIQ UnRead Follow-up Conversation tags Thank you for considering. Best regards, CJ
      • Record sharing for Activities modules in CRM

        Hello everyone, We've got a few quick enhancements to what we covered in this previous announcement: record sharing is now available for Activities modules. 1. Sharing Tasks, Meetings, and Calls Until now, activity records could only be shared indirectly
      • SalesIQ : How to disable "Idle chat handling" ?

        Hello SalesIQ Team. SalesIQ, How to disable "Idle chat handling" ? I would like to disable the option “Automatically close chats that have been idle for a specified amount of time.”
      • How do I create an update to the Cost Price from landed costs?

        Hi fellow Zoho Inventory battlers, I am new to Zoho inventory and was completely baffled to find that the cost price of products does not update when a new purchase order is received. The cost price is just made up numbers I start with when the product
      • Facturation électronique 2026 - obligation dès le 1er septembre 2026

        Bonjour, Je me permets de réagir à divers posts publiés ici et là concernant le projet de E-Invoicing, dans le cadre de la facturation électronique prévue très prochainement. Dans le cadre du passage à la facturation électronique pour les entreprises,
      • Function and workflow to create customer payment and send receipt

         I am attempting to set up a workflow/custom function for the automatic creation of a customer payment and sending the email receipt, but am receiving the error "Improper Statement Error might be due to missing ';' at end of the line or incomplete expression" I've been over everything several times and cannot see where the error is (code is copied into the attached document).  I haven't used custom functions before with Deluge, so it's very likely something very simple, or I've completely mucked
      • Smart Alerts: Protect users with configurable email alerts

        Email-based threats are becoming harder to identify and manage. Administrators need proactive ways to protect users from phishing, fraud, and policy violations. Standard filters can block emails, but blocking alone isn't always the most effective response.
      • Power up Zoho CRM with project intelligence

        Dear user, You're probably one of those businesses using your CRM as a single source of truth. It's where sales, project execution, and finance teams go to analyze past decisions and formulate future strategies. But what happens when project data is either
      • Print multiple uploaded images in an HTML snippet in a Page

        I have a Form: Job_Preparation It stores details of each new item that must be built by the fabricators in our workshop. The form has a field: Documents I upload 4 image files to the Documents field. I want to print a sheet for our workshop staff with
      • "Track Inventory for this item" is forced checked by default for goods items (eTims issue?)

        Hello, Since connecting our Zoho books to eTims (Kenya) the "Track Inventory for this item" is forced checked by default (eTims issue?) in the Item creation page for any type of goods. So when purchasing anything that the company does not intend to sale,
      • Its 2022, can our customers log into CRM on their mobiles? Zoho Response: Maybe Later

        I am a long time Zoho CRM user. I have just started using the client portal feature. On the plus side I have found it very fast and very easy (for someone used to the CRM config) to set up a subset of module views that make a potentially extremely useful
      • Why can't we choose Fixed Asset account for Purchased Items? (eTims issue?)

        Hello, When the company purchase items not for sale and not supposed to be in the inventory stock, like equipment for operational use, there is no way to access the Fixed Asset accounts in the drop down list. Is that an eTims limitation again? Or something
      • Zoho Team Inbox - roadmap

        Hi, would be good to understand the Teaminbox roadmap, in particular: 1. API / Zoho Deluge connections. We have a process where the each email needs to be either tagged or assigned daily. It would be great if we could automate a 5pm alert for any exemptions
      • Free webinar! Sign documents across borders: AES, QES, ID verification

        Hello all, Signing paperwork across geographies sounds simple, until critical questions around legality, security, and compliance pop up. Join our upcoming webinar to see how Zoho Sign helps businesses worldwide sign documents with confidence. Agenda:
      • Add field "Expected Availability Date" to Purchase Orders

        Hi there. We drop ship and 'make to order' whereby we backorder sales order items directly with factories for manufacturing. One of the leading questions from Customers is "when is the order ready". Currently there is an 'Expected Delivery Date', which
      • Related list view for Assets

        We first set up all our parent assets in FSM and now we are adding child assets which are the parts for the parent assets. When under the customer related list, since it only displays 5 rows of data, I have to click through many assets to locate the parent
      • How To Invoice Immediately for Future Subscription

        Hi, When a new subscription is created that has a future start date, Zoho Subscriptions does not invoice the customer until the start date of the subscription. Is there a way to immediately invoice the customer as soon as the subscription is created,
      • name change of company in same GSTIN registration . how to retain historical company name for past transactions?

        hello I have recently change my company name from BHANU DIAM to BHANUMATI IMPEX in same GSTIN registration number While i have update the company name in profile name that change all my historic data like sale invoices and purchase bill , i would like
      • Problem with the blueprint flow.

        Scenario: 3 departments in a single environment: A-B-C agents from department 1 D-E-F agents from department 2 G-H agents from department 3 Since we've been using Zohodesk (2023), agents can assign tickets to the correct department using the blueprint
      • Spell Check Red Underlines Keep Appearing Even After Disabling

        Hello Zoho Support, I'm facing an issue in Zoho Writer where red spell-check underlines keep appearing even after I disable Spell Check. I have already: Turned OFF Spelling Errors Turned OFF Grammar Turned OFF Writing Quality Turned OFF browser spell
      • Next Page