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

                                                                                                • 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?
                                                                                                • Function #4: Schedule Customer Statements

                                                                                                  Regularly sending statements to customers is an imperative part of many business processes as it helps foster strong customer relationships and provides timely guidance on payments. While you can generate the statement of accounts and have it sent over
                                                                                                • Music files on Zoho Docs

                                                                                                  1) Uploaded a ma3 music file from Itunes.  When I click on the link, i go to the page and see a music player but it doesn't play.  Clicking on the play arrow does nothing.  How to fix???? 2) Also, when i put up a .zip file  and goto the page, anyone download it.  That's fine. But with a music file, all I get is that non functional player with no way to simply download the song. Do I have to zip every song so it can be downloaded?
                                                                                                • Why is there no integration with native Brazilian shipping methods?

                                                                                                  Zoho Commerce is a powerful platform for e-commerce, but its lack of integration with native Brazilian shipping solutions is a significant limitation for users in Brazil. Integrating with popular shipping providers like Correios, Frenet, and Kangu would
                                                                                                • 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
                                                                                                • 5名限定 課題解決型ワークショップイベント Zoho ワークアウト開催のお知らせ (12/19)

                                                                                                  ユーザーの皆さま、こんにちは。Zoho ユーザーコミュニティチームの藤澤です。 12月開催のZoho ワークアウトについてお知らせします。 参加登録はこちら: https://us02web.zoom.us/meeting/register/tZAqdOCrrDMtGdL3w__UraUPaZxJpeS_wcyt ━━━━━━━━━━━━━━━━━━━━━━━━ Zoho ワークアウトとは? Zoho ユーザー同士で交流しながら、サービスに関する疑問や不明点の解消を目的とした「Zoho ワークアウト」を開催します。
                                                                                                • Restrict Employees Access to Zoho Support

                                                                                                  Dear Zoho Support Team, Greetings! I am the focal point for all Zoho-related matters in our organization, and I would like to request the following features to help us streamline and centralize our support interactions. We request that zoho one support
                                                                                                • 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
                                                                                                • Contacts Don't Always Populate

                                                                                                  I've noticed that some contacts can easily be added to an email when I type their name. Other times, a contact doesn't appear even though I KNOW it is in my contact list. It is possible the ones I loaded from a spreadsheet are not an issue and the ones
                                                                                                • How to import timesheets or entries into a projecgt

                                                                                                  How can one import timesheets into a project via a csv file?
                                                                                                • Automatic License Management Upon User Deactivation in Zoho One

                                                                                                  Dear Zoho Team, We would like to propose a feature enhancement for Zoho One regarding license management. Currently, when a user is deactivated, their license is not automatically downgraded or removed from our account. Zoho explains this behavior by
                                                                                                • Shared Snippets Everyone

                                                                                                  Hi, Now that the Shared Snippets have been released and I think will be the most used feature implemented in 2023 :) Creating and Using Snippets in Ticket Responses - Online Help | Zoho Desk Maintain consistency in ticket responses with shared snippets
                                                                                                • 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
                                                                                                • Introducing parent-child ticketing in Zoho Desk [Early access]

                                                                                                  Hello Zoho Desk users! We have introduced the parent-child ticketing system to help customer service teams ensure efficient resolution of issues involving multiple, related tickets. You can now combine repetitive and interconnected tickets into parent-child
                                                                                                • How to suppress display of "USD" of currency field?

                                                                                                • 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,
                                                                                                • New permissions for accessing emails sent via Zoho CRM

                                                                                                  Last modified on Nov 4, 2024: Permissions for accessing emails sent via Zoho CRM have now been extended to the IN DC. With this rollout, the feature is now available to all users across all DCs. Resources: Data sharing for emails, Configuring email compose
                                                                                                • When is Zoho Vault getting fuzzy search?

                                                                                                  Seeing posts on here dating back as far as 3 years complaining about Vaults search functionality. It’s terrible. Please include fuzzy search, and sorting of results according to “most applicable”; not just alphabetically.
                                                                                                • Automation#22 Track Ticket Duration at Specific Status

                                                                                                  Hello Everyone! Welcome back to the Community Learning Series! Today, we explore how Zylker Techfix, a gadget servicing firm, boosted productivity by tracking the time spent at a particular ticket status in Zoho Desk. Zylker Techfix customized Zoho Desk’s
                                                                                                • Self-Support Portal invites

                                                                                                  I'm a one man operation and I'm using the free version of the Zoho Desk for now, but I am in need of help. When I do test tickets, I get a reply from the system inviting me to join the Self Service portal. I don't plan on using that, so I wonder if there
                                                                                                • Lookup field in User module cannot look up to custom modules!

                                                                                                  Hi there, Expense has been great so far but it's sad to see that a simple thing such as allowing a lookup to custom modules from the Users module is not yet implemented. Hope to see this in the next release. Do you have any plan for that?
                                                                                                • Tip #10: Automatically add tags to Zoho CRM records using form responses

                                                                                                  You may be using tags to filter records, create reports based on specific tags, or let your sales team to know which clients to give priority to. Don't skip tagging for the crm records added via forms. The tags can be set to be automatically captured during the form submission. How it works When you set up a configuration to push form entries into CRM, you can add a tag to them automatically. The tag value can vary based on the respondent's input (captured using form fields), or you can include a
                                                                                                • Understanding response time

                                                                                                  We have the following set up for our SLA. When a contact first writes in, the response due and resolution due dates are set. When one of our agents responses, the response due goes away. When a ticket gets a response from the contact, it appears to reset
                                                                                                • Publish multiple languages at once in Knowledge Base

                                                                                                  Does anyone know if it is possible to publish multiple translated articles at the same time? My knowledge base has about 35 languages, and while I have them set up to automatically translate, I still have to go in and select each language and manually
                                                                                                • Canvas and Related lists

                                                                                                  Hi, As much as I like canvas, when adding in a asection with related lists,it doesnt mimic the same functionality as the standard view within the CRM e.g left hand panel will show the module and total number of records. Is there a way of indicating this
                                                                                                • Email address ZOHO suggestions in replying - how to delete unwanted suggestions?

                                                                                                  Hi, I have some "unwanted" email addresses suggestions by ZOHO, and made some mistakes by replying for some tickets already. How can I clear this in ZOHO directly, I deleted all web browser history and cookies . Did not help :/ Below example, where one
                                                                                                • Copy Widget to another Dashboard

                                                                                                  I can see the option to clone a widget to the same dashboard but is it possible to copy it to another dashboard?
                                                                                                • 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 :
                                                                                                • 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
                                                                                                • 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
                                                                                                • Subform edits don't appear in parent record timeline?

                                                                                                  Is it possible to have subform edits (like add row/delete row) appear in the Timeline for parent records? A user can edit a record, only edit the subform, and it doesn't appear in the timeline. Is there a workaround or way that we can show when a user
                                                                                                • CRM x WorkDrive: File storage for new CRM signups is now powered by WorkDrive

                                                                                                  Availability Editions: All DCs: All Release plan: Released for new signups in all DCs. It will be enabled for existing users in a phased manner in the upcoming months. Help documentation: Documents in Zoho CRM Manage folders in Documents tab Manage files
                                                                                                • Zoho Learn vs. Trainer Central

                                                                                                  Hi, I'm currently using Zoho One with a WordPress-based website and WooCommerce to manage my online courses. I would like to know what is the difference between Zoho Learn and Trainer Central and if it's possible for these two platforms to replace WP
                                                                                                • How to Display a Logo Image on a Public Form?

                                                                                                  I would like to display a logo image in the header of a form. To achieve this, I added an Add Notes field to the form. The code below works perfectly for Zoho users accessing the form. However, when the form is made public, the image does not load properly:
                                                                                                • Clear String field based on the value of other field

                                                                                                  Hello everyone, We would like to be able to clear a string field (delete whatever has been written and make it empty) when another field (picklist) is changed to a specific value. While I can empty other types of fields, I noticed that I can't do this
                                                                                                • Creating a Zoho Online Meeting in a Blueprint

                                                                                                  We are looking for an easy solution to schedule online meetings in a blueprint and ran into the same problem discussed in this topic: https://help.zoho.com/portal/en/community/topic/custom-function-to-set-meeting-to-online-meeting (After connecting Zoho
                                                                                                • Enabling 'From Number' and 'To Number' fields in the Calls module

                                                                                                  Hello everyone, We've added "To Number" and "From Number" fields in the Calls module as part of our latest update to provide users with the option to enable or disable them through the Calls Preferences tab. When enabled, these fields will be displayed
                                                                                                • Exciting Update: Multi WhatsApp Business Account (WABA) Support Now Available in SalesIQ!

                                                                                                  We’re pleased to share an important update that will enhance the way you manage your WhatsApp Business accounts (WABAs) within SalesIQ. With the launch of Multi WABA support, you can now connect and manage multiple brands more effectively, each under
                                                                                                • Route Optimizer

                                                                                                  Does Zoho Inventory offer route optimization for our in-house deliveries? It will save us time to manually route our daily orders. Thank you
                                                                                                • can I link a contacts to multiple accounts

                                                                                                  can I link a contacts to multiple accounts
                                                                                                • Next Page