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

                                                                                                  • How do I delete a test email address to which I am supposed to send a test email?

                                                                                                    How do I delete an email address added to a test email recipient that is no longer needed due to resignation or other reasons?
                                                                                                  • What is Attendee Status 0 and 1?

                                                                                                    Hi there, I recently stumbled upon the API to get the attendee list and in the return value, there is a parameter called "status", and 0 supposed to mean not_attending, and 1 means attending. I cannot find this representation anywhere in the attendee
                                                                                                  • Kaizen #121 : Customize List Views using Client Script

                                                                                                    Hello everyone! Welcome back to another interesting Kaizen post. In this post, we can discuss how to customize List Views using Client Script. This post will answer the questions Ability to remove public views by the super admin in the Zoho CRM and Is
                                                                                                  • Batch Number on Packing Slip

                                                                                                    When we send orders to our warehouse, we want to tell them the batch number to pull from the shelf.  It seems we should be able to pick the batch when assembling the package. In the current Inventory, we have to create an invoice, pick batches for the invoice.  This is too late.   As a workaround, we are sending the invoice to the warehouse (via a template that removes most of the price information).  This is cumbersome and causes our warehouse to see the total invoice price (which can't be removed
                                                                                                  • Editing a bundle

                                                                                                    How can I edit a bundle?
                                                                                                  • Saving URL for Submitted Forms

                                                                                                    The unique URL for submitted forms should be saved automatically within 'System Fields'. (without sending a duplicate email to myself, there is no other way to retrieve the unique URL for a submitted form if the user wishes to update) Additionally, it
                                                                                                  • Implement Meeting Polls in Zoho Bookings

                                                                                                    Dear Zoho Bookings Support Team, We'd like to propose a feature enhancement related to appointment scheduling within Zoho Bookings. Current Functionality: Zoho Bookings excels at streamlining individual appointment scheduling. Users can set availability
                                                                                                  • Response from a customer via web channel

                                                                                                    Is it possible to ensure that a customer using the web channel can respond to an agent's question without creating a new thread but instead linking their response to the existing thread?
                                                                                                  • Venezuelan Bolivares missing from available currencies

                                                                                                    My mother is ill and lives in Venezuela. I do her finances and insurance expences related to medical billing. Most receipts are in Venezuelan Bolivares. However I cannot find this currency. I am migrating from Expensify which conveniently has Bolivares
                                                                                                  • Flow with CRM

                                                                                                    Hello, I have a simple flow that uses a web hook to enter data into a Sales Order. I have the web hook sending Flow data which has a PO field. If the PO has a special character like - or / or \ the task fails. How can I get the flow to be okay with the
                                                                                                  • Using WhatsApp with your existing number

                                                                                                    Hi. We want to use the WhatsApp functionality in Zoho Desk. We already have a WhatsApp business account. Is it possible to use your existing number instead of creating a new number?
                                                                                                  • Customize Section

                                                                                                    I know it has to be in the themes somewere but where is it that you can change the divider color of a section?
                                                                                                  • Customer Feature Requests

                                                                                                    Like Zoho, we're a software company that markets an SaaS product. We frequently get feature requests that come from the support system. My technicians have a responsibility to listen to our customer requests and add them. Right now the only way to do
                                                                                                  • the expected input type is jsonarray

                                                                                                    I keep getting an error when creating a record in CRM via a Zoho Form. CRM has a pick list field "Type". All Form entries from this form will ALWAYS be "Volunteer", therefore we do not ask them what their Type is. I am trying to use Set Value to create
                                                                                                  • fetch records from analytics table from creator

                                                                                                    I have a creator workflow that I am working in that will compare data from within the app to a table in zoho analytics. Is there a way to fetch a record from Analytics? I have attempted a custom connector with analytics and tried to use it with invoke
                                                                                                  • Remove County field from Customer Address input screen (or allow input to be deleted)

                                                                                                    We are in the USA and have just noticed that there is now a County field in the Customer Address input screen (and maybe other areas of Zoho Books, but this is the one affecting us at the moment). County is not important to our business, and in fact we
                                                                                                  • Card payment surcharge?

                                                                                                    Hi, I would like to offer my customers the ability to pay invoices by card (using the PayPal integration). However, PayPal charges me around 5% to receive a card payment, and I would like to pass on this cost to my customer by way of a card payment surcharge. Is there any way for Zoho Invoice to be set up to automatically add a defined "card processing fee", say 5% of the invoice total, if the customer elects to pay by card? I don't want to add this on to invoice manually, since most of my clients
                                                                                                  • Cant add contact mail. cant find it

                                                                                                    Hi, I am writing a new message and when I enter the contact address that is in my address book, zoho cannot find it. Previously there was no problem. I wrote the first two characters and it shows me all the contact.
                                                                                                  • Customer Parent Account or Sub-Customer Account

                                                                                                    Some of clients as they have 50 to 300 branches, they required separate account statement with outlet name and number; which means we have to open new account for each branch individually. However, the main issue is that, when they make a payment, they
                                                                                                  • Creating a text box background with round corners in Campaigns

                                                                                                    Hello fellow Campaigns users, Is it possible to create a non-square text box? So with rounded off corners. Like the image that I added below. The shadow effect would be cool too, but I guess that would be more difficult (if possible). I suppose this can
                                                                                                  • Image field in custom module

                                                                                                    Hi guy, Is there any hope of adding a custom image field in the custom module? We created a custom module to keep track of assets, and it would be helpful if we could attach an image to the record. Thanks Rudy
                                                                                                  • Team can't view their created ticket through Followed Tickets

                                                                                                    Hello Everyone, in our organization we are new to zoho desk we have multiple teams, and each team handles specific topics and tickets when one of them tries to create a ticket for another team and use followed tickets to view this ticket we get a message
                                                                                                  • Function #61: Automatically add free item to the invoice based on item quantity

                                                                                                    Hello everyone, and welcome back to another Custom Function Friday! During holiday seasons or special promotions, businesses offer deals like BOGO (Buy One, Get One), Buy 3 Get 1 Free, Buy 2 at 50% off, and much more to attract customers. These promotions
                                                                                                  • Use color coding for picklist field values to enhance visual representation

                                                                                                    It's easier and more efficient to manage a large volume of data in a ticket or other custom module records, such as ticket priorities and issue types, when you apply clear visual distinctions through color coding. Color-coded picklist fields allow users
                                                                                                  • Creating a support request / ticket via email to xxx@zohosupport.com

                                                                                                    Is there the ability to create a ticket from an email sent to my support email address (e.g. xxx@zohosupport.com)? For example, I am running a small computer support/service business and I would like to be able to direct potential customers to send an
                                                                                                  • Call transcrition working for ringcentral?

                                                                                                    I don't see anything about what telephony providers can be used. The Zoho support person A said that RingCentral isn't supported. Zoho support person B said that it works, just make sure the call recording link works. Excellent instructions here: Call
                                                                                                  • Setting up CRM for RFP workflow management

                                                                                                    This will be the first time our organization uses an off-the-shelf CRM, transitioning from our homegrown custom solution, and I would appreciate general thoughts on how to get started in general with our workflow using Zoho CRM. The main question: if
                                                                                                  • Introducing Appointment Title Customization

                                                                                                    Hi all, We're delighted to announce an exciting feature, Appointment Title Customization, which you can use to personalize your appointment title according to your business's specific needs and preferences. An appointment title provides a glimpse of the
                                                                                                  • Custom Module

                                                                                                    I've created a custom module in Zoho Recruit for a separate list outside of qualified candidates. On the module, I use First name and Last Name in separate lines. On the top of the module and when I search a person, it only shows the first name at the
                                                                                                  • How to merge duplicate products?

                                                                                                    merge duplicate products
                                                                                                  • Data not visible in sheet cells

                                                                                                    I'm having an issue where my data is not visible in my sheet cells. If I click on an individual cell, the data does display above in the little "fx" box. But all the boxes in the sheet just look blank. My collaborators do not have this issue. I have checked
                                                                                                  • Rollup summary for custom module

                                                                                                    Rollup summary feature was introduced almost a year ago: https://help.zoho.com/portal/en/community/topic/introducing-rollup-summary-in-zoho-crm-public-early-access-2023 It does not support custom modules tough and this post aims to track such feature
                                                                                                  • Foreign Currency Bank Account

                                                                                                    I have a bank account in USD zero balance but when i run the bank ledger in my company currency in AED it was shown small balance 1.31 AED , how to make it zero also ,Thanks
                                                                                                  • Why don't we have better integration with Mercado Pago or Pagseguro?

                                                                                                    Currently, the integration between Zoho Commerce and Mercado Pago for Brazil is very poor... Since it is old, it does not include the main payment method in Brazil today, which is PIX. Is there a date for this to finally be launched? There are numerous
                                                                                                  • Alert for Back Navigation in Zoho Creator Widgets on Mobile Apps

                                                                                                    In Zoho Creator widgets, when a user navigates back on mobile devices, the data within the widget is reset. This leads to a loss of any unsaved changes or inputs, causing frustration for users. To enhance user experience, we need to implement a confirmation
                                                                                                  • "Trigger flow for each entry" not working

                                                                                                    I've read this article on how to trigger a flow for each entry in my array. https://help.zoho.com/portal/en/kb/flow/user-guide/create-a-flow/articles/webhook-trigger#Trigger_flow_for_each_entry I cannot get the flow to run for each variant in this JSON
                                                                                                  • migrating from Zoho Invoices (CRM) to Zoho Books

                                                                                                    Good day, I was wondering if there was a easy way to migrate all the quotes and invoices from Zoho Invoices CRM to Zoho Books. We plan to move to using Zoho Books in a few weeks and would like to have all the quotes and invoices from the past 3 years
                                                                                                  • Edit specific job page on carreer site

                                                                                                    Hey, I was wondering how I could change the layout of a specific job page? (when you go to the carreer website and then click on a job listed there). When I go to customization I can edit the carreer website but I seem to be only able to edit the first
                                                                                                  • CRM - Clearing a Subform

                                                                                                    I seem incapable of working out subform functions without assistance.  I've searched, but can't seem to find anything that works. I have a subform that gets filled in when a Zoho Sign document is completed but the fields don't match with the original field values held on CRM (I did have it automatically update, but some fields were being filled in with terrible data, so had to put a stop to it).  There are 4 fields on the subform: Field Name Original Value New Value Update Update is automatically
                                                                                                  • How to include GST% in PO amount?

                                                                                                    Currently when I raise PO, the basic price of the item is used. However, the GST is not calculated and added along with the basic amount. I have added a Custom field for GST in the PO but I need Zoho Inventory to calculate the GST amount and add it with the Basic price to give me the final PO price.
                                                                                                  • Next Page