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

                                                                                                  • Default Sorting on Related Lists

                                                                                                    Is it possible to set the default sorting options on the related lists. For example on the Contact Details view I have related lists for activities, emails, products cases, notes etc... currently: Activities 'created date' newest first Emails - 'created
                                                                                                  • Send email to all contacts related to a module

                                                                                                    My use case: I have a module named products, the records of which contains a related list of contacts associated with subscribing to that product. In cases where i need to trigger emails manually to give specific unprecedented updates of that product,
                                                                                                  • Function #28: Automatically calculate Customer Loyalty points

                                                                                                    Hello everyone, and welcome back to our series! Today, we're excited to share a workflow designed to streamline the management of loyalty points. Many businesses offer incentives or rewards in the form of loyalty points to their customers as a way to
                                                                                                  • Custom Modules Support for Zoho Creator Integration

                                                                                                    The title says it all. We have to create custom coded widgets for every little thing because this is not supported. Zoho Creator does not support custom modules. Zoho Forms does not support Multi-select-lookups. The point of Zoho is to not have to code
                                                                                                  • C# SDK net8.0 compatibility

                                                                                                    The NuGet packages seem to be targeting .net4.6.1 only. Are there any plans to target .net8.0, which is the current LTS version? Which package should I be using to interact with the API when targeting .net8.0, if any? If the SDK does not readily support
                                                                                                  • Notifications

                                                                                                    I am facing a problem with notifications, the mobile crm app does not notify me at all for any mail, task, activity, ... etc., the web is slightly better as i can see a notification on the bell icon however with a delay from real time and without a sound,
                                                                                                  • Disable All

                                                                                                    I want to disable all the fields on the form when it loads.  I know there is a way to do this by listing all the fields as follows: disable Name; disable Address; disable City;  ... I have over 50 fields on my form and i am wondering if there is a single command or way to just disable all fields on load.   On load = disable All Thank you for any help.  
                                                                                                  • Zoho Mail - CRM Widget

                                                                                                    When I click on Associate this email to a contact within the CRM widget, I get "Oops! Something went wrong". This happen when I try to associate an email in a shared mailbox. The widget detect correctly the contact and show his informations from the CRM
                                                                                                  • Kanban View for Projects.

                                                                                                    At our organization, we describe active projects with various statuses like "In Proofing" or "Printing" or "Mailing". In the Projects view, one can set these project statuses by selecting from the appropriate drop-down. While this works, it's difficult to view and comprehend the progress of all of your projects relative to each other in a table. Creating a Kanban view for projects where I can move them from one status to another allows me to see where each project is in the order of our workflow.
                                                                                                  • Feature request - export as video

                                                                                                    Export presentation as video. I think that it would be super useful for many users. Thanks
                                                                                                  • Display Company Logos in Pipeline View

                                                                                                    To improve deal management and enhance usability, we propose adding the option to display the associated company's logo directly in the pipeline view. Currently, users can only see the deal owner's avatar, but having the company's logo would make it easier
                                                                                                  • Attention: Scheduled Maintenance at US DC on Dec 19, 2024

                                                                                                    Dear Bookings users, We would like to inform you that we've scheduled maintenance activity at our US data centers on Thursday, December 19th, 2024, from 5:30 PM to 5:45 PM PT. During this period, Zoho Bookings will be completely unavailable for the accounts
                                                                                                  • StatusIQ

                                                                                                    Please add StatusIQ to data sources. We using site24x7 and StatusIQ together and site24x7 integration is already there. Thanks and regards, Torsten
                                                                                                  • Set Display for Numbers/Currency/etc with Client Script/Customization in Canvas List Page

                                                                                                    Is it possible to set a display mask for a number/currency field using Client Script or customization? I have custom fields that I would like to keep the decimal places for calculation purposes, but do not need them displayed to the user. So 101.3568
                                                                                                  • Cross module filtering is now supported in CRM

                                                                                                    Editions: All DCs: All Release plan: This enhancement is being released in phases. It is now available in AU, JP, and CN DCs. Help resource: Advanced filters While the feature is being released in phases, you can also request for Early Access. Early Access
                                                                                                  • Filter Criteria - Default Option for text fields should be "Contains" and not the current default "is"

                                                                                                    When in a list view and filtering by an input text field it would be a lot more helpful to have the default criteria be "contains" instead of "is". The "is" criteria is too specific and I'm forever changing it to "contains" in order to use the filter
                                                                                                  • Getting email status through api

                                                                                                    Refer to code below for getitng status of mail sent through CRM any modules. You can get the subject as a key in each response, so if you want to filter a specific email you just put an if condition for that. Note that the status will be given as a JSON
                                                                                                  • How to refresh/update module fields in

                                                                                                    Hi, I created a Workspace for CRM years ago. Since that time I've updated the layouts in several modules in CRM but Zoho Analytics displays the previous state fields only. How to refresh the module fields to reflect the actual state in Analytics? BR
                                                                                                  • Présentation d'une nouvelle fonctionnalité de webinar à la demande

                                                                                                    De nos jours, les gens s'attendent à un accès instantané aux informations et aux ressources, qu'il s'agisse de divertissement en continu ou d'apprentissage en ligne. Conscients de cette évolution, nous sommes ravis de vous présenter une nouvelle fonctionnalité
                                                                                                  • An accurate email totals report

                                                                                                    DOes anyone know how to create an email totals report that actually works? I am running the outlook integration and if I count the actual total number of emails that I sent last month, it is ten times higher than what zoho reports.
                                                                                                  • Settings - Time Display 12-hour vs 24-hour

                                                                                                    Hi All This is probably a question for developers as it only seems to be an issued on applications published from Developer account to client accounts. Usually a client would update how they want to view their time (12-hour vs 24-hour) in the Settings
                                                                                                  • AMP HTML in Email Templates on Zoho CRM?

                                                                                                    Hello Team! Is it possible to add AMP HTML features to the email tempalte in Zoho CRM? Im using an external service to create tempaltes and they provide me with AMP HTML features, or dynamic HTML modules. But when I try to add them to the Email template
                                                                                                  • Error : Bin Locations Provided are not valid

                                                                                                    1. We just moved our data from the US to Indian Data Center 2. Now, in one of my organisations, I am unable to save invoices or purchase bills for items and it shows an error 3. Irony is, we dont' even use Zoho Inventory. Operations are completely on
                                                                                                  • [FREE LIVE WEBINAR] Maximize the impact of your marketing campaigns using a centralized Brand Studio

                                                                                                    Hey everyone, We're introducing a free live webinar on Zoho Marketing Plus entitled Maximize the impact of your marketing campaigns using a centralized Brand Studio. The main agenda of the webinar is to give you a complete overview of how Zoho Marketing
                                                                                                  • Trouble Creating Basic Chart for Accounts - past 6 months

                                                                                                    We run a sports performance gym, and I want to create a chart to track member growth, by month, over the last 6 months or so. We group members under the Accounts module (e.g. a family of 4 contacts has 1 billing account). Accounts are termed "Active"
                                                                                                  • Possible to pause/control the data refresh schedule for data visualisation triggered from custom button?

                                                                                                    In a module record view, I have created a custom button action to show a data table view from Zoho Analytics, using https://help.zoho.com/portal/en/kb/crm/customize-crm-account/custom-links-and-buttons/articles/custom-buttons. I noticed that the view
                                                                                                  • Sorting a list of record acquired from the zoho.crm.searchRecords function.

                                                                                                    This is something for which I'm trying to figure out a straightforward way to do. The searchRecords does a great job fetching me the records that I want. However, in some cases, where it returns multiple records, I want it to sort the returned list by date of creation of that record, so that when I do records.get(0), I get the most recent record.  As an example, here's my sample pseudo code: records = zoho.crm.searchRecords("Clients", "Office_Number:equals:123456"); Now the "records" list above contains
                                                                                                  • Creating cadences Unable to save

                                                                                                    Hi, I'm creating a cadence for sales based on the leads module I have email templates in a folder "sales Cadence emails" when I add follow up 1 I select the email address of the user the cadence is for but it won't save....why not? Moderation Update (2nd
                                                                                                  • Tab order for custom phone fields.

                                                                                                    Our Lead records utilize multiple custom phone fields, appearing in multiple sections. The tab order has been configured from top to bottom for each section. When users create a new record, or edit one in a way that makes a custom phone field appear for
                                                                                                  • How Can i put a form in Zobot

                                                                                                    Hi,how can i integrate a form which has a multiple options to choose from.the form should be opened or displayed by zobot after it meets a requirement in the conversation. Thanks in advance !
                                                                                                  • Sales IQ needs to capture both first and last names

                                                                                                    Sales IQ chat only has one field for name. When this then syncs with Campaigns, the field populates the "last name" field in Campaigns. However most people fill in the "name" field of Sales IQ with either their full name or their Christian name. This
                                                                                                  • Export PDF from Zoho Books via API

                                                                                                    Hi, I'm trying to export a PDF of all the invoices from a customer in Zoho Books via API. I'm doing it this way: $url = 'https://books.zoho.com/api/v3/invoices/pdf?'; $token = "xxxxxxxxxxxxxxxxxxxxx"; $org_ID = "xxxxxxxx"; $invoice_ids = "6289710000XXXXXXXX,62897100000YYYYYYY"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url . 'authtoken=' . $token . '&organization_id=' . $org_ID . '&invoice_ids=' . $invoice_ids); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER,
                                                                                                  • is there a way to tag the form rule? so that the email workflow can be sent through zoho begin for that perticular response?

                                                                                                    I have a form rule; based on which the response like a program to be sent via begin workflow. How do i do that?
                                                                                                  • Zoho Writer page break in a merge repeating region always adds an unwanted blank page

                                                                                                    Hi I'm merging a Zoho CRM record to a Zoho Writer document with a repeating region to display subform records on their own page within the document. When I try to insert a page break in a repeating region, the resulting merge always adds an unwanted blank
                                                                                                  • Introducing bot filtering for accurate analytics

                                                                                                    Dear Zoho Campaigns Users, We're happy to introduce bot filtering to enhance the accuracy of your email campaign analytics. This new feature is designed to help you filter out bot-generated opens and clicks, which will ensure your campaign reports reflect
                                                                                                  • Is there a way to add clients who don't have organisation in Zoho Books/Payroll/Expense ?

                                                                                                    The Zoho Practice software is only allowing a total of 15 such clients who are not organisations in Zoho Books/Payroll/Expense. i.e. 5 organisation in each of the software by creating a new organization for them and adding the accountant as the admin
                                                                                                  • Error AS101 when adding new email alias

                                                                                                    Hi, I am trying to add apple@(mydomain).com The error AS101 is shown while I try to add the alias.
                                                                                                  • Zoho Mail POP & IMAP Server Details

                                                                                                    Hello all! We have been receiving a number of requests regarding the errors while configuring or using Zoho Mail account in POP/ IMAP clients. The server details vary based on your account type and the Datacenter in which your account is setup. Ensure
                                                                                                  • Company domain with Zoho Mail as support email in Zoho Desk

                                                                                                    Hello, We are a Zoho One customer. We just converted to Zoho Mail from Google Workspace Mail yesterday. We have a domain name for our company. With Gmail, we were able to forward our info@company.com email to Zoho Desk. Customer would then be able to
                                                                                                  • Best way to organize Zoho Desk with CRM products

                                                                                                    I'm having a bit of trouble finding out how I'm supposed to organize our Zoho Desk (departments vs teams vs products) and how to use it. We want to use the KnowledgeBase, Community, and Tickets sections. Here's a general overview of our company to get
                                                                                                  • Next Page