Function for Emails tranfer from Lead to Deal

Function for Emails tranfer from Lead to Deal

Hi

Due to the fact that my Deals conversion needs to be done in 2 ways - depending on the fact if those records already exists or not - resources in fields are different.
I am making function control conversation for Leads but I have problem with transferring email communication to Deal.
Here's a detailed explanation of the code and its functionality:

/**
 * Function: LeadAktualizacjaKontaktFirmaPrzeniesienieDzialanNaDealaV1
 * Purpose: Converts a Lead to a Deal and transfers all related emails to the new Deal
 * 
 * Main operations:
 * 1. Creates a new Deal from Lead data
 * 2. Finds all emails related to the Lead
 * 3. Updates email associations to point to the new Deal
 * 
 * @param leadId - The ID of the Lead to be converted
 */
void automation.LeadAktualizacjaKontaktFirmaPrzeniesienieDzialanNaDealaV1(String leadId)
{
    try 
    {
        // Deklaracja wszystkich zmiennych
        leadData = null;
        kontakt = null;
        firma = null;
        dealName = null;
        dealOwner = null;
        leadOwner = null;
        dealMap = Map();
        newDeal = null;
        dealId = null;
        emailList = null;
        emailIdVal = null;
        updateMap = null;
        updateResult = null;
        eml = null;
        
        // Pobranie danych leada
        leadData = zoho.crm.getRecordById("Leads",leadId);
        if(leadData.isEmpty())
        {
            info "BŁĄD: Lead o ID " + leadId + " nie został znaleziony.";
            return;
        }
        
        kontakt = leadData.get("Kontakt_w_bazie");
        firma = leadData.get("Firma_w_bazie");
        dealName = leadData.get("Pods_Nazwa_Firmy");
        dealOwner = leadData.get("Dla_Salesa");
        leadOwner = leadData.get("Owner");
        
        dealMap.put("Deal_Name",dealName);
        dealMap.put("Account_Name",firma.get("id"));
        dealMap.put("Contact_Name",kontakt.get("id"));
        dealMap.put("Stage","Spotkania");
        dealMap.put("Pipeline","Standard");
        dealMap.put("Owner",dealOwner);
        dealMap.put("Created_By",leadOwner);
        dealMap.put("Lead_provided_by",leadOwner);
        
        if(leadData.get("Lead_Source") != null)
        {
            dealMap.put("Lead_Source",leadData.get("Lead_Source"));
        }
        if(leadData.get("TTP_rezultat") != null)
        {
            dealMap.put("TTP_result",leadData.get("TTP_rezultat"));
        }
        if(leadData.get("Istniejaca_centrala") != null)
        {
            dealMap.put("Centrala",leadData.get("Istniejaca_centrala"));
        }
        if(leadData.get("E_hardware") != null)
        {
            dealMap.put("Wartosc_hardware",leadData.get("E_hardware"));
        }
        
        info "========= START TWORZENIA DEALA I PRZENOSZENIA MAILI =========";
        info "Rozpoczęto dla leada: " + leadId;
        info "Tworzę Deal z danymi: " + dealMap.toString();
        newDeal = zoho.crm.createRecord("Deals",dealMap);
        if(newDeal.get("id") == null)
        {
            info "BŁĄD: Nie udało się stworzyć Deala";
            return;
        }
        dealId = newDeal.get("id");
        info "✓ Utworzony Deal ID: " + dealId;
        
        info "--- Przenoszenie emaili ---";
        emailList = zoho.crm.searchRecords("Emails","(Lead_Id:equals:" + leadId + ")");
        if(emailList != null && !emailList.isEmpty())
        {
            info "Debug: Liczba znalezionych emaili: " + emailList.size();
            
            for each eml in emailList
            {
                try
                {
                    if(eml != null)
                    {
                        info "Debug: Struktura emaila: " + eml.toString();
                        
                        // Próbujemy pobrać ID bezpośrednio
                        emailIdVal = eml.get("id");
                        
                        if(emailIdVal != null)
                        {
                            updateMap = Map();
                            updateMap.put("What_Id",dealId);
                            updateMap.put("$se_module","Deals");
                            
                            info "Debug: Próba aktualizacji emaila o ID: " + emailIdVal;
                            updateResult = zoho.crm.updateRecord("Emails",emailIdVal,updateMap);
                            
                            if(updateResult != null && updateResult.get("id") != null)
                            {
                                info "✓ Email " + emailIdVal + " przeniesiony";
                            }
                            else
                            {
                                info "Błąd: Nie udało się zaktualizować emaila " + emailIdVal;
                            }
                        }
                        else
                        {
                            info "Błąd: Nie znaleziono ID dla emaila";
                        }
                    }
                }
                catch(e)
                {
                    info "BŁĄD przenoszenia emaila: " + e.toString();
                    info "Debug: Szczegóły emaila powodującego błąd: " + eml.toString();
                }
            }
        }
        else
        {
            info "Nie znaleziono żadnych emaili do przeniesienia";
        }
        
        info "========= ZAKOŃCZONO TWORZENIE DEALA I PRZENOSZENIE MAILI =========";
    }
    catch (ex)
    {
        info "Wystąpił błąd główny: " + ex.toString();
    }
}

Here's what each part of the code does:

1. **Lead Data Retrieval and Deal Creation**:
   - Retrieves Lead data using `zoho.crm.getRecordById("Leads", leadId)`
   - Extracts important fields: Contact, Company, Deal Name, Deal Owner, etc.
   - Creates a Deal Map with required fields:
     ```javascript
     dealMap.put("Deal_Name", dealName);
     dealMap.put("Account_Name", firma.get("id"));
     dealMap.put("Contact_Name", kontakt.get("id"));
     dealMap.put("Stage", "Spotkania");
     dealMap.put("Pipeline", "Standard");
     // ... other fields
     ```
   - Creates a new Deal record using `zoho.crm.createRecord("Deals", dealMap)`

2. **Email Migration**:
   - Searches for related emails using `searchRecords`:
     ```javascript
     emailList = zoho.crm.searchRecords("Emails", "(Lead_Id:equals:" + leadId + ")");
     ```
   - This search should return all emails associated with the Lead

3. **Email Association Update**:
   - For each found email, attempts to:
     - Get the email's ID
     - Create an update map with new Deal association:
       ```javascript
       updateMap.put("What_Id", dealId);
       updateMap.put("$se_module", "Deals");
       ```
     - Update the email record to point to the new Deal using `zoho.crm.updateRecord("Emails", emailIdVal, updateMap)`

**Current Issues**:
1. The email search returns records (4 emails found), but we're having trouble accessing the email ID field
2. The update operation fails due to data type issues with the email ID

**Requirements for Zoho Support**:
1. Need to confirm the correct field name for email ID in the search results
2. Need guidance on the correct way to update email associations when converting from Lead to Deal
3. Need to understand if there are any specific data type requirements for the email ID when updating records

**Test Results**:
========= START DEAL CREATION AND EMAIL TRANSFER =========
Started for lead: 751364000004048409
Creating Deal with data: {"Deal_Name":"Account Name","Account_Name":"751364000002639001","Contact_Name":"751364000004048395","Stage":"Meetings","Pipeline":"Standard","Owner":{"name":"Artur Sznek","id":"751364000000551001"},"Created_By":{"name":"Name","id":"751364000000416001","email":"k******.*****@*****.com"},"Lead_provided_by":{"name":"Name","id":"751364000000416001","email":"k******.*****@*****.com"},"TTP_result":232,"Central":"234","Hardware_value":72364}
✓ Created Deal ID: 751364000004185020
--- Email Transfer ---
Debug: Number of emails found: 4
ERROR transferring email: Error at line : 66
ERROR transferring email: Error at line : 69
========= DEAL CREATION AND EMAIL TRANSFER COMPLETED =========
Could you please help with:
1. The correct way to access email IDs from search results
2. The proper data type for email IDs when updating records
3. Any specific requirements for updating email associations in Zoho CRM

The code is functional for Deal creation but needs assistance with the email transfer portion.


Thank you in advance for help
kochnik


    • 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
    • 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,
    • Function-2: Round-Robin assignment of records

      Welcome back folks! Last week, we saw how to update sales commission in quotes using a custom function. This week, let's see an interesting use case asked by many of you - auto-assignment records by round-robin method. Business scenario: Right now, the solution allows you to auto-assign leads from web form and imported lists. Let us look at a need where you want to auto-assign leads from in-bound calls in a round-robin method, across modules. Prerequisite: You must create a permanent record in the
    • Recent Topics

    • Chat issues

      I am having a couple problems with the zoho chat feature. When I use Chat from the App bar, not everyone is getting messages (these are to different accounts, Yahoo & Gmail). I did finally get the Users to show up correctly. However, when in an active chat with someone, I only get one sound notification. No other notifications, pop up or otherwise, come through to alert if another message was sent. Also, the bottom Chat bar that shows Active chats while I am in email does not show any online contacts
    • Problem with multiple pages record template

      Hi, I have a record template with multiple pages. When I print, it has gaps between pages. How can i fix it?
    • Field Update: can't find a custom multi-line text field in the options list

      I want to update a custom text field (large size multi-line: 32000 characters) that I have added in the Accounts module using this functionality https://help.zoho.com/portal/en/kb/crm/automate-business-processes/actions/articles/field-updates , but I
    • Ask the experts - A live Q & A discussion on Zoho Recruit

      We are delighted to come back with another edition of Ask the Experts community series. This edition, we'll be focusing on everything about Zoho Recruit. The topics will focus on the features that are used/asked by the majority of users and also based
    • No Sales Returns on SO's with Dropped Shipped items + Inventory Items

      We have encountered an issue in Zoho related to sales orders that include both dropshipped items and inventory items. Specifically, it is currently not possible to create sales returns for the company’s own inventory items from these sales orders. This
    • Task Due dates and Reminder Date & Time

      I like to have a reminder on many tasks in Zoho Recruit. I find the process cumbersome in that each task requires the following: 1. click and select due date 2. Click the reminder box 3. Click on (Reminder) Start Date 4. Click on (Reminder )Time If one
    • Bug - OTP (email) and No Duplicates

      Scenario: Form with an email field, Validation: "No Duplicates" (because I want to ensure 1 entry per email). Embedded form into website (JS option). Enabled email based OTP. 1st test (via my website) - entered my email address - sent OTP - entered pin,
    • Zoho One Datensicherung möglich

      Gibt es eine Zoho One Datensicherung über alle Apps mit eindeutigen Datensatz-Id´s eines Kontaktes in allen Apps und mit allen Bildern (insbesondere Artikel-Bilder)? Wir haben festgestellt, dass die Zoho Books Datensicherung keine Bilder sichert. Und
    • Note not being pulled for other modules in email template

      Hi there, Currently i am creating an email template that is able to pull the data from notes field in estimate module and email it to procurement team where they will be able to receive the email with the contents of the note, i am unable to replicate
    • Pop Up

      Hello, I want to automatically display the information of the attached data in the product module in the related list section of my data in the lead module when the current time matches the "Call Time" field of my data in the leads module. How can I achieve
    • New feature alert: Witness signing is now available in Zoho Sign

      Hello! Getting documents signed with confidence in Zoho Sign just got a major boost! We're delighted to introduce witness signing, where other individuals or entities can be designated as witnesses to observe the signing process and add their signatures
    • How to report and analyze a multi-select field entries distinctly ?

      As many of CRM users I have many multi-select fields that allows me to choose more than one chose in one cell for a specific filed Like: Field A - A;BC - A;C -B;C But when reporting the field it will handle each cell as a "String" not multiple entries
    • Get the capability to convert documents to different formats

      Hello users, In this article, we'll be exploring the Conversion API in Zoho Office Integrator to understand how it can be used to convert documents to different formats right from your web app. Before we get to the details of the Conversion API, here's
    • Is the Contacts sync between Campaigns and CRM bi-directional?

      Is the Contacts sync between Campaigns and CRM bi-directional?
    • Guidance on Making Zoho Desk Connections Available for All Data Centers

      Hi Team, I’m currently developing an application using Zoho Desk connections to manage OAuth for my third-party products. Could you please advise on the steps required to make it available across all data centers? Looking forward to your thoughts on
    • Issues with certain CRM, Desk & webhook blocks in Guided Conversations

      Good day I have been attempting to add a block on our guided conversations, which give our customers relavent information based on their queries. The issue is that when I attempt to use a block that fetches data I get the following error popup: Cannot
    • Unable to load your extension. Please check your plugin-manifest or Resources.json.

      Hi Team, I am using the config module with multiple fields of different types, such as checkboxes and picklists. However, I am encountering the following issues: Error Message: When loading the extension, I get the error: "Unable to load your extension.
    • Use Zoho Creator as a source for merge templates in Zoho Writer

      Hello all! We're excited to share that we've enhanced Zoho Creator's integration with Zoho Writer to make this combination even more powerful. You can now use Zoho Creator as a data source for mail merge templates in Zoho Writer. Making more data from
    • Analytics Module: Can you move items from one dashboard to another?

      Is there a way to move items from one dashboard to another? I want to rearrange my dashboard now that I know what i'm doing but i don't want to remake my various widgets? Edit: Hey Zoho, This would be a good feature: to be able to move/copy widgets to
    • How can I insert and update field data of a sub-form without adding data into the main form’s mandatory fields.

      1. I have a main form that contains a sub-form. I need to update the data of the sub-form from a function, but I am unable to do so. How can I achieve this in Zoho Creator? 2. How can I insert data into a sub-form without inserting data into the mandatory
    • Can't delete/hide related lists

      Hi, Maybe I'm missing something, but I can't seem to find where I delete or hide related lists in a module. When I go to a record and click the little arrow on the right next to the related list, I only get the option to select what fields in that list
    • Make Widgets Clickable or Copiable

      Hi, I created a KPI Widget in Zoho Analytics whose content I would like the users that see my dashboard could copy or click and be redirected elsewhere. Yes, I'm aware I can create a Text Box for that instead of a Widget, but the problem is that the link
    • Custom API - Need to create a string return value, not only MAP

      @Support: When creating a Custom API it only allows a return from a function of MAP type. The service I'm using requires a string return, how can this be achieved?
    • I trying to connect our PM tool but API shows failure

      Hi All, in ZOHO CRM when an enquiry stage is moved to WON then I have created a rule to trigger POST URL to thrid party AP and then create a function for mapping with below code void automation.kytesfunctions(String enquiryId) { // Fetch enquiry details
    • Automate data upload process like reports

      I'll start with the end in mind.  I want to basically keep certain creator tables updated with data that are in a sql database/tables in our office (employees, active jobs, employee positions) so I can reference that data and not have to duplicate it by hand every time someone adds a new job or employee in the office desktop software.  Here are some thoughts I had about how to do this, but am unsure as to whether any of them are actually possible and how to go about it from there: Is there any way
    • Automatically assign Contacts to Account owners

      Hi, I have a finite number of accounts set up in the CRM, and each new contact that comes in is automatically assigned to an Account according to a rule I set up. I want the Contact owner in the Contacts module to be assigned to the relevant Account owner.
    • Address Autofill

      Hi I'm having issues with the address autofill tutorial (https://zurl.co/rGXQ). I have followed each step in the tutorial, but when i paste the code into a workflow/function, i'm getting the following error code: Improper code format Correct format :
    • Sync custom module ID to Lead module

      Hello, I am trying to sync Contract ID (custom module) from Deal module. I have an existing function that whenever a contract is created, it will automatically creating deals based on the frequency of the contract. Now i am having problem to show the
    • In Kiosk, please support "File upload field" in the "Field Update" action

      Hello. Supporting "File upload field" in the "Field Update" actions would be a great addition to Kiosk Studio. I would appreciate it if you could evaluate it. Saludos,
    • can I link a contacts to multiple accounts

      can I link a contacts to multiple accounts
    • Change Last Name to not required in Leads

      I would like to upload 500 target companies as leads but I don't yet have contact people for them. Can you enable the option for me to turn this requirement off to need a Second Name? Moderation update (10-Jun-23): As we explore potential solutions for
    • For security reasons your account has been blocked as you have exceeded the maximum number of requests per minute that can originate from one account.

      Hello Zoho Even if we open 10-15 windows in still we are getting our accounts locked with error " For security reasons your account has been blocked as you have exceeded the maximum number of requests per minute that can originate from one account. "
    • Zoho Creator - Zoho Analytics

      I am facing an issue in Zoho Analytics where I am still seeing deleted data from the Zoho Creator form I created. Could you please look into this and let me know what needs to be done?
    • The Social Wall: November 2024

      Hey everyone, As we move into December, we're excited to share all the updates that went live in Social during November. View, monitor, and respond to your WhatsApp and Telegram messages from Inbox Take your communication a step further by integrating
    • Launching CPQ for Zoho CRM! An in-built solution for bespoke quote management

      Hello everyone, We are thrilled to announce the public release of CPQ (Configure, Price, Quote) for Zoho CRM, which is a fundamental block in sales management. NOTE: CPQ was a public early access feature from March 2023 — January 2024. Since February
    • Add an action to set agent as a member of a team in zoho desk

      Hi, Please add an action to zoho flow to set agent as a member of a team in zoho desk (add to a team or remove from a team). Regards, Ram
    • Power of Automation :: Automatically set the dependency between Parent task and the respective sub tasks

      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 complex tasks and
    • Registration in community

      Namaste I am from Shimla, But there is no option selection of shimla.
    • Number of Workflow runs

      Is there a way in Zoho desk to see statistics regarding workflows, rules and other automation objects? Would be nice for several reasons: You could ensure that your workflows are actually running. You could determine which ones weren't being used so you
    • Spell Check default language

      Hello All, Is it possible to set the Spell Check default language? I can't find it in the settings. Thanks a lot! Levente
    • Next Page