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


    Zoho Campaigns Resources

      Zoho Desk Resources

      • Desk Community Learning Series


      • Digest


      • Functions


      • Meetups


      • Kbase


      • Resources


      • Glossary


      • Desk Marketplace


      • MVP Corner


      • Word of the Day


        • 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

        Zoho CRM Plus Resources

          Zoho Books Resources


            Zoho Subscriptions Resources

              Zoho Projects Resources


                Zoho Sprints Resources


                  Zoho Orchestly Resources


                    Zoho Creator Resources


                      Zoho WorkDrive Resources



                        Zoho CRM Resources

                        • CRM Community Learning Series

                          CRM Community Learning Series


                        • Tips

                          Tips

                        • Functions

                          Functions

                        • Meetups

                          Meetups

                        • Kbase

                          Kbase

                        • Resources

                          Resources

                        • Digest

                          Digest

                        • CRM Marketplace

                          CRM Marketplace

                        • MVP Corner

                          MVP Corner




                          Zoho Writer Writer

                          Get Started. Write Away!

                          Writer is a powerful online word processor, designed for collaborative work.

                            Zoho CRM コンテンツ






                              ご検討中の方

                                • Recent Topics

                                • Zoho email folders gone

                                  Hi, All my email folders are gone, i cant found any email, except sent. Also before folder rulesas was changed and i didnt fixed them, could you please check it?
                                • Pause/Resume Subscrtiption API

                                  I don't see the option to Pause/Resume a subscription using the API, is it in the pipeline?
                                • Update Department on Ticket (with applied Blueprint)

                                  Hello, Is it possible to update the Department of a ticket which is dictated by a blueprint, e.g. I would like to change departments at different states in the Blueprint. I do not see this is an option in workflow rules or blueprint transition actions,
                                • ERROR_CODE :554, ERROR_CODE :rejected due to spam

                                  Please verify bounce message: This message was created automatically by mail delivery software. A message that you sent could not be delivered to one or more of its recipients. This is a permanent error. xxx@thalesesec.com Error, ERROR_CODE :554, ERROR_CODE
                                • Can't verify domain with AWS Route53

                                  I have a domain successfully transferred to AWS Route53 from NameCheap. When I try to CNAME or TXT Records as suggested, they are added in AWS console however zohomail does not verify them. For the TXT record zohomail says the value is wrong, whereas
                                • Sent emails not going and showing "Processing"

                                  Hello Team, Could you please assist with sent emails showing "processing" and not actually going through? Many thanks and regards, Cycology
                                • LinkedIn verification link and otp not receiving

                                  For the last 2 to 3 weeks I'm trying to verify my LinkedIn account to access my company's LinkedIn page, Linkedin is sending verification links and codes to this email address but I have not received any codes or links. Please help me here. Looking forward
                                • Admin Control for Default Email Templates in Zoho Desk

                                  Hi Zoho Desk Team, We would like to request a feature enhancement related to default email templates. Currently, agents can select and set their own default email templates when replying to tickets. However, we believe this setting should be managed centrally
                                • Unlocking New Horizons: A Year in Review

                                  As we bid farewell to 2024, let's celebrate and revisit the key highlights of the year. From adding a new edition to cross-platform enhancements, here’s a roundup of all the feature updates designed to simplify accounting, optimize financial management,
                                • Zoho desk desktop application

                                  does zoho desk has a destop applicaion?
                                • send file to ftp or another external service

                                  i'v created a zoho creator application for take a picture and rename it by phone. Now i need to send Each renamed pictures to my ftp or to specific folder on google drive...then, delete it from creator. (every picture recived it will processed by another program and stored on my Erp) HOW CAN I DO ??
                                • Error 403: Forbidden When Updating Email Signature via API

                                  Hi Zoho Desk team, First, congratulations again on the excellent Zoho API. But, I’m encountering an issue while attempting to update an email signature via the API. Whenever I make a request to update the signature, the response returns an HTTP 403 Forbidden
                                • Has anyone built a ticket export that allows Help Center users to export the tickets shown in the My Area list they are looking at?

                                  Hi, We are moving to Zoho Desk soon. Our current support system displays an option in our help center allowing customers to export their Open, Closed, or all tickets based on which list they are looking at. We need to offer the same in Zoho Desk help
                                • Mass pdfs into OCR field

                                  I am working on a Creator app that my org will use internally. Is there any way to mass upload pfs through a form with an OCR file upload field? Is Creator capable of this, or would I need to use Catalyst?
                                • How to upload a file to form file upload field from deluge script.

                                  Hi guys, I need to store API response into Form File upload field . I'm not getting any errors but PDF file is not assigned to file upload field. You can check possibilities using below details: Method: POST URL: https://v2.convertapi.com/convert/web/to/pdf?Secret=<<SecretKey>>&Token=<<APIKey>>&Url=https://www.google.com You need to generate secretKey and APIKey by Login to https://www.convertapi.com/a/su Response: { "ConversionCost": 4, "Files": { "FileName": "www_google_com.pdf", "FileSize": 68342,
                                • Export view via deluge.

                                  Hi, Is it possible to export a view (as a spreadsheet) via deluge? I would like to be able to export a view as a spreadsheet when a user clicks a button. Thanks     
                                • Subform Time field showing as null in script.

                                  Good Afternoon everyone. I am trying to take the information from my subform and populate it into a multiline field in the CRM. The code below works with no errors. The problem is, it shows that the Open and Close (Time fields) are null. But they are
                                • Zoho Payroll's Year in Review 2024

                                  As we roll into 2025, we'd like to pay tribute to all the milestones we hit in 2024! From releasing out new features that streamlined your workflows to updates that made payroll management smoother, we’ve had a prolific year—all while keeping you, our
                                • Is there a way to sort report on record template by a specific field like date field

                                  Hi, Is it possible to sort the report on the record template by the date field and not the default Added Time. Please check the example bellow: The records are sorting by the added time I wand to change that by the date field,
                                • Shared subfolders

                                  Am I right in thinking that there is no Zoho email application that allows me to create a shared inbox and then add additional folders/subfolders under that inbox? If so, this is really quite incredible and probably a deal breaker for us to start using
                                • Update Multi select field values to another form table as individual record

                                  Hi, I am new to coding and do basics within deluge. I need help with the deluge script to meet the following requirement. Form Student Attendance The fields are : Attendance Date Course (Lookup to Course Form) Class (Lookup to Class Form) Students (Multi
                                • Shared Mailbox - Mark as read for all users

                                  Hi all, Maybe someone can help me out. At the moment we have a shared mailbox without streams. When a users reads an mail or marks it as read other users will not see this. How can we resolve this? We now archive the mails when read and followed up. However
                                • Allocate emails to user in a shared mailbox

                                  Hi, This might be obvious, but I cannot find the answer. I have 3 shared mailboxes so any team member can see the emails. Is there a way of allocating a specific email to a user so that it is their responsibility to deal with it? Thanks in advance.
                                • How to view shared mailbox in Outlook

                                  How to view shared mailbox in Outlook or in another software
                                • Search mails in shared mailbox

                                  Hi everyone, is there a way to search mails in shared mailbox's? Search in streams or mail doesn't return anything from mails in shared mailboxes. Thanks! Rafal
                                • Customising the approval email

                                  Is there anyway to customise the Approval email or to add further fields as the default looks so basic and unlike any of the other email notifications from Desk. My users just thought it was spam.
                                • Pushing GCLID info from Gravity Forms to ZohoCRM

                                  We are switching to Gravity Forms from Zoho Forms and I cannot find any good info on how to make sure my GCLID tracking info is pushed through to the CRM through my new forms. There was an article in the documentation about placing something within the
                                • Issue Configuring SSO Integration with Cognito in Zoho Help Center

                                  Dear Zoho Support Team, We have been working on configuring SSO integration for our Zoho Help Center using Amazon Cognito. While the setup appears to be completed successfully, we are encountering an issue when attempting to access the Help Center. The
                                • Need manual aggregate column pathing help

                                  See linked video here: https://workdrive.zohoexternal.com/external/a5bef0f0889c18a02f722e59399979c604ce0660a1caf50b5fdc61d92166b3e7
                                • Merging contacts does fail because of help center membership

                                  I'm trying to merge two contact records (they are the same contact) where one of them is a member on the help center. The system warns me about this situation and then I de-activate this contact as an "End User" for the help center. Right now the system
                                • Duplicate Contacts - how to get merge or delete

                                  I have noticed that our list of contacts in Zoho Desk duplicates contacts periodically.  I have yet to identify when or why.  How do I merge or delete them?  I see there is a "Deduplicate" but I am unable to find anything that explains this feature.
                                • Admin Access to Direct Messages in Zoho Cliq

                                  Hi Zoho Cliq Team, We would like to request a feature enhancement to enable admin access to one-on-one conversations (direct messages) conducted through Zoho Cliq. Use Case: As administrators, there are situations where it becomes essential to access
                                • "Mark as Spam" not working as expected

                                  Dear support, in the below scenario, clicking on "Mark as spam" identifies only the first of the checked emails as spam, removes that email from the visible list and leaves the rest of the list still visible & unchecked. I've tried check-marking them
                                • Massive price increase for user licenses of Zoho Portal

                                  This actually a complaint about this announcement: https://help.zoho.com/portal/en/community/topic/free-user-licenses-across-all-portal-user-types You present this as an enhancement. And, yes, while reading the main part, I'd agree that (for smaller companies),
                                • Elevating Email Security on Zoho Desk: DKIM Now Mandatory

                                  Hello Zoho Desk Users! It has been a wonderful journey with you on Zoho Desk. As we welcome 2025, we are strengthening our efforts to ensure a secure and seamless experience for you. To enhance email security, DKIM configuration will be mandatory for
                                • Calendar - "super compact" week view

                                  every time i go to my calendar i have to re-engage the "super-compact view" for the week view...is there a way to make "super-compact" a default view so I dont have to keep on setting it manually?
                                • Calendar - "pop up" locations

                                  One of the attractive features of google calendar and outlook calendar is that locations for events will start to automatically populate the location drop down menu as you type. Adding this feature to zoho calendar would be the final feature i need.
                                • Using Zia in Zoho Sheet data to research the internet and return answer to a cell in Zoho Sheet

                                  I'm trying to see if Zia (connected with OpenAI key) can take data parameters stored in a Zoho Sheet to conduct research out on the internet then return an answer into the same Sheet. I'm trying to do the equivalent of using something like the =AI() function
                                • [Free Webinar] Learning Table Series - Creator for the Education Industry

                                  Hello Everyone! We're thrilled to invite you to the Learning Table Series—a year-long initiative to demonstrate how Zoho Creator can transform industries with innovative and automated solutions. Each month focuses on a specific industry, and this time,
                                • Remove the [## XXXX ###] from subject replies

                                  For our organisation we would like to have the [## XXXX ###] removed from subject replies. Cheers, Jurgen 365VitaalWerken
                                • Next Page