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,