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

        • Lookup field - Can I avoid using advanced search?

          I have a lookup field in my app that has surpassed 500,000 records, now basic search is disabled and I'm forced to use advanced search. That adds multiple steps to what used to be very simple. Before: Select field > Type last digits of product code and
        • Invalid Value Type Error Conditional Formatting

          Hello, I'd like to use conditional formatting on a table using Classic conditional formatting for Cell Value, but when I attempt to apply the formatting, I get the error "Invalid Value Type: Value must be of type number". The error is being produced because
        • Simplify Zoho API integration with Deluge’s invokeAPI task

          Hello all! Happy New Year! As we kick off 2025, we’re excited to share some of the latest updates to enhance your Deluge experience. While Deluge already offered robust API integration capabilities, we’ve taken it to the next level with the introduction
        • Automation #6 - Prevent Re-opening of Closed Tickets

          This is a monthly series where we pick some common use cases that have been either discussed or most asked about in our community and explain how they can be achieved using one of the automation capabilities in Zoho Desk. Typically when a customer submits
        • How create deal with label added using api

          Hi, I am creating automations in n8n for Zoho CRM. I want to create a new deal with a label added at the same time. However, I keep getting an error. Using the API, I can create a deal successfully, but when I try to add a label during the deal creation,
        • Reporting tags

          Hi, I suggest to improve the integration with Books, adding the faculty to especify a reporting tag from payment pages. Thanks!
        • Can I add Conditional merge tags on my Templates?

          Hi I was wondering if I can use Conditional Mail Merge tags inside my Email templates/Quotes etc within the CRM? In spanish and in our business we use gender and academic degree salutations , ie: Dr., Dra., Sr., Srta., so the beginning of an email / letter
        • SEO Support for Jobs

          I know Zoho recruit has some very basic metadata settings at the job board level which is not really helpful. We are wanting to utilise SEO and other Google features (like Google Jobs) which require the ability to add structured data to each job posting
        • Workdrive Oauth2 Token Isn't Refreshing

          I have set up oauth for a bunch of zoho apis and have never had a problem with oauth. With workdrive i am using the exact same template i usually use for the other zoho apps and it is not working. All requests will work for the first hour then stops so
        • Create deal from estimate

          Hello, I have integrated CRM and books. I created an estimate on CRM but I would like to allocate that estimate to a deal with the contact. How can I do this please?
        • Selecting Multiple Transactions

          Is there a way to select multiple transactions when in a bank account and batch categorize them?
        • Email Notification to WordPress Blog Subscribers

          You know when a new WordPress blog is published, your subscribers will be notified via email with a link to that blog? Jetpack does it but I'm hoping to get away from it or any other specialized WordPress plugin (like MailPoet), and instead, use a dedicated
        • Se detectó una actividad inusual para esta IP. Inténtelo de nuevo más tarde.

          Recibo el siguiente mensaje al intentar agregar una nueva cuenta de correo electronico a mi dominio @grupomgglobal.com Necesito una respuesta urgente a este asunto ya que he tenido varios inconvenientes con mi el servidor de correo. Si sigo asi creo que
        • Oops! Something went wrong. Try again later When trying to send email

          Hi, This error is appearing everytime i am trying to send an email. Oops! Something went wrong. Try again later Please help.
        • Stock Count - Extracting Data

          Hi, I really like the new stock counting functionality however I can't find any way to extract the stock count results. -The build in stock count report is limited and has no export option - There is no export options from within the stock count screens
        • Search Option not working

          My search option is not working properly. I type in what I'm searching for, and it says not results found. How to I get this issue resolved?
        • Missing users in CRM workflow notification and "share with zoho cliq"

          Hi, I'm creating a workflow that should send a notification to a Zoho Cliq user when a Lead with specific lead source enters the CRM. The problem is that not all users are showing up in the select menu, when I choose "Notify to Zoho Cliq - Users". As
        • Question about on User input workflows

          In my app I have a field for device IMEI which should trigger a check on an external API through an invokeUrl. But it seems the workflow will only run after the user has moved the focus away from the field by clicking somewhere else. However, if the user
        • Workaround for Backstage's non-compliant cookie banner

          Hi Does anyone has a workaround for the cookie banner Backstage uses when you publish an event? Currently there is no "Decline All Cookies" button, only "Accept All" and "Customise". Which means it is not compliant with data protection requirements, as
        • Creating a code for Task to event creation

          I am looking to automate an event creation to do the following: When a task is created for a user, create an event at 530PM simply called TASKS. This will serve as a reminder that we have at least one task that needs to be addressed. We miss the task
        • Creating smart filters manually

          Hi Team, One of my colleagues accidentally deleted the Notification folder in Zoho Mail. Now all the emails are directing to spam instead of inbox. Is there any way to create the smart filter manually?. With Regards, Logeswar V
        • Zoho mail stopped receiving emails

          My Zoho email addresses that are linked to a domain suddenly stopped receiving messages yesterday, even though I've been using Zoho mail without problems for 1,5 years. I receive this reply to test emails: "553 Relaying disallowed". Due to this, my SMTP
        • Connecting Zoho Inventory to ShipStation

          we are looking for someone to help connect via API shipStation with Zoho inventory. Any ideas? Thanks. Uri
        • Auto CC - Moving Departments

          We have Auto CC e-mail replies to your support mailbox enabled. We have two departments: Helpdesk (helpdesk@domain.com) Delivery (delivery@domain.com) If we create a Helpdesk ticket, and reply, replies are CC'd to helpdesk@domain.com (OK) We then move
        • Not getting copy of emails sent from Zoho CRM in my email sent box

          Where is the setting to make sure I receive a copy of an email I sent to a contact in the CRM in my email SENT folder?  (I use gmail) Thanks
        • Custom image for each contact using merge tag

          Hi, I'm wondering if it's possible to set up an email campaign to display a different image for each contact using a custom field for the image url. I tried inserting custom html: <img src='$[UD:APP_IMAGE_URL||]$'/> but the editor seemed to reject this and did not actually add anything to the email template. Has anyone got any ideas? cheers, Jeremy
        • CASE Module - email function

          HI there, I dont know if this has been asked or answered before as i couldnt find it on the forums. Issue: when a new case is raised, it goes under case tab and everything is captured. Then how do i send emails to the client who raised case with the details
        • Use of External Email Services

          Would like the ability to use an external SMTP service to send emails campaigns in Marketing Automation.  Services like SendGrid, Maligun Amazon SES, etc
        • Requiring Proxy

          We are trying to get support from a company that uses Zoho assist. When we download the helper it is questing that we put in a proxy. What info do we need for the proxy / or to not need a proxy? I have tried a hot spot and allowing the program through
        • Can I add social media icons / widgets to my email template in Zoho CRM?

          I know there are more features in Zoho Campaigns (vs Zoho CRM) when creating an email campaign/template. For instance you can easily add social media widgets. But is there a way to add social media widgets when creating an email template in Zoho CRM? I created a single image in Photoshop of the social media icons I want to include. But if I were to add them in my template using the "IMAGE" component, I will only be able to include one hyperlink (as it is a single image); I cannot hyperlink them individually.
        • Filter report using dynamic filter using function not working

          Hi - I am trying to dynamically filter a report as follows: when I save the filter it looks like this: However when I run the report it is not returning results as I expect. I have tested the function. If I copy and paste the output of the function and
        • All notes disappeared

          I've been using the notebook app for over five years on my phone without being logged into an account. A few days ago I opened the app and all my notes had disappeared. Since then I tried restarting my phone, updating the app and logging into my account,
        • Best email set up

          Hi! We are a non-profit and just recently gained Zoho as our email host. We have 10 email addresses available and 10 positions that need those email addresses. Every 3 years (or less) the people holding these positions change and the necessity comes when
        • I can't receive emails

          I can't receive emails but I can send them, there is nothing clear to do if this happens so that's why I'm asking for help
        • unable to verify mx configuration

          hey I have added mx configuration as per the instructions in the respective domain, yet I am unable to verify that.
        • Create custom rollup summary fields in Zoho CRM

          Hello everyone, In Zoho CRM, rollup summary fields have been essential tools for summarizing data across related records and enabling users to gain quick insights without having to jump across modules. Previously, only predefined summary functions were
        • How manage to hardware and software contracts.

          So I have been tasked with setting up on crm a way of managing our software and hardware contracts. with a filter switch, so if they are no longer on say a hardware contract but still on a software, we would like the history about the hardware contract
        • Zoho Payments integration

          What are you going to get Zoho Payments integrated with Zoho Forms? It's kind of embarrassing to have several payment options... but not your own, which has been out for quite a while.
        • 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
        • BIN Locations

          Hi, I’m new to Zoho inventory and unless Im missing something, I cannot find BIN locations anywhere in ‘items’? please tell me it’s there somewhere?!? Thanks
        • Next Page