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

                                                                                                • Sales

                                                                                                  1/ How can I make a discount on invoice exmple : invoice 5,100 le , custmar pay 5000 and I need to make this 100 le as a discount , how can i make it ?! 2/ Is thare any report can make me match my company’s balance with the customer’s balance?
                                                                                                • Include Project Hours when Creating Estimates from Projects

                                                                                                  Hi Currently, in Books, you can create estimates from Projects by inserting tasks that pull both the task and the hourly charge rate. But it doesn't pull the budgeted hours for the task, so you manually have to remember the number of hours for a given
                                                                                                • acc

                                                                                                  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 pay//
                                                                                                • South African Payment Gateways

                                                                                                  Since the "Demise" of Wave many South African users have moved over to Zoho and yet for years users have been requesting Integration with a South African Payment Gateway to no avail. Payfast was the most commonly requested gateway as it supports recurring
                                                                                                • Calendly does not show scheduled Meetings

                                                                                                  I use Calendly as my standard booking tool, but no matter what I am doing, Calendly shows any appointment as free (when in fact there already is an appointment in CRM Calendar or Zoho Calendar). Drives me nuts - cannot go away from Calendly due to various
                                                                                                • CRM Implementation

                                                                                                  I need to implement Zoho CRM. Is there a useful user manual available to guide me through the implementation?
                                                                                                • Zoho Creator Upcoming Updates - December 2024

                                                                                                  Hi all, We're excited to be back with the latest updates and developments on the Creator platform. Here's what we're going over this month: Deluge AI assistance Rapid error messages in Deluge editor QR code & barcode generator Expandable RTF and multi
                                                                                                • Zoho Social integration with Zoho Flow

                                                                                                  Is there any plans for Zoho Social integration with Zoho Flow?
                                                                                                • Marketing 2.0 has been a catastrophe

                                                                                                  Anyone else having significant issues with their link between their CRM and Marketing automation since moving to version 2.0? We had an easy flow for triggering leads in the CRM to journeys in Marketing Automation but now nothing seems to work properly.
                                                                                                • Pop Up

                                                                                                  Hello, I want to automatically display the information of the attached data in the product module in the related list section of my data in the lead module when the current time matches the "Call Time" field of my data in the leads module. How can I achieve
                                                                                                • Cannot average "Duration (Time)" from Pick List History Tracking in Reports

                                                                                                  Okay, let's say I have a custom module. In this custom module I have a pick-list named "Status" with "New", "In-Progress", "Completed" values. I also have turned ON pick-list history tracking and chose "Time" to track the duration in (instead of "Calendar
                                                                                                • Field Update: can't find a custom multi-line text field in the options list

                                                                                                  I want to update a custom text field (large size multi-line: 32000 characters) that I have added in the Accounts module using this functionality https://help.zoho.com/portal/en/kb/crm/automate-business-processes/actions/articles/field-updates , but I
                                                                                                • Authorize.Net Update: Disable Transaction IP Velocity Filter to Avoid Payment Failures

                                                                                                  Update: The Authorize.Net integration was updated on November 20, 2024. To prevent recurring transaction failures, we recommend disabling the Transaction IP Velocity Filter at the earliest. We’re updating the Authorize.Net integration in Zoho Books on
                                                                                                • Need to send a single email to up to 20 recipients

                                                                                                  I want to send a single email to ~16 or 20 recipients. It appears that I cannot do this in Zoho email as it gets flagged as unusual activity. I need to be able to communicate with this group on a regular basis. What am I missing that Zoho doesn't allow
                                                                                                • Whatsapp Limitation Questions

                                                                                                  Good day, I would like to find out about the functionality or possibility of all the below points within the Zoho/WhatsApp integration. Will WhatsApp buttons ever be possible in the future? Will WhatsApp Re-directs to different users be possible based
                                                                                                • Note not being pulled for other modules in email template

                                                                                                  Hi there, Currently i am creating an email template that is able to pull the data from notes field in estimate module and email it to procurement team where they will be able to receive the email with the contents of the note, i am unable to replicate
                                                                                                • Unable to Schedule One-to-One Emails in Zoho CRM

                                                                                                  Hi everyone, I’m using the Zoho CRM Professional Edition and facing an issue with scheduling one-to-one emails directly from CRM. While I can send immediate emails without any problem, I don’t see an option to schedule these emails for a later time. I’ve
                                                                                                • Canvas Detail View Related List Sorting

                                                                                                  Hello, I am having an issue finding a way to sort a related list within a canvas detail view. I have sorted the related list on the page layout associated with the canvas view, but that does not transfer to the canvas view. What am I missing?
                                                                                                • Repeatable Fields/Sections in Zoho CRM

                                                                                                  Hi Zoho Team, We have a module in CRM named "Clients". We would like to know whether it is possible to have a feature enables us to have repeatable sections in our clients' profiles? For example, if we customized a section in the clients' profiles named
                                                                                                • Zoho Analytics: Requests for view access

                                                                                                  Hello, We have a user that might request access to a certain view, report etc. However this request for access is being sent to different admins within the workspace, is is possible to set who the "approver" is of these requests? If not what are the rules
                                                                                                • Boolean Fields in Mail Merge Displaying as Checkmarks

                                                                                                  I'm really liking the new mail merge functionality. It's replaced the Zoho Sign extension for us. One problem I've seen is that boolean operators (i.e. Checkbox fields) in CRM merge as "True" or "False". This looks a little ugly in my final document — is there a way I can get those to display as checkboxes?
                                                                                                • Formula in Sub Form

                                                                                                  Hello - I have created a sub-form and the data is going to be insurance policy information. However some of the policy amounts are based on a percentage of a main coverage. For example, Debris removal coverage is 5% of the main dwelling policy. Is there
                                                                                                • Zoho cases and remote work api

                                                                                                  How to use zoho cases listing api? When i try to hit the endpoint specified in the docs , i get the error : the page you are looking for does not exist with a 401.
                                                                                                • Email alias already exist

                                                                                                  Hello, I'm getting an error message the email alias already exist when attempting to add 2 email addresses. The emails are associated with an account I deleted. I started a new account and need to add them back to get 1 email at each. I have an open ticket
                                                                                                • Migrate emails from a shared mail box to a private mail box

                                                                                                  How is possible migrate a shared mail box if the migration tool require a password, and the shared mail dosent have ?
                                                                                                • Support poor service

                                                                                                  I just wanted Zoho support to give me some more concrete answers. I’m facing SMTP error issues, and they told me that the South American IP was experiencing problems, but they didn’t provide an estimate for when it would be resolved. Now my company is
                                                                                                • Zoho say my domain seems to be already associated with another account

                                                                                                  I created a zoho account for try my domain mail configuration. When I want to add my domain in this page https://mailadmin.zoho.com/hosting?plan=free then this shows an error that is "This domain is already associated with this account a*****n@f*****."
                                                                                                • Incorrect Device Time

                                                                                                  Hi On my windows laptop I can't sign into Zoho mail due to "incorrect device time". I'm in Toronto, Canada. How can this be resolved?
                                                                                                • Get user images by API

                                                                                                  Hi For our internal management software, I want to retrieve user photos via REST API: curl --location --request GET 'https://profile.zoho.com/file?fs=thumb&ID=<zoid>' \ --header 'Authorization: Zoho-oauthtoken <token>' The token has `profile.userphoto.ALL`,
                                                                                                • Depois de 1 ano não consigo receber e-mail

                                                                                                  Consigo enviar e-mails mas não estou recebendo nenhum e-mail isso aconteceu pontualmente após eu completar 1 ano de uso. Me ajudem por favor
                                                                                                • Submitted form URL

                                                                                                  I am using the feature "Include a link to allow respondents to edit their responses" for the first time. This URL is included in the email sent to the user after they press Submit. If a form is Saved, there is a section called Partially Saved Entries
                                                                                                • 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
                                                                                                • Create a new immigration service- Similar to immigration law software

                                                                                                  It will be good if you can build a new service. Data will be pulled from the employee form. Then automatically users should be able to complete immigration forms like I 129, ETA 9089, ETA 9035 E, G- 28, W4, I 9 PDF forms and then be able to send for signature with Zoho sign. Immigration Softwares like docketwise can be used for ideas. The advantage with this it sits within Zoho people and employees don't have to feed data in another system
                                                                                                • Accessibility in Zoho CRM: Not just a feature—a way to empower

                                                                                                  For instructions on setting up these controls, please check this help document: Configuring accessibility controls. Hello everyone, Today (December 3, 2024), on the International Day of Persons with Disabilities, we begin our journey towards a CRM that
                                                                                                • Zoho Meeting very bad video quality

                                                                                                  Hello, I need 1080p HD on my Zoho Meeting as explained here: Low Resolution/Quality Video (zoho.com) Currently, video quality is lagging with 400mb internet which is not acceptable for my business. My 1080p 60FPS webcam performs well on platforms like
                                                                                                • Contacts with Deals not appearing.

                                                                                                  What: I simply want to see all of the contacts that are tied to an open deal Problem: In Contacts Module > When filtering on Contacts with an open deal, Zoho only shows some Contacts instead of all. Details: More specifically, I should have ~200 contacts
                                                                                                • Auto-sync field of lookup value

                                                                                                  This feature has been requested many times in the discussion Field of Lookup Announcement and this post aims to track it separately. At the moment the value of a 'field of lookup' is a snapshot but once the parent lookup field is updated the values diverge.
                                                                                                • CRM limit reached: only 2 subforms can be created

                                                                                                  we recently stumbled upon a limit of 2 subforms per module. while we found a workaround on this occasion, only 2 subforms can be quite limiting in an enterprise setting. @Ishwarya SG I've read about imminent increase of other components (e.
                                                                                                • Version of Cliq included with Zoho One and Limitations

                                                                                                  I'm confused by the information presented in the application detail page of Zoho One. I'm a solopreneur with a single-seat Zoho One Enterprise license and I need to communicate externally .. extensively. The plan details page suggests channels are limited to 100 members. Whereas the pricing plan comparison page on the Cliq marketing site says 2500 for enterprise level.  If it's 100... that's going to kill my use case as it is my understanding that external customers can only be communicated with
                                                                                                • Resubmit for Approval for Zoho Books Module in CRM

                                                                                                  The integration between CRM and Books is great, but it is incomplete in many areas. One of them is if an estimate/invoice/sales order is rejected, the users in CRM cannot resubmit it for approval. Let's face it, sales people will mostly be in CRM and
                                                                                                • Next Page