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!

    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

                                                            • 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
                                                            • Function #37: Create a Purchase Order from a Quote

                                                              Welcome back everyone! Last week, we learnt how to calculate the total number of activities for a lead and further take note of the activity count for particular dates. For instance, from the period of Demo to Negotiation. This week, let's look at a function that lets you create a Purchase Order instantly from a Quote. Business scenario: In any form of business, one of the most important things to do is to document the transactions. Naturally, negotiation, signing an agreement, placing an order,


                                                            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 Writer

                                                                                              Get Started. Write Away!

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

                                                                                                Zoho CRM コンテンツ




                                                                                                  Nederlandse Hulpbronnen


                                                                                                      ご検討中の方




                                                                                                            • Recent Topics

                                                                                                            • I want to transfer the project created in this account to another account

                                                                                                              Dear Sir I want to transfer the project created in one account to another account
                                                                                                            • Inactive User Auto Response

                                                                                                              We use Zoho One, and we have a couple employees that are no longer with us, but people are still attempting to email them. I'd like an autoresponder to let them no the person is no longer here, and how they can reach us going forward. I saw a similar
                                                                                                            • Weekly Tips : Customize your Compose for a smoother workflow

                                                                                                              You are someone who sends a lot of emails, but half the sections in the composer just get in your way — like fields you never use or sections that clutter the space. You find yourself always hunting for the same few formatting tools, and the layout just
                                                                                                            • Custom Bulk Select Button

                                                                                                              Zoho CRM offers the ability to select multiple records and invoke a Custom Button This functionality is missing from Recruit Currently we can only add buttons in the detail page and list But we cannot select Multiple Records and invoke a function with
                                                                                                            • Need support in setting up the company email and few other setups

                                                                                                              Need support in setting up the company email and few other setups
                                                                                                            • Power of Automation :: Smart Ticket Management Between Zoho Desk and Projects

                                                                                                              Hello Everyone, A custom function is a software code that can be used to automate a process and this allows you to automate a notification, call a webhook, or perform logic immediately after a workflow rule is triggered. This feature helps to automate
                                                                                                            • Need to set workflow or journey wait time (time delay) in minutes, not hours

                                                                                                              Minimum wait time for both Campaigns workflows and Marketing Automation journeys is one hour. I need one or the other to be set to several minutes (fraction of the hour). I tried to solve this by entering a fraction but the wait time data type is an integer
                                                                                                            • Remote Server is misconfigured

                                                                                                              Dear Team, I am unable to use email id as remote server is misconfigured. It would be really great if you could help on this and get this resolved. Thanks & Regard Rohit Gupta
                                                                                                            • BUG - Google Business Buttons - Add a button to GBP Post

                                                                                                              I am experiencing an issue with the "Add a button" feature when creating posts for my Google Business Profile (GBP) through Zoho Social. When I schedule or publish a GBP post and include a call-to-action button with a specific URL, the post itself publishes
                                                                                                            • This mobile number has been marked spam.

                                                                                                              Dear zoho team, I am very happy to use zoho,because it india 🇮🇳 own app, but when we login into zoho account we facing some issue, please solve below issue ASAP. Add your mobile number As an added security measure for Accounts, you need to verify and
                                                                                                            • Do you have software like Windows software?

                                                                                                              We want swadeshi software
                                                                                                            • Support for Custom Fonts in Zoho Recruit Career Site and Candidate Portal

                                                                                                              Dear Zoho Recruit Team, I hope you're doing well. We would like to request the ability to use custom fonts in the Zoho Recruit Career Site and Candidate Portal. Currently only the default fonts (Roboto, Lato, and Montserrat) are available. While these
                                                                                                            • Trying to export a report to Excel via a deluge script

                                                                                                              I have this code from other posts but it gives me an error of improper statement, due to missing ; at end of line or incomplete expression. Tried lots of variations to no avail. openUrl(https://creatorapp.zoho.com/<username>/<app name>/XLSX/#Report:<reportname>,"same
                                                                                                            • Need help to create a attach file api

                                                                                                              https://www.zoho.com/crm/developer/docs/api/v8/upload-attachment.html Please help me to create it... It's not working for while. Do you have some example?
                                                                                                            • Export view via deluge.

                                                                                                              Hi, Is it possible to export a view (as a spreadsheet) via deluge? I would like to be able to export a view as a spreadsheet when a user clicks a button. Thanks     
                                                                                                            • Zoho Inventory's latest shipping integration updates at a glance.

                                                                                                              Hello Users, We would like to share some important news about our latest improvements in the Shipping integration capabilities of Zoho Inventory that we achieved in 2024 with some of our major integration partners in key editions across APAC, North America,
                                                                                                            • IP Address Blocked

                                                                                                              Hi Team. Hope you're doing good. I'm unable to access Zoho with my IP address. I have to use VPN to access it. IP: 39.44.12.153 This is happening with all the Zoho products, the admin console and the mail.
                                                                                                            • Outdated state in mexico

                                                                                                              Hello Zoho team, the drop down to add the state for customers, when they introduce their state in mexico has a city named “Distrito Federal” that name changed many years ago to “ciudad de mexico”. could you please update this so my clients can find the
                                                                                                            • Possible to generate/download Quote PDF using REST API?

                                                                                                              See title. Is there any way after a quote has been created to export to a PDF using a specified template and then download it? Seems like something that should be doable. Is this not supported in the API v2.0?
                                                                                                            • Creating an invoice to be paid in two installments?

                                                                                                              Hi there, I own a small Photographic Services business and have not been able to find a way to fit my billing system into Zoho, or any other Accounting software. The way my payments work is: 1. Customer pays 50% of total price of service to secure their
                                                                                                            • Bug in allowing the user to buy out of stock items

                                                                                                              Hi i want to allow the user to buy out of stock items, according to the commerce documentation if i disable Restrict "Out of stock" purchases it will, but it doesnt work, so i want to know if it had any relation with zoho inventory, and if theres any
                                                                                                            • Replace Lookup fields ID value with their actual name and adding inormation from subforms

                                                                                                              Hi everyone,  I wanted to see if someone smarter than me has managed to find any solutions to two problems we have. I will explain both below.  To start we are syncing data from Zoho CRM to Zoho Analytics and I will use the Sales Order module when giving
                                                                                                            • Can a Zoho Sites page be embedded into another website (outside Zoho)

                                                                                                              Hi All, We have a request from a client - they'd like to take one of our information pages created in Zoho Sites and embed it into their own website? I was told through an email with Zoho that this was possible >>Thank you for your patience regarding
                                                                                                            • Bug in allowing the user to buy out of stock items

                                                                                                              Hi i want to allow the user to buy out of stock items, according to the commerce documentation if i disable Restrict "Out of stock" purchases it will, but it doesnt work, so i want to know if it had any relation with zoho inventory, and if theres any
                                                                                                            • Transition Criteria Appearing on Blueprint Transitions

                                                                                                              On Monday, Sept. 8th, the Transition criteria started appearing on our Blueprints when users hover over a Transition button. See image. We contacted Zoho support because it's confusing our users (there's really no reason for them to see it), but we haven't
                                                                                                            • Zoho CRM Sales Targets for Individual Salespeople

                                                                                                              Our organistion has salespeople that are allocated to different regions and have different annual sales targets as a result. I am building an CRM analytics dashboard for the sales team, which will display a target meter for the logged in salesperson.
                                                                                                            • Transfer all Related Data to new Account Owner

                                                                                                              Currently when I change the account Owner I only see the option to change only the open deals But I want the new account owner to take over all the related modules and all the deal stages Is it not possible right now? Am I missing something? Do I really
                                                                                                            • Can i connect 2 instagram accounts to 1 brand?

                                                                                                              Can i connect 2 instagram accounts to 1 brand? Or Do i need to create 2 brands for that? also under what subscription package will this apply?
                                                                                                            • Add an external email to the allowed list

                                                                                                              I need to allow an external email to raise a ticket on Manage Engine ServiceDesk Plus. The external email is a outside of our domain and is not a domain user. The email address that needs to be allowed to raise a ticket request is noreply@formsatack.com.
                                                                                                            • How to Calculate MTTR (Mean Time to Resolve)

                                                                                                              We want to calculate MTTR (Mean Time to Resolve) in our Zoho Analytics report under Tickets. Currently, we are using the following fields: Ticket ID Ticket Created Time Ticket Closed Time Ticket On Hold Time We are planning to calculate MTTR (in days)
                                                                                                            • How to export project tasks, including the comments

                                                                                                              Hi, how can I export the project tasks, whereby I can also see the comments associated to a specific task? The use-case is that often we use comments to discuss or update a task related ideas. I would like to export the tasks, where we can also see the
                                                                                                            • Unable to see Zoho contacts in Zoho app on ios

                                                                                                              Hi Support Team, I am a new user, I have created my account and installed zohomail app on iOS 16 which works. I was also able to import my Gmail contacts into Zoho Contacts, which I can see. The problem is that I can’t see these imported cobalts in Zohomail
                                                                                                            • Does Zoho Sheet Supports https://n8n.io ?

                                                                                                              Does Zoho Sheet Supports https://n8n.io ? If not, can we take this as an idea and deploy in future please? Thanks
                                                                                                            • Bigin Android app update: User management

                                                                                                              Hello everyone! In the most recent Bigin Android app update, we have brought in support for the 'Users and Controls' section. You can now manage the users in your organization within the mobile app. There are three tabs in the 'Users and Controls' section:
                                                                                                            • Share records with your customers and let them track their statuses in real time.

                                                                                                              Greetings, I hope everyone is doing well! We're excited to introduce the external sharing feature for pipeline records. This new enhancement enables you to share pipeline records with your customers via a shareable link and thereby track the status of
                                                                                                            • Live webinar: Discover Zoho Show: A complete walkthrough

                                                                                                              Hello everyone, We’re excited to invite you to our upcoming live webinar, Discover Zoho Show: A Complete Walkthrough. Whether you’re just getting started with Show or eager to explore advanced capabilities, this session will show you useful tips and features
                                                                                                            • Deal Stage component/widget/whatever it is... event

                                                                                                              Deal Stages I am trying to access the event and value of this component. I can do it by changing the Stage field but users can also change a Deal Stage via this component and I need to be able to capture both values. Clicking on 'Verbal' for instance,
                                                                                                            • Create advanced slideshows with hybrid reports using Zoho Projects Plus

                                                                                                              Are your quarterly meetings coming up? It’s time to pull up metrics, generate reports, and juggle between slides yet again. While this may be easier for smaller projects, large organizations that run multiple projects may experience the pressure when
                                                                                                            • Add an option to disable ZIA suggestions

                                                                                                              Currently, ZIA in Zoho Inventory automatically provides suggestions, such as sending order confirmation emails. However, there is no way to disable this feature. In our case, orders are automatically created by customers, and we’ve built a custom workflow
                                                                                                            • Formula field with IF statement based on picklist field and string output to copy/paste in multi-line field via function

                                                                                                              Hello there, I am working on a formula field based on a 3-item picklist field (i.e. *empty value*, 'Progress payment', 'Letter of credit'). Depending on the picked item, the formula field shall give a specific multi-line string (say 'XXX' in case of 'Progress
                                                                                                            • Next Page