Function to check frequency of customer ordering patterns

Function to check frequency of customer ordering patterns

Hi,

I'm no coder, so I thought I could make use of Chat GPT to generate some Deluge script to create a function that would check order frequency of our customers so that I could send an email if they go beyond their usual order pattern.

Chat GPT and Claude seemed super confident they could do the job, but failed. I keep getting errors.

Here's sample code:

string calculateOrderFrequency(string orderID)
{
    // Get the Contact associated with this order
    contactInfo = zoho.crm.getRelatedRecords("Contacts", "Sales_Orders", orderID);
    
    // If no contact is found, exit the function
    if(contactInfo.isEmpty())
    {
        return "No contact found for this order";
    }
    
    // Get the contact ID from the first related contact
    contactId = contactInfo.get(0).get("id");
    
    // Retrieve all previous orders for this contact
    previous_orders = zoho.crm.getRelatedRecords("Sales_Orders", "Contacts", contactId);
    
    // We need at least 2 orders to calculate frequency
    if(previous_orders.size() >= 2)
    {
        // Create a list to store order dates
        order_dates = List();
        
        // Add all order dates to our list
        for each rec in previous_orders
        {
            orderDate = rec.get("Order_Date");
            if(orderDate != null)
            {
                order_dates.add(orderDate);
            }
        }
        
        // Sort dates from oldest to newest
        order_dates.sort();
        
        // Calculate time between orders using a different approach
        total_days = 0;
        intervals = 0;
        
        // Calculate date differences without using a standard loop
        latest_index = order_dates.size() - 1;
        
        // Process manually if we have at least 2 dates
        if(latest_index >= 1)
        {
            // Manually calculate first interval
            days_diff_1 = dateDiff(order_dates.get(1), order_dates.get(0), "days");
            total_days = total_days + days_diff_1;
            intervals = intervals + 1;
            
            // Manually calculate second interval if we have enough dates
            if(latest_index >= 2)
            {
                days_diff_2 = dateDiff(order_dates.get(2), order_dates.get(1), "days");
                total_days = total_days + days_diff_2;
                intervals = intervals + 1;
                
                // Manually calculate third interval if we have enough dates
                if(latest_index >= 3)
                {
                    days_diff_3 = dateDiff(order_dates.get(3), order_dates.get(2), "days");
                    total_days = total_days + days_diff_3;
                    intervals = intervals + 1;
                    
                    // Manually calculate fourth interval if we have enough dates
                    if(latest_index >= 4)
                    {
                        days_diff_4 = dateDiff(order_dates.get(4), order_dates.get(3), "days");
                        total_days = total_days + days_diff_4;
                        intervals = intervals + 1;
                        
                        // Manually calculate fifth interval if we have enough dates
                        if(latest_index >= 5)
                        {
                            days_diff_5 = dateDiff(order_dates.get(5), order_dates.get(4), "days");
                            total_days = total_days + days_diff_5;
                            intervals = intervals + 1;
                        }
                    }
                }
            }
        }
        
        // Calculate average frequency (if we have valid intervals)
        if(intervals > 0)
        {
            avg_frequency = total_days / intervals;
            
            // Round to nearest whole number
            avg_frequency = round(avg_frequency);
            
            // Create map of fields to update
            update_map = Map();
            update_map.put("Average_Order_Frequency", avg_frequency);
            update_map.put("Last_Order_Date", order_dates.get(order_dates.size() - 1));
            update_map.put("Email_Sent_Flag", false);
            
            // Update the contact record
            update_response = zoho.crm.updateRecord("Contacts", contactId, update_map);
            return "Updated contact with average order frequency: " + avg_frequency + " days";
        }
        else
        {
            return "Could not calculate intervals between orders";
        }
    }
    else
    {
        // If this is their first order, just update the last order date
        if(previous_orders.size() == 1)
        {
            update_map = Map();
            update_map.put("Last_Order_Date", previous_orders.get(0).get("Order_Date"));
            update_map.put("Email_Sent_Flag", false);
            zoho.crm.updateRecord("Contacts", contactId, update_map);
            return "First order - updated last order date only";
        }
        else
        {
            return "No orders found for this contact";
        }
    }
}

      • 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,

        • Recent Topics

        • Choosing a portal option and the "Unified customer portal"?

          I am trialling Zoho to replace various existing systems, one of which is a customer portal. Our portal allows clients to add and edit bookings, complete forms, manage their subscriptions and edit some CRM info. I am trying to understand how I might best
        • How to create a Zoho CRM report with 2 child modules

          Hi all, Is it possible to create a Zoho CRM report or chart with 2 child modules? After I add the first child module, the + button only adds another parent module. It won't let me add multiple child modules at once. We don't have Zoho Analytics and would
        • Elevate your CX delivery using CommandCenter 2.0: Simplified builder; seamless orchestration

          Most businesses want to create memorable customer experiences—but they often find it hard to keep them smooth, especially as they grow. To achieve a state of flow across their processes, teams often stitch together a series of automations using Workflow
        • Unified Directory : How to Access ?

          I signed in to Zoho One this morning and was met with the pop up about the upgraded directory (yay!) I watched the video and pressed "Get Started" ... and it took me back to the standard interface. How do I actually access the new portal/directory ?
        • Translation support expanded for Modules, Subforms and Related Lists

          Hello Everyone!   The translation feature enables organizations to translate certain values in their CRM interface into different languages. Previously, the only values that could be translated were picklist values and field names. However, we have extended
        • Send Automated WhatsApp Messages and Leverage the Improved WhatsApp Templates

          Greetings, I hope all of you are doing well. We're excited to announce a major upgrade to Bigin's WhatsApp integration that brings more flexibility, interactivity, and automation to your customer messaging. WhatsApp message automation You can now use
        • Unified task view

          Possible to enable the unified task view in Trident, that is currently available in Mail?
        • Bigin, more powerful than ever on iOS 26, iPadOS 26, macOS Tahoe, and watchOS 26.

          Hot on the heels of Apple’s latest OS updates, we’ve rolled out several enhancements and features designed to help you get the most from your Apple devices. Enjoy a refined user experience with smoother navigation and a more content-focused Liquid Glass
        • Importing data into Assets

          So we have a module in Zoho CRM called customers equipments. It links to customers modules, accounts (if needed) and products. I made a sample export and created extra fields in zoho fsm assets module. The import fails. Could not find a matching parent
        • Allow instruction field in Job Sheets

          Hello, I would like to know if it is possible to have an instruction field (multi line text) in a job sheet or if there is a workaround to be able to do it. Currently we are pretty limited in terms of fields in job sheets which makes it a bit of a struggle
        • Streamlining Work Order Automation with Zoho Projects, Writer & WorkDrive

          Hello Community, Here is the first post in 'Integration & Automation' Series. Use Case :: Create, Merge, Sign & Store Documents in Zoho WorkDrive. Scenario :: You have a standard Work Order template created in Zoho Writer. When a task status is chosen
        • The dimensions of multilingual power

          Hola, saludos de Zoho Desk. Bonjour, salutations de Zoho Desk. Hallo, Grüße von Zoho Desk. Ciao, saluti da Zoho Desk. Olá, saudações da Zoho Desk. வணக்கம், Zoho Desk இலிருந்து வாழ்த்துகள். 你好,来自 Zoho Desk 的问候。 مرحباً، تحيات من Zoho Desk. नमस्ते, Zoho
        • Multi-line address lines

          How can I enter and migrate the following 123 state street Suite 2 Into a contact address. For Salesforce imports, a CR between the information works. The ZOHO migration tool just ignores it. Plus, I can't seem to even enter it on the standard entry screen.
        • Accessing Zoho Forms

          Hi all, We're having trouble giving me access to our company's Zoho Forms account. I can log in to a Forms account that I can see was set up a year ago, but can't see any shared forms. I can log into Zoho CRM and see our company information there without
        • Archiving Contacts

          How do I archive a list of contacts, or individual contacts?
        • Cost of good field

          Is there a way we can have cost of good sold as a field added to the back end of the invoicing procedure and available in reports?
        • How to add image to items list in Invoice or Estimate?

          Hello! I have just started using Zoho Invoice to create estimates and, possibly to switch from our current CRM/ERP Vendor to Zoho. I have a small company that is installing CCTV systems and Alarm systems. My question is, can I add images of my "items" to item list in Zoho Invoice and Estimates and their description? I would like to show my clients the image of items in our estimates so they can decide if they like these items. And I tell you, often they choose more expensive products just because
        • Issue with the Permission to Zoho Form

          I am getting an error by signing in to zoho form as it is stated that i don't have permission to access this is admin account
        • CRM templates

          Hello everyone, In my company we use Zoho campaigns where we set up all newsletters and we use Zoho CRM for transactional emails. I have created some templates in Zoho campaigns but from my understanding i cannot use those in Zoho CRM, right?
        • Meet Canvas' Grid component: Your easiest way to build responsive record templates

          Visual design can be exciting—until you're knee-deep in the details. Whether it's aligning text boxes to prevent overlaps, fixing negative space, or simply making sure the right data stands out, just ironing out inconsistencies takes a lot of moving parts.
        • Addin Support in Zoho Sheet

          Is there any addin support available in zoho sheet as like google marketplace to enhance productivity by connecting with other apps, providing AI data analysis, streamlining business processes, and more?
        • Where to integrate Price Book and Product List Price

          Hello, We sync zoho crm all modules with all data to zoho analytics. In zoho crm, we have "Price Books" and "Products" modules, where each product is assigned to a few price books with different list prices. From zoho crm, I am able to export a dataset
        • Pending Sales Order Reports

          Pending sale order report is available for any single customer, Individual report is available after 3-4 clicks but consolidated list is needed to know the status each item. please help me.
        • Zoho Mail SMTP IP addresses

          We are using Zoho Mail and needs to whitelist IP for some redirections from your service to another e-mails. You can provide IP address list for Zohomail SMTP servers?
        • Migrate Your Notes from OneNote to Zoho Notebook Today

          Greetings Notebook Users, We’re excited to introduce a powerful new feature that lets you migrate your notes from Microsoft OneNote to Zoho Notebook—making your transition faster and more seamless than ever. ✨ What’s New One-click migration: Easily import
        • Deluge sendmail in Zoho Desk schedule can't send email from a verified email address

          I am trying to add a scheduled action with ZDesk using a Deluge function that sends a weekly email to specific ticket client contacts I've already verified the email address for use in ZDesk, but sendmail won't allow it in its "from:" clause. I've attached
        • Zoho Campaigns - Why do contacts have owners?

          When searching for contacts in Zoho Campaigns I am sometimes caught out when I don't select the filter option "Inactive users". So it appears that I have some contacts missing, until I realise that I need to select that option. Campaigns Support have
        • One Contact with Multiple Accounts with Portal enabled

          I have a contact that manages different accounts, so he needs to see the invoices of all the companies he manage in Portal but I found it not possible.. any idea? I tried to set different customers with the same email contact with the portal enabled and
        • End Date in Zoho Bookings

          When I give my appointments a 30 minutes time I would expect the software not to even show the End Time.  But it actually makes the user pick an End Time.  Did I just miss a setting?  
        • Zoho Commerce

          Hi, I have zoho one and use Zoho Books. I am very interested in Zoho Commerce , especially with how all is integrated but have a question. I do not want my store to show prices for customers that are not log in. Is there a way to hide the prices if not
        • email forwarding not working

          Your email forwarding service does not work. I received the confirmation email and completed the confirmation, after that nothing and nothing since no matter what I have tried. Shame as everything else was smooth. I spose it's harder to run one of these web based internet mail services than you guys thought!!! can you fix the email forwarding asap PLEASE!
        • Google Ads Conversions Not Being Tracked in Zoho CRM

          We have 3 different conversions created in our Google Ads Account. Only one of the 3 conversion types is tracking in Zoho CRM. Our forms are Elementor Forms that are mapped into Zoho CRM. It apprears to me that all leads are showing up in Zoho CRM, but
        • Zoho Desk KB article embedded on another site.

          We embed KB articles from Zoho Desk on another site (our application). When opening the article in a new tab, there is no issue, but if we choose lightbox, we are getting an error "To protect your security, help.ourdomain.com will not allow Firefox to
        • Enable Locations for Expense

          Hi, please enable Locations (ex Branches) for Zoho Expense so that there is consistency between this app and Zoho Books. Thanks in advance.
        • Currency abbreviations

          Hello, Im stuck, and need help. I need the currency fields for example, opportunity value, or total revenue, to be abbreviated, lets say for 1,000 - 1K, 1,000,000 - 1M, and so on, how should I do this?
        • Losing description after merging tickets

          Hello, We merge tickets when they are about the same topic from the same client. It happens sometimes. We recently noticed that after the merger only the description from the master ticket is left in a thread. And the slave-ticket description is erased.
        • in the Zoho Creator i have File Upload field get the file on submission of the form Get the File and upload to Zoho Books

          in the Zoho Creator i have File Upload field get the file on submission of the form Get the File and upload to Zoho Books . how I get the file From zoho creator and upload to Zoho Books . using Api response = invokeUrl [ url: "https://www.zohoapis.com/creator/v2.1/data/hh/l130/report/All_Customer_Payments/"+input.ID
        • 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
        • Syntax for URLs in HTML Snippets

          What are some best practices for inserting a URL in an HTML snippet? I've looked at Zoho Help articles on navigation-based and functional-based URLs, but I'm still unclear on how to incorporate them in an HTML snippet. For example, 1. How do I link to
        • Rate Limiting in Zoho Flow (OpenAI API)

          Hi Everyone, We are facing some issues when using Zoho Flow as we have a deluge script running which is making external calls to OpenAI endpoint. Sometimes the response takes more than 30 seconds meaning the script will timeout. We want to implement a
        • Next Page