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


    Access your files securely from anywhere

          Zoho Developer Community




                                    Zoho Desk Resources

                                    • Desk Community Learning Series


                                    • Digest


                                    • Functions


                                    • Meetups


                                    • Kbase


                                    • Resources


                                    • Glossary


                                    • Desk Marketplace


                                    • MVP Corner


                                    • Word of the Day



                                        Zoho Marketing Automation
                                                • 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


                                                Manage your brands on social media



                                                      Zoho TeamInbox Resources

                                                        Zoho DataPrep Resources



                                                          Zoho CRM Plus Resources

                                                            Zoho Books Resources


                                                              Zoho Subscriptions Resources

                                                                Zoho Projects Resources


                                                                  Zoho Sprints Resources


                                                                    Qntrl Resources


                                                                      Zoho Creator Resources



                                                                          Zoho Campaigns 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

                                                                                                  • Payroll In Canada

                                                                                                    Hi, When can we expect to have payroll in Canada with books 
                                                                                                  • Why can't we associate a contact to mulitple accounts?

                                                                                                    This simple feature has been for 14 years now... it's way past ridiculous. We don't want to add a multiple lookup field, we just want to add a second account to our contact. This way i'll go on Jonh Doe and see in the account field : Company 1 and Company
                                                                                                  • Easy way to delete attachments

                                                                                                    I've reached my data limit and would like to run a view/report, and mass delete attachments. Is there an easy, fast way to do this? Moderation Update: Post Summary: There are two features the post discusses a) Easy way to remove Email attachments Will
                                                                                                  • Calendar Bookings in Recruit

                                                                                                    Hi there, We have recently started using Zoho recruit and although it has some great functionality there are a few gaps that are causing real headaches. One of those being how interviews are scheduled. The majority of our hiring managers are field based
                                                                                                  • Multiple Vendor SKUs

                                                                                                    One of the big concerns we have with ZOHO Inventory is lack of Vendor Skus like many other inventory software packages offer. Being able to have multiple vendor skus for the same product would be HUGE! It would populate the appropriate vendor Sku for
                                                                                                  • How to Use Branch-Specific Templates for Invoices Created via Zoho Books invoice API?

                                                                                                    I am using the Zoho Books Invoice API and I am sending the branch_id when creating an invoice. The invoice is being generated, but it is using the default template rather than the template that corresponds to the branch I specified. In Zoho Books, when
                                                                                                  • Automatic Department and Employee Sync Between Zoho One and Zoho People

                                                                                                    Dear Zoho Support, I'm writing to propose a valuable feature request that would streamline data management and improve user experience within the Zoho ecosystem: automatic synchronization between departments and employees in Zoho One and Zoho People.
                                                                                                  • Delete Unactive Users form Directory

                                                                                                    Hi, how to delete all unactive users ?
                                                                                                  • Manual Journal entry problem

                                                                                                    Hi, all my manual Journal entries are not reflected in my general ledger. i have check to see if the entry were done correctly and everything is fine. Please help me
                                                                                                  • Changing Related Modules in a Report

                                                                                                    Once a report is created, is it possible to add Related Modules? David Shalev | Chief Revenue Officer | 800 558 9130 davids@splitit.com | www.Splitit.com
                                                                                                  • Is there a way to limit/turn off unlimited Version History?

                                                                                                    We save CAD files in our Zoho WorkDrive and while the files aren't very big themselves, whenever someone hits the save button in the CAD program it uploads another version of the file to the WorkDrive. This means files that are only a few MBs in size can actually be taking up 10s of GB in our WorkDrive if someone is saving frequently. Is there a way to limit the number of versions WorkDrive stores to save WorkDrive space?
                                                                                                  • ZOHO One Webinar Functionality

                                                                                                    I am currently trialling ZOHO Projects and have also been looking into over a dozen different Webinar solutions from various vendors. I understand that ZOHO Webinars is a stand alone tool. But that ZOHO Meetings also offers webinar functionality. The
                                                                                                  • Avoid None option in List Custom Fields

                                                                                                    Does anybody know a way to avoid -- None --  option to be displayed in a List Custom Field?  - With Mandatory option selected, you can prevent from saving if user select --None-- value. - With Default value selected, a different value than --None-- is
                                                                                                  • How do I modify the the incoming/current call popup? I can modify other call pages but not that one.

                                                                                                    I want to modify the incoming and active call popup on the crm to include customer relevant information, such as purchase history or length of relationship. Under modules and fields, I don't seem to see active call as a choice to modify, only the main
                                                                                                  • JavaScript or iframe embed with transparent background

                                                                                                    If I have a form with transparent Wallpaper, it appear great on my website by using my default background. However, using Zoho Forms SAVE button, the user is directed to Zoho Forms managed page and a blank background. Alternatively, I can include a Wallpaper
                                                                                                  • Emails and Kanban for Portals

                                                                                                    There was talk portals would have emails and email templates, and kanban view. Is there any release date for this? Portals has been so good for offering a simple crm option. It just needs a couple of small things.
                                                                                                  • Custom sorting Axis in a Heatmap report

                                                                                                    I have a heatmap and want to sort the order of the axis in a custom priority order - is this possible ? So I want the priority to be "New, Urgent, High, Medium, Low, Not Set, Unknown" Can I set this manually ?
                                                                                                  • ZOHO BackStage

                                                                                                    How to get list of events, using ZOHO BackStage APIs. Is it possible OR not?
                                                                                                  • Which attribute in Zoho books invoice api represent branch attached to the invoice?

                                                                                                    Hi Zoho Team, We have done the integration with Zoho Books API. While fetching data from Invoice API we want to get branch value attached to the invoice. We could not figure out which field in "Get an Invoice" api represents branch value attribute. Thanks
                                                                                                  • The 3.1 biggest problems with Kiosk right now

                                                                                                    I can see a lot of promise in Kiosk, but it currently has limited functionality that makes it a bit of an ugly duckling. It's great at some things, but woeful at others, meaning people must rely on multiple tools within CRM for their business processes.
                                                                                                  • Zoho People down

                                                                                                    Zoho People (EU) appears to be inaccessible this morning. Have gotten through log-in and MFA but have been on the "Please wait while we work our charm..." page for several minutes now. A colleague has tried to access it via the One dashboard and experienced
                                                                                                  • Zoho Analytics Pivot Table - How to compare month vs last year same month

                                                                                                    Hi, I had created a pivot table with setup as below: Column: - Delivery Date Row: - Customer Group Data as column - Total amount (sum > normal) (show data of the month) - Total amount (sum > % difference from previous value) (compare between this month
                                                                                                  • Adding Bluesky channel

                                                                                                    Hello, Is Bluesky (AT protocol) soon added on Social ? Bluesky is being developped and is now open to anyone (no more invitation) Thank you
                                                                                                  • No Zoho Support on the weekends or after hours?

                                                                                                    Zoho Support is only available Monday - Friday during normal business hours. My business (as does many businesses) operates 7-days a week. Last Saturday, I had a client come in and in order for me to help her, I needed to log into CRM but to my surprise,
                                                                                                  • How do I overcome the 800 transaction rule limit?

                                                                                                    I just received a message: "You have reached the maximum rule limit of 800." I searched the documentation, and I didn't find anything about the cap or limit. I asked the ZOHO Books team if there is a way to increase the limit. Their answer was: "Please
                                                                                                  • Search functionality in Vault is very poor

                                                                                                    Hi Zoho Team Please... the search functionality is absolutely vital in Vault, particularly when it's being used by a team. It's just a fact of life that everybody has their own way of naming something, so using exact match on the Password name is horribly
                                                                                                  • 👋 Pessoal, como está sendo sua experiência com ferramentas de produtividade?

                                                                                                    Percebo que muitos usuários de soluções como Google Workspace e Microsoft 365 acabam enfrentando desafios quando pensam em migrar de plataforma, especialmente por conta de multas contratuais ou até pela complexidade em adaptar as equipes. Além disso,
                                                                                                  • Quais são os maiores desafios que você enfrenta ao implementar o Zoho CRM?

                                                                                                    Olá, pessoal da comunidade Zoho Brasil! Sou parceiro autorizado da Zoho e, ao longo do tempo, tenho notado que cada implementação de CRM traz desafios únicos, dependendo do segmento de negócio, das metas da empresa e até da familiaridade da equipe com
                                                                                                  • Parent - Child Ticket Twins

                                                                                                    I think i maybe losing my mind. Are these two completely separate parent-child ticketing functions? I think I remember adding a plugin years ago and I think I also remember seeing something about parent-child ticketing in a release notes being added.
                                                                                                  • Can the Comments from approval process be posted onto a module field and not on the timeline?

                                                                                                    I have set up approval process for the quotations module and would like for the approval comments to be posted onto a module field as opposed to me searching for the particular quote and going to the timeline section. This would also help keep tabs on
                                                                                                  • auto reply shopify order details in zoho desk based on order number in subject using deluge script custom function

                                                                                                    auto reply shopify order details in zoho desk based on order number in subject using deluge script custom function
                                                                                                  • Is there an ability to keep the status field unlocked while having an active blueprint?

                                                                                                    Hi. Is there an ability to keep the status field unlocked while having an active blueprint? Here is the case. We have a transition let's say "Ask to the customer" When we do this transition the Status is switch to "waiting for customer" But if for exemple
                                                                                                  • Rename Category and Sub Category fields

                                                                                                    Is it possible to rename the field labels for Category and Sub Category - if so can this be done at layout or department level ?
                                                                                                  • Thoughts on users being able to create Zoho accounts?

                                                                                                    For anyone who's used Zoho for a while, I'm sure you've come up against an issue where you create an account for a user, and they go ahead and sign up for a new one accidentally. Then, only they can delete the account, as it exists outside the organisation.
                                                                                                  • Deluge should permit a connection to be set with a variable

                                                                                                    Hello, Being one who occasionally likes to post code in the forums, I try to make anything that the end user needs to define be present at the very top of the script so that those who want to implement the script won't have to hunt through lines of code,
                                                                                                  • Bcc option in "new ticket --> send as email" disappeared

                                                                                                    Is it just me or did the bcc option disappear in the "send as email" option of new tickets in desk? This is very inconvenient.
                                                                                                  • Automated Intercompany Transaction

                                                                                                    Hello team - expecting a support today. I have some good experience with Zoho products as an accountant and trying to introduce the Zoho to my newly joined company. So far it's going on good except below question. I'm currently maintaining multiple companies
                                                                                                  • change subscription within customer portal

                                                                                                    Would be great for the customer to be able to change their own subscription (or restart existing one) within the customer portal. Also, would like to be able to have early termination fee on subscriptions if canceled early.
                                                                                                  • I'm getting an "Invalid_scope" error, even though I used an access token generated with the correct scope.

                                                                                                    I'm getting an "Invalid_scope" error, even though I used an access token generated with the correct scope. Here’s what I did in Postman: Generated the code to create an access token using the following URL: https://accounts.zoho.eu/oauth/v2/auth?scope=ZohoCampaigns.contact.UPDATE&client_id=<client_id>&response_type=code&access_type=offline&redirect_uri=https://1882-2-26-193-161.ngrok-free.app
                                                                                                  • How to Automate Form Creation and Workflow Setup in Zoho Creator?

                                                                                                    Does anyone have ideas on how to create a form workflow that can perform the following functions automatically when a new submission is received for the existing form? Create a new form and report Create a new page Generate a new form workflow for the
                                                                                                  • Next Page