Custom Action Name

AG_Batch_LeadTo

Objects affected

Lead and possible Accounts, Contacts, Opportunities (depending on the conversion)

Description

Use this custom action to convert selected Leads into Opportunities or Contacts in your organization. Use it from the Leads level. Please see the code comments for specific conversion behavior.

Use Cases

Convert a single Lead or a group of Leads at once.

Convert a Single Lead

Follow these steps to convert a Lead to an Account, Contact, Opportunity, or Follow-Up Task.

  1. Click Conga Grid Explorer.
  2. Click Lead in the object list.
  3. Select the check box of the record you want to convert.
  4. Click Actions and select Convert Lead > Convert Lead (Form).
  5. This opens the selected record in a Salesforce Convert Lead page where you can fill in the details about the selected lead. Refer to the Salesforce documentation for instructions on the Lead conversion process.Batch Convert LeadsFollow these steps to convert multiple Leads to Opportunities:
  6. Click Conga Grid Explorer.
  7. Click Lead in the object list.
  8. Select one or more records to convert.
  9. Click Actions and select Convert Lead > Batch Convert. The Batch Convert Options screen appears.
  10. Click Create Opportunities.
  11. Click OK. The results open in a new tab.

Warning

The use of JavaScript in Conga solutions is considered an advanced method, requiring JavaScript knowledge, and is not supported by Conga or the Conga support team. You are welcome to use this feature at your own risk

Code Example

/**
    * @author Conga Grid
    * @version 1.07
    * @description Batch convert leads.
    *
    * @id AG_Batch_LeadTo   Grid custom action id that is added to the name field.
    * @param kendoEntry     Grid helper for Kendo UI modal entry forms.
    * @param kendoPopup     Grid helper for Kendo UI model message windows.
    * @param sfdc           Grid helper for Salesforce REST API's
*/
/** Notes
    Account - Match on the name.
            - Bring over all child data.
            - Contact - Match on email address.
            -  If the Contact is a dupe then we don't need the account. -ISSUE
Note: account is required if merging a contact otherwise you will get a new account.
I built a lookup to pull the parent account of the matched contact. This will merge the
lead and its child data with the contact and its parent account. Warning, if that lead
was somehow matched with a different account by name the contact parent lookup will
override that value, because a lead merging  with a contact must be paired, and merged, with
its parent account.
    Opportunity - Convert if checked.
*/

crmc.require(["KendoEntry", "KendoPopup", "sfdc"], function(kendoEntry, kendoPopup, sfdc) {
    var LeadToForm =        { 
           "isAvailable": function (context) {
                var isEnabled = true;
                var isProject = context.objectDescribe.name == "Lead";
                var multipleSelected = context.selectedRows && context.selectedRows.length > 0;
                return isProject && isEnabled && multipleSelected;
            },
            "getLabel": function (context) {
                return "Convert Lead (Form)";
            },
            "createSubmenuItems": function (context) {
                return [];
            },
            "click": function (context) {
                if(context.selectedRows.length > 5){
                    var buttons = [{
                        label: "Yes",
                        click: function() {
                            processURL();
                        }
                    },
                    {
                        label: "No"
                    }];
                    kendoPopup.popupWithButtons("WARNING", "5 records are recommended because each item will show in a new tab. Do you want to continue?", buttons);
                }else{
                    processURL();
                }
                function processURL(){
                    var ids = []; 
                    context.selectedRows.map(function(row) {
                        ids.push(row.Id);
                    }); 
                    for (var i = 0; i < ids.length; i++) {
                        window.open("/lead/leadconvert.jsp?id=" + ids[i]);
                    };
                }
            }
    }; 
    var LeadToBatchConvert =
    {
        "isAvailable": function (context) {
            var isEnabled = true;
            var isProject = context.objectDescribe.name == "Lead";
            var multipleSelected = context.selectedRows && context.selectedRows.length > 0 && context.selectedRows.length <= 30;
            return isProject && isEnabled && multipleSelected;
        },
        "getLabel": function (context) {
            return "Batch Convert";
        },
        "createSubmenuItems": function (context) {
            return [];
        },
        "click": function (context) {
            //Created Ids.
            var accountIds = [];
            var contactIds = [];
            var opportunityIds = []; 
            //Lookup data.
            var records = [];
            var success = 0;
            var CANNOT_UPDATE_CONVERTED_LEAD = 0;
            var failCount = 0;
            var failed = ["<ul>"];
            var errorTrue = false;
            //Fields
            var doNotCreateOpportunity = true; 
            function ConvertLead(records){
                sforce.connection.convertLead(records,{
                    onSuccess: function(results){

//results test data
context.kendoGrid._progress && context.kendoGrid._progress(false);
                        for (var i = 0; i < results.length; i++) {
                            if(results[i].success && results[i].success == "true"){
                                success++;
                                results[i].accountId != null ? accountIds.push(results[i].accountId): function(){};
                                results[i].contactId != null ? contactIds.push(results[i].contactId): function(){};
                                results[i].opportunityId != null ? opportunityIds.push(results[i].opportunityId): function(){};
                            }
                            else if(results[i].errors.statusCode == "CANNOT_UPDATE_CONVERTED_LEAD"){
                                CANNOT_UPDATE_CONVERTED_LEAD++;
                            }
                            else{
                                errorTrue = true;
                                failCount++;
                                if(results[i].errors != undefined && results[i].errors.message != undefined){
                                    failed.push("<li>"+results[i].errors.message+"</li>");
                                }
                                else{
                                    failed.push("<li>"+results[i]+"</li>");
                                }
                            }
                        };
                        failed.push("</ul>"); 

                        // Convert lead debug email example example. Remove code comments and add preferred email addresses.
                        // var body = "Errors: " + errorTrue + " -- Records: " + records.toString() + " -- Results: " + results.toString();
                        // var singleRequest = new sforce.SingleEmailMessage();
                        // singleRequest.replyTo = "[Please add Reply To email address here]";
                        // singleRequest.subject = "Convert Lead Failures";
                        // singleRequest.plainTextBody = body;
                        // singleRequest.toAddresses = "[Please add To email address here]";
                        // var sendMailRes = sforce.connection.sendEmail([singleRequest]); 

                        var buttons = [
                            {
                                label: "Yes",
                                click: function() {
                                    window.open(kendo.format("/apex/CRMC_PP__crmc_grid?object={0}&Ids={1}", "Account", accountIds.join()));
                                    window.open(kendo.format("/apex/CRMC_PP__crmc_grid?object={0}&Ids={1}", "Contact", contactIds.join()));
                                    if(doNotCreateOpportunity == false){
                                        window.open(kendo.format("/apex/CRMC_PP__crmc_grid?object={0}&Ids={1}", "Opportunity", opportunityIds.join()));
                                    }
                                    if(failCount>0){
                                        kendoPopup.popupWithButtons("Errors", failed.join(""), [{label: "Ok"}], {width: 900});
                                    }
                                }
                            },{
                                label: "No",
                                click: function(){
                                    if(failCount>0){
                                        kendoPopup.popupWithButtons("Errors", failed.join(""), [{label: "Ok"}], {width: 900});
                                    }
                                }
                            }
                        ]; 
                        if(context.selectedRows.length == success){
                            var message = (doNotCreateOpportunity ? "Review the new/merged Account and Contact records?" : "Review the new/merged Account, Contact, and Opportunity records?");
                            kendoPopup.popupWithButtons("Success!", message, buttons);
                        }
                        else{
                            //Check if any records were converted
                            var anySuccess = (accountIds.length > 0 || contactIds.length > 0 || opportunityIds.length > 0);
                            var label = "";
                            var message = [
                                "<ul>",
                                "<li> Total selected: " + context.selectedRows.length + "</li>",
                                "<li> Already converted: " + CANNOT_UPDATE_CONVERTED_LEAD + "</li>",
                                "<li> New/Merged Accounts: " + accountIds.length + "</li>",
                                "<li> New/Merged Contacts: " + contactIds.length + "</li>",
                                "<li> New Opportunities: " + opportunityIds.length + "</li>",
                                "<li> Errors: " + failCount + "</li>",
                                (anySuccess ? "" : "<li> Click 'To Console' for more information </li>"),
                                "</ul>"
                            ];                           
                            if(anySuccess){
                                label = "Warning: Not all records were processed.";
                                message.push((doNotCreateOpportunity ? "Review the new/merged Account and Contact records?" : "Review the new/merged Account, Contact, and Opportunity records?") + " <br/>");
                                kendoPopup.popupWithButtons(label, message.join(""), buttons, {width: 350});
                            } else {
                                var buttons = [
                                    {
                                        label: "Ok",
                                        click: function(){
                                            if(failCount>0){
                                                kendoPopup.popupWithButtons("Errors", failed.join(""), [{label: "Ok"}], {width: 900});
                                           }
                                        }
                                    }
                                ];
                                label = "Warning: No records were processed.";
                                kendoPopup.popupWithButtons(label, message.join(""), buttons, {width: 300});
                            }
                        }
                        context.actionGrid.refresh();
                    },
                    onFailure: function(error) {
                        context.kendoGrid._progress && context.kendoGrid._progress(false);"
                        console.log("Error: " + error);
                        alert("Error: " + error);
                    }
                });
            } 
            var convertedList = sfdc.query("SELECT MasterLabel FROM LeadStatus WHERE IsConverted = true");
            if(convertedList.length > 1){
                var objectDescribe = sfdc.getSObjectDescribe("Lead");
                var picklistValues = []; 
                //Loop through the Lead fields.
                Object.each(objectDescribe.fields, function(field){
                    //Find the Status field.
                    if (field.name == "Status"){
                        //Loop through the LeadStatus Converted fields.
                        for (var i = 0; i < convertedList.length; i++) {
                            //Loop through the Lead picklist values for each LeadStatus.
                            for (var j = 0; j < field.picklistValues.length; j++) {
                                //Match LeadStatus MasterLabel with Lead Status picklist value.
                                if(convertedList[i].MasterLabel === field.picklistValues[j].value){
                                    //Populate form droplist with matched values.
                                    picklistValues.push(field.picklistValues[j]);
                                }
                            };
                        };
                    }
                });
            } 
            function GetFields(){
                if(convertedList.length > 1){
                    return [
                        {referenceTo:"User", name: "OwnerId", label: "Owner", type: "reference", required: false},
                        {name: "Status", label: 'Status', type: 'picklist', values: picklistValues, required: true},
                        {name: "createOpportunity", label: 'Create Opportunities', type: 'boolean', value: false},
                        {name: "sendNotificationEmail", label: 'Notify Owner', type: 'boolean', value: false},
                        {name: "overwriteLeadSource", label: 'Overwrite Lead Source', type: 'boolean', value: false},
                    ];
               }
                else {
                    return [
                        {referenceTo:"User", name: "OwnerId", label: "Owner", type: "reference", required: false},
                        {name: "createOpportunity", label: 'Create Opportunities', type: 'boolean', value: false},
                        {name: "sendNotificationEmail", label: 'Notify Owner', type: 'boolean', value: false},
                        {name: "overwriteLeadSource", label: 'Overwrite Lead Source', type: 'boolean', value: false},
                    ]
                }
            } 
            kendoEntry.entry("Batch Convert Options",
                GetFields(),
                {
                    objectName:"Lead",
                    resizable: true,
                    autoSizeFields: true,
                    width: '25%',
                    minWidth: '410px'
                },
                null,
                function(selectedValues) {
                    try{
                        context.kendoGrid._progress && context.kendoGrid._progress(true);
                        doNotCreateOpportunity = !selectedValues["createOpportunity"].value;
                        //Query arrays.
                        var ids = [];
                        var leadCompanies = [];
                        var leadEmails = []; 
                        //Convert Object.
                        var mapConvert = {};
                        var convert = []; 
                        function DataCheck(string){
                            return string.replace("'", "\\'");
                        } 
                        //Get a list of selected record Id's.
                        context.selectedRows.map(function(row) {
                            ids.push(row.id);
                        }); 
                        //Query for the Lead Company and email address.
                        var data = sfdc.query("SELECT Id, Company, Email FROM Lead WHERE Id IN('" + ids.join("','") + "')");
                        //Map lead names and build query arrays.
                        for (var i = 0; i < data.length; i++) {
                            var record = data[i];
                            //Query arrays.
                            leadCompanies.push(DataCheck(record.Company));
                            if(record.Email != "" && record.Email != null && record.Email != undefined){
                                leadEmails.push(record.Email);
                            } 
                            //Create a new lead convert object mapping for this lead.
                            mapConvert[record.Id] = {
                                leadId: record.Id,
                                Company: record.Company,
                                Email: record.Email,
                            };
                        };
                        
                         //Match lead names with account names.
                        var accountMatch = sfdc.query("SELECT Id, Name FROM Account WHERE Name IN('" + leadCompanies.join("','") + "') AND IsDeleted = false");
                        var joinEmails = leadEmails.join("','");
                        //Query only if there are contact emails to match.
                        if(joinEmails != ''){
                            //Match lead emails with contact emails.
                            var contactMatch = sfdc.query("SELECT Id, AccountId, Email FROM Contact WHERE Email IN('" + leadEmails.join("','") + "') AND IsDeleted = false");
                        } 
                        for (var key in mapConvert) {
                            for (var i = 0; i < accountMatch.length; i++) {
                                 var match = accountMatch[i];
                                if(mapConvert[key].Company == match.Name){
                                    //Set the matching account.
                                    mapConvert[key].accountId = match.Id;
                                }
                            };                           
                            if(joinEmails != ''){
                                for (var i = 0; i < contactMatch.length; i++) {
                                    var match = contactMatch[i];
                                    if(mapConvert[key].Email == match.Email){
                                        //Set the parent account Id.
                                        mapConvert[key].accountId = match.AccountId;
                                        //Set the matching contact.
                                        mapConvert[key].contactId = match.Id;
                                    }
                                };
                            }
                        } 
                        for (var key in mapConvert) {
                            var leadConvert = new sforce.LeadConvert();
                            leadConvert.leadId = mapConvert[key].leadId;
                            leadConvert.accountId = mapConvert[key].accountId;
                            leadConvert.contactId = mapConvert[key].contactId;
                            leadConvert.sendNotificationEmail = selectedValues["sendNotificationEmail"].value;
                            leadConvert.overwriteLeadSource = selectedValues["overwriteLeadSource"].value;
                            if(selectedValues.hasOwnProperty("Status")){
                                leadConvert.convertedStatus = selectedValues["Status"].value;
                            }
                            else {
                                leadConvert.convertedStatus = convertedList[0].MasterLabel;
                            }
                            leadConvert.doNotCreateOpportunity = doNotCreateOpportunity;
                            if(selectedValues["OwnerId"].value != "") leadConvert.ownerId = selectedValues["OwnerId"].value;
                            convert.push(leadConvert);
                        };
                        ConvertLead(convert);
                    }
                    catch(error){
                        context.kendoGrid._progress && context.kendoGrid._progress(false);
                        console.log("Error: "+ error);
                        alert("Error: " + error)
                    } 
                }
            );
        }
    };
     crmc.addCustomAction({
        actions: [LeadToForm, LeadToBatchConvert],
        "itemID": "AG_Batch_LeadTo",
        isAvailable: function(context) {
            var available = false;
            Object.each(this.actions, function(subMenu){
                if (subMenu.isAvailable(context)){
                    available = true;
                }
            });
            return available;
        },
        "getLabel": function (context) {
          return "Convert Lead...";
        },
        "createSubmenuItems": function (context) {
          return this.actions;
        },
        "click": function (context) {
        }
    });
});
CODE