function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ashley Cobb 25Ashley Cobb 25 

Lead conversion trigger not firing

Hello,

The company that I work for has custom code to convert a lead to a contact/account.  For some reason it only fires about half the time.  This is extrememly important because our users do not have access to leads so when they are not converted they are not followed up with. I would really appreciate it if anyone can look and see if they find any errors. I have been looking through it for days and cannot seem to figure out why it only fires half the time and doesn't send me any error messages.  This is a little bit beyond my ability as I have never worked with @future methods or scheduling things via the UI.

Trigger:
trigger LeadTrigger on Lead( after update, after insert )
{
    // Assign values of trigger new list to helper class variable
    LeadTriggerHelper.newLeadList = trigger.new;
    // Assign values of trigger old list to helper class variable
    LeadTriggerHelper.oldLeadList = trigger.old;
    // Assign values of trigger new map to helper class variable
    LeadTriggerHelper.newLeadMap = trigger.newMap;
    // Assign values of trigger old map to helper class variable
    LeadTriggerHelper.oldLeadMap = trigger.oldMap;
    
    // Check if runTrigger
    if( LeadTriggerHelper.runTrigger )
    {
        // Check if after
        if( trigger.isAfter )
        {
            // Check if Update
            if( trigger.isUpdate )
            {
                // Call method to convert lead
                LeadTriggerHelper.leadConversionAfterInsert();
            }
            
            if( trigger.isInsert )
            {
                LeadTriggerHelper.scheduleLeadConversion();
            }
        }
    }
}
Classes:
public with sharing class LeadTriggerHelper
{
    // To check whether to call boolean or not
    public static Boolean runTrigger = true;
    // List to store Lead of trigger.new
    public static List<Lead> newLeadList = new List<Lead>();
    // List to store Lead of trigger.old
    public static List<Lead> oldLeadList = new List<Lead>();
    // Map to store Lead of trigger.newMap
    public static Map<Id, Lead> newLeadMap = new Map<Id, Lead>();
    // Map to store Lead of trigger.oldMap
    public static Map<Id, Lead> oldLeadMap = new Map<Id, Lead>();
    
    private static String convertStatus;
    private static Map<String, User> nameToUserMap = new Map<String, User>();
    
    /**
     * Name: leadConversionAfterInsert
     * @param:
     * @return:
     * Desc: Method to convert lead when created
    **/
    public static void leadConversionAfterInsert()
    {
        //try
        //{
            Set<String> uniqueEmails = new Set<String>();
            Set<String> uniqueWebsites = new Set<String>();
            List<Lead> uniqueLeads = new List<Lead>();
            List<Lead> existingLeads = new List<Lead>();
            List<Lead> newAccountExistingEmail = new List<Lead>();
            Set<String> userNames = new Set<String>();
            
            for( Lead lead : newLeadList )
            {
                if( lead.Convert__c && !oldLeadMap.get( lead.Id ).Convert__c && !lead.Isconverted )
                {
                    if( lead.Website != null && lead.Website != '' )
                    {
                        if( uniqueWebsites.contains( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
                        {
                            if( lead.Email != null && lead.Email != '' )
                            {
                                if( uniqueEmails.contains( lead.Email ))
                                {
                                    newAccountExistingEmail.add( lead );
                                }
                                else
                                {
                                    uniqueEmails.add( lead.Email );
                                    existingLeads.add( lead );
                                }
                            }
                            else
                            {
                                existingLeads.add( lead );
                            }
                        }
                        else
                        {
                            uniqueWebsites.add( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                            uniqueLeads.add( lead );
                            
                            if( lead.Email != null && lead.Email != '' )
                            {
                                uniqueEmails.add( lead.Email );
                            }
                        }
                    }
                    else if( lead.Email != null && lead.Email != '' )
                    {
                        if( uniqueEmails.contains( lead.Email ))
                        {
                            existingLeads.add( lead );
                        }
                        else
                        {
                            uniqueEmails.add( lead.Email );
                            uniqueLeads.add( lead );
                        }
                    }
                    else
                    {
                        uniqueLeads.add( lead );
                    }
                    
                    if( lead.MASTER_SDR_Owner__c != null && lead.MASTER_SDR_Owner__c != '' )
                        userNames.add( lead.MASTER_SDR_Owner__c );
                }
            }
            
            LeadStatus convertStatuses = [ Select MasterLabel from LeadStatus where IsConverted = true limit 1 ];
            convertStatus = convertStatuses.MasterLabel;
            
            for( User u : [ Select Id, Name from User where Name IN :userNames ])
            {
                nameToUserMap.put( u.Name, u );
            }
            
            convertLeads( uniqueLeads );
            convertLeads( existingLeads );
            convertLeads( newAccountExistingEmail );
        /*}
        catch( Exception e )
        {
            system.debug( 'Error********************' + e.getMessage() + ':::::::::::::::' + e.getLineNumber() );
        }*/
    }
    
    public static void convertLeads( List<Lead> leadsToBeConverted )
    {
        Set<String> emailAddressSet = new Set<String>();
        Set<Id> accountIds = new Set<Id>();
        Set<String> webSiteSet = new Set<String>();
        
        for( Lead lead : leadsToBeConverted )
        {
            if( lead.bizible2__Account__c != null )
                accountIds.add( lead.bizible2__Account__c );
            else if( lead.Website != null && lead.Website != '' )
                webSiteSet.add( '%' + lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                
            if( lead.Email != null && lead.Email != '' )
                emailAddressSet.add( lead.Email );
        }
        
        Map<Id, Account> accountMap = new Map<Id, Account>([ Select Id, Website, Phone, Description, Intel_City__c,
                                                                Intel_Country__c, Intel_State__c, Territory_New__c,
                                                                ( Select Id, Email, Phone, Title, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                                                                    Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                                                                    Survey_Using_an_Agency__c, Calls_Made__c, Follow_up_Date__c, Relevant_ADR_Notes__c, ADR_Owner__c, Current_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                                                                    LeadSource from Contacts where Email IN :emailAddressSet )
                                                                from Account where Id IN :accountIds ]);
        
        Map<String, List<Account>> websiteToAccountMap = new Map<String, List<Account>>();
        for( Account acc : [ Select Id, Website, Phone, Description, Intel_City__c, Intel_Country__c, Intel_State__c,
                                Territory_New__c, ( Select Id, Email, Phone, Title, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                                Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                                Survey_Using_an_Agency__c, Calls_Made__c, Follow_up_Date__c, Relevant_ADR_Notes__c, ADR_Owner__c, Current_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                                LeadSource from Contacts where Email IN :emailAddressSet ) from Account where Website like :webSiteSet ])
        {
            List<Account> accs = new List<Account>();
            if( websiteToAccountMap.containsKey( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
            {
                accs = websiteToAccountMap.get( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
            }
            
            accs.add( acc );
            websiteToAccountMap.put( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ), accs );
        }
        
        /*Map<String, Contact> emailAddressToContactMap = new Map<String, Contact>();
        for( Contact con : [ Select Id, Email, Phone, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                            Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                            Survey_Using_an_Agency__c, MASTER_SDR_Contact_Attempts__c, MASTER_SDR_Follow_Up_Date__c, MASTER_SDR_Notes__c,
                            MASTER_SDR_Owner__c, MASTER_SDR_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                            LeadSource from Contact where Email IN :emailAddressSet ])
        {
            emailAddressToContactMap.put( con.Email, con );
        }*/
        
        List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
        Map<Id, Account> accountsToBeUpdated = new Map<Id, Account>();
        Map<Id, Contact> contactsToBeUpdated = new Map<Id, Contact>();
        
        for( Lead lead : leadsToBeConverted )
        {
            Database.LeadConvert lc = new Database.LeadConvert();
            lc.setDoNotCreateOpportunity( true );
            lc.setLeadId( lead.Id );
            lc.setConvertedStatus( convertStatus );
            
            Account acc;
            Contact con;
            if( lead.bizible2__Account__c != null && accountMap.containsKey( lead.bizible2__Account__c ))
            {
                acc = accountMap.get( lead.bizible2__Account__c );
                
                if( lead.Email != null && lead.Email != '' )
                {
                    for( Contact c : acc.Contacts )
                    {
                        if( c.Email != null && c.Email != '' && c.Email.equalsIgnoreCase( lead.Email ))
                        {
                            con = c;
                            break;
                        }
                    }
                }
            }
            else if( lead.Website != null && lead.WebSite != ''
                        && websiteToAccountMap.containsKey( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
            {
                List<Account> accounts = websiteToAccountMap.get( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                
                if( lead.Email != null && lead.Email != '' )
                {
                    for( Account a : accounts )
                    {
                        for( Contact c : a.Contacts )
                        {
                            if( c.Email != null && c.Email != '' && c.Email.equalsIgnoreCase( lead.Email ))
                            {
                                acc = a;
                                con = c;
                                break;
                            }
                        }
                        
                        if( acc != null )
                            break;
                    }
                    
                    if( acc == null )
                        acc = accounts[0];
                }
            }
            
            if( acc != null )
            {  
                lc.setAccountId( acc.Id );
                Boolean flag = false;
                
                if( acc.Phone == null || acc.Phone == '' )
                {
                    acc.Phone = lead.Phone;
                    flag = true;
                }
                
                if( acc.Description == null || acc.Description == '' )
                {
                    acc.Description = lead.Description;
                    flag = true;
                }
                
                if( acc.Intel_City__c == null || acc.Intel_City__c == '' )
                {
                    acc.Intel_City__c = lead.Intel_City__c;
                    flag = true;
                }
                
                if( acc.Intel_Country__c == null || acc.Intel_Country__c == '' )
                {
                    acc.Intel_Country__c = lead.Intel_Country__c;
                    flag = true;
                }
                
                if( acc.Territory_New__c == null || acc.Territory_New__c == '' )
                {
                    acc.Territory_New__c = lead.Territory_New__c;
                    flag = true;
                }
                
                if( acc.Intel_State__c == null || acc.Intel_State__c == '' )
                {
                    acc.Intel_State__c = lead.Intel_State__c;
                    flag = true;
                }
                
                if( flag )
                    accountsToBeUpdated.put( acc.Id, acc );
            }
            
            if( con != null )
            {
                lc.setContactId( con.Id );
                Boolean flag = false;
                //Contact con = emailAddressToContactMap.get( lead.Email );
                
                if( con.Phone == null || con.Phone == '' )
                {
                    con.Phone = lead.Phone;
                    flag = true;
                }
                
                if( con.Title == null || con.Title == '' )
                {
                    con.Title = lead.Title;
                    flag = true;
                }
                
                if( con.Description == null || con.Description == '' )
                {
                    con.Description = lead.Description;
                    flag = true;
                }
                
                if( con.LeadSource == null || con.LeadSource == '' )
                {
                    con.LeadSource = lead.LeadSource;
                    flag = true;
                }
                
                if( !con.Snapengage__c )
                {
                    con.Snapengage__c = lead.Snapengage__c;
                    flag = true;
                }
                
                if( con.Survey_Agency_Services__c == null || con.Survey_Agency_Services__c == '' )
                {
                    con.Survey_Agency_Services__c = lead.Survey_Agency_Services__c;
                    flag = true;
                }
                
                if( con.Survey_Current_Attribution_Model__c == null || con.Survey_Current_Attribution_Model__c == '' )
                {
                    con.Survey_Current_Attribution_Model__c = lead.Current_Attribution_Model_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Marketing_Channels_in_Use__c == null || con.Survey_Marketing_Channels_in_Use__c == '' )
                {
                    con.Survey_Marketing_Channels_in_Use__c = lead.Marketing_Channels_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Name_of_Agency__c == null || con.Survey_Name_of_Agency__c == '' )
                {
                    con.Survey_Name_of_Agency__c = lead.Survey_Name_of_Agency__c;
                    flag = true;
                }
                
                if( con.Survey_Reporting_Tools_and_Apps_in_Use__c == null || con.Survey_Reporting_Tools_and_Apps_in_Use__c == '' )
                {
                    con.Survey_Reporting_Tools_and_Apps_in_Use__c = lead.Reporting_Tools_and_Apps_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Using_an_Agency__c == null || con.Survey_Using_an_Agency__c == '' )
                {
                    con.Survey_Using_an_Agency__c = lead.Survey_Using_an_Agency__c;
                    flag = true;
                }
                
                if( con.Calls_Made__c == null || con.Calls_Made__c == '' )
                {
                    con.Calls_Made__c = lead.MASTER_SDR_Contact_Attempts_2__c;
                    flag = true;
                }
                
                if( con.Follow_up_Date__c == null )
                {
                    con.Follow_up_Date__c = lead.MASTER_SDR_Follow_Up_Date__c;
                    flag = true;
                }
                
                if( con.Relevant_ADR_Notes__c == null || con.Relevant_ADR_Notes__c == '' )
                {
                    con.Relevant_ADR_Notes__c = lead.MASTER_SDR_Notes__c;
                    flag = true;
                }
                
                if( con.ADR_Owner__c == null )
                {
                    if( lead.MASTER_SDR_Owner__c != null && lead.MASTER_SDR_Owner__c != '' && nameToUserMap.containsKey( lead.MASTER_SDR_Owner__c ))
                    {
                        con.ADR_Owner__c = nameToUserMap.get( lead.MASTER_SDR_Owner__c ).Id;
                        flag = true;
                    }
                }
                
                if( con.Current_Stage__c == null || con.Current_Stage__c == '' )
                {
                    con.Current_Stage__c = lead.MASTER_SDR_Stage_2__c;
                    flag = true;
                }
                
                if( con.Demo_Result__c == null || con.Demo_Result__c == '' )
                {
                    con.Demo_Result__c = lead.Demo_Rejection_Reason__c;
                    flag = true;
                }
                
                if( con.Demo_Scheduled_Date__c == null )
                {
                    con.Demo_Scheduled_Date__c = lead.Demo_Scheduled_Date__c;
                    flag = true;
                }
                
                if( flag )
                    contactsToBeUpdated.put( con.Id, con );
            }
            
            leadConverts.add(lc);
        }
        
        if( leadConverts.size() > 0 )
            Database.convertLead( leadConverts );
        
        if( accountsToBeUpdated.size() > 0 )
            update accountsToBeUpdated.values();
            
        if( contactsToBeUpdated.size() > 0 )
            update contactsToBeUpdated.values();
    }
    
    public static void scheduleLeadConversion()
    {
        Set<Id> leadIdsToScheduleAterFiveMins = new Set<Id>();
        Set<Id> leadIdsToScheduleAterThirtyMins = new Set<Id>();
        Set<Id> leadIds = new Set<Id>();
        
        for( Lead lead : newLeadList )
        {
            if( !lead.IsConverted )
            {
                if( lead.bizible2__Account__c != null )
                    leadIds.add( lead.Id );
                else if( lead.Inbound__c )
                    leadIdsToScheduleAterFiveMins.add( lead.Id );
                else
                    leadIdsToScheduleAterThirtyMins.add( lead.Id );
            }
            system.debug(leadIds);
            system.debug(leadIdsToScheduleAterFiveMins);
            system.debug(leadIdsToScheduleAterThirtyMins);
        }
        
        if( leadIds.size() > 0 )
            LeadConnectorBatch.runBatchJob( 200, '', leadIds );
        
        if( leadIdsToScheduleAterFiveMins.size() > 0 )
            convertLeadsByBatch( leadIdsToScheduleAterFiveMins, 5 );
        
        if( leadIdsToScheduleAterThirtyMins.size() > 0 )
            convertLeadsByBatch( leadIdsToScheduleAterThirtyMins, 30 );
    }
    
    @future
    private static void convertLeadsByBatch( Set<Id> leadIds, Integer mins )
    {
        // Get the new Date time instance for schedular
        Datetime nextRunInstance = Datetime.now().addMinutes( mins );
        
        // Get seconds, minutes and hours
        String seconds = String.valueOf( nextRunInstance.second());
        String minutes = String.valueOf( nextRunInstance.minute());
        String hour = String.valueOf( nextRunInstance.hour());
        String day = String.valueOf( nextRunInstance.day());
        String month = String.valueOf( nextRunInstance.month());
        String year = String.valueOf( nextRunInstance.year());
        
        // Create Schedular string and return
        String nextFireTime = seconds + ' ' + minutes + ' ' + hour + ' ' + day + ' ' + month + ' ? ' + year;
        
        LeadConversionScheduler.runSchedular( nextFireTime, leadIds );
    }
}
global with sharing class LeadConversionScheduler implements Schedulable
{
    // To store lead Id
    private Set<Id> leadIds;
    
    /**
     * Name: runSchedular
     * @param: schedularString - Time string to schedule batch
     *         leadId - Lead id to be converted
     * @return: 
     * Desc: Method which initiates the schedular class to run the Batch Class
    **/
    global static void runSchedular( String schedularString, Set<Id> leadIds )
    {
        // Create the instance of schedular class
        LeadConversionScheduler schedularInstance = new LeadConversionScheduler();
        schedularInstance.leadIds = leadIds;
        
        // Schedule the class
        System.schedule( 'Lead Conversion starts at ' + Datetime.now() + ' ' + Math.random(), schedularString, schedularInstance );
    }
    
    /**
     * Name: execute
     * @param: SC - SchedulableContext
     * @return: 
     * Desc: Schedular execution method, to process results
    **/
    global void execute( SchedulableContext SC )
    {
        // Run the Queue
        LeadConnectorBatch.runBatchJob( 200, '', leadIds );
    }
}


Thanks!!
Ashley Cobb 25Ashley Cobb 25
This is the final piece. This is a huge moster of a code and I am lost so I appreciate it!!
 
global with sharing class LeadConnectorBatch implements Database.Batchable<sObject>
{
    // To store Lead territory
    private String territoryName = '';
    private Set<Id> leadIds = new Set<Id>();
    
    private static String convertStatus;
    private static Map<String, User> nameToUserMap = new Map<String, User>();
    
    /**
     * Name: runBatchJob
     * @param: batchSize - Integer value defines the batch size.
     *         territoryName - Lead Territory Name
     * @return: 
     * Desc: Method which initiates the batch process to convert lead
    **/
    public static void runBatchJob( Integer batchSize, String territoryName, Set<Id> leadIds )
    {
        // Create the batch class instance
        LeadConnectorBatch batchToConvertLead = new LeadConnectorBatch();
        
        // Assign Territroy name
        batchToConvertLead.territoryName = territoryName;
        batchToConvertLead.leadIds = leadIds;
            
        // Execute the batch
        Id batchprocessid = Database.executeBatch( batchToConvertLead, batchSize );
    }
    
    /**
     * Name: start
     * @param: BC - Database.BatchableContext
     * @return: Database.QueryLocator - Return the list of data
     * Desc: Batch Start method, create query for the queue items
    **/
    global Database.QueryLocator start( Database.BatchableContext BC )
    {
        String query;
        
        if( leadIds.size() > 0 )
        {
            // Create query for Lead which needs to be converted
            query = 'Select Id, Email, WebSite, Phone, Title, Description, MASTER_SDR_Stage_2__c, MASTER_SDR_Notes__c, '
                        + 'MASTER_SDR_Owner__c, MASTER_SDR_Follow_Up_Date__c,   MASTER_SDR_Contact_Attempts_2__c, '
                        + 'Survey_Using_an_Agency__c, Reporting_Tools_and_Apps_in_Use__c, Survey_Name_of_Agency__c, '
                        + 'Marketing_Channels_in_Use__c, Current_Attribution_Model_in_Use__c, Survey_Agency_Services__c, '
                        + 'Snapengage__c, Intel_State__c, Territory_New__c, Intel_Country__c, Intel_City__c, '
                        + 'Demo_Rejection_Reason__c, Demo_Scheduled_Date__c, LeadSource, bizible2__Account__c From Lead '
                        + 'Where Isconverted = false and Id IN :leadIds';
        }
        else
        {
            // Create query for Lead which needs to be converted
            query = 'Select Id, Email, WebSite, Phone, Title, Description, MASTER_SDR_Stage_2__c, MASTER_SDR_Notes__c, '
                        + 'MASTER_SDR_Owner__c, MASTER_SDR_Follow_Up_Date__c,   MASTER_SDR_Contact_Attempts_2__c, '
                        + 'Survey_Using_an_Agency__c, Reporting_Tools_and_Apps_in_Use__c, Survey_Name_of_Agency__c, '
                        + 'Marketing_Channels_in_Use__c, Current_Attribution_Model_in_Use__c, Survey_Agency_Services__c, '
                        + 'Snapengage__c, Intel_State__c, Territory_New__c, Intel_Country__c, Intel_City__c, '
                        + 'Demo_Rejection_Reason__c, Demo_Scheduled_Date__c, LeadSource, bizible2__Account__c From Lead '
                        + 'Where Isconverted = false and Territory_New__c = :territoryname';
        }
        
        // Query leads which are to be processed by batch
        return Database.getQueryLocator( query );
    }
    
    /**
     * Name: execute
     * @param: BC - Database.BatchableContext
     *         leads - List of Lead for which batch is to be executed
     * @return:
     * Desc: Batch execution method, to process results
    **/
    global void execute( Database.BatchableContext BC, List<Lead> leads )
    {
        //try
        //{
            Set<String> uniqueEmails = new Set<String>();
            Set<String> uniqueWebsites = new Set<String>();
            List<Lead> uniqueLeads = new List<Lead>();
            List<Lead> existingLeads = new List<Lead>();
            List<Lead> newAccountExistingEmail = new List<Lead>();
            Set<String> userNames = new Set<String>();
            
            for( Lead lead : leads )
            {
                if( lead.Website != null && lead.Website != '' )
                {
                    if( uniqueWebsites.contains( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
                    {
                        if( lead.Email != null && lead.Email != '' )
                        {
                            if( uniqueEmails.contains( lead.Email ))
                            {
                                newAccountExistingEmail.add( lead );
                            }
                            else
                            {
                                uniqueEmails.add( lead.Email );
                                existingLeads.add( lead );
                            }
                        }
                        else
                        {
                            existingLeads.add( lead );
                        }
                    }
                    else
                    {
                        uniqueWebsites.add( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                        uniqueLeads.add( lead );
                        
                        if( lead.Email != null && lead.Email != '' )
                        {
                            uniqueEmails.add( lead.Email );
                        }
                    }
                }
                else if( lead.Email != null && lead.Email != '' )
                {
                    if( uniqueEmails.contains( lead.Email ))
                    {
                        existingLeads.add( lead );
                    }
                    else
                    {
                        uniqueEmails.add( lead.Email );
                        uniqueLeads.add( lead );
                    }
                }
                else
                {
                    uniqueLeads.add( lead );
                }
                
                if( lead.MASTER_SDR_Owner__c != null && lead.MASTER_SDR_Owner__c != '' )
                    userNames.add( lead.MASTER_SDR_Owner__c );
            }
            
            LeadStatus convertStatuses = [ Select MasterLabel from LeadStatus where IsConverted = true limit 1 ];
            convertStatus = convertStatuses.MasterLabel;
            
            for( User u : [ Select Id, Name from User where Name IN :userNames ])
            {
                nameToUserMap.put( u.Name, u );
            }
            
            convertLeads( uniqueLeads );
            convertLeads( existingLeads );
            convertLeads( newAccountExistingEmail );
        /*}
        catch( Exception e )
        {
            system.debug( 'Error********************' + e.getMessage() + ':::::::::::::::' + e.getLineNumber() );
        }*/
    }
    
    /**
     * Name: finish
     * @param: BC - Database.BatchableContext
     * @return:
     * Desc: Batch finish method
    **/
    global void finish( Database.BatchableContext BC )
    {
    }
    
    private void convertLeads( List<Lead> leadsToBeconverted )
    {
        Set<String> emailAddressSet = new Set<String>();
        Set<Id> accountIds = new Set<Id>();
        Set<String> webSiteSet = new Set<String>();
        
        for( Lead lead : leadsToBeconverted )
        {
            if( lead.bizible2__Account__c != null )
                accountIds.add( lead.bizible2__Account__c );
            else if( lead.Website != null && lead.Website != '' )
                webSiteSet.add( '%' + lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                   
            if( lead.Email != null && lead.Email != '' )
                emailAddressSet.add( lead.Email );
        }
        
        Map<Id, Account> accountMap = new Map<Id, Account>([ Select Id, Website, Phone, Description, Intel_City__c,
                                                                Intel_Country__c, Intel_State__c, Territory_New__c,
                                                                ( Select Id, Email, Phone, Title, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                                                                    Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                                                                    Survey_Using_an_Agency__c, Calls_Made__c, Follow_up_Date__c, Relevant_ADR_Notes__c, ADR_Owner__c, Current_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                                                                    LeadSource from Contacts where Email IN :emailAddressSet )
                                                                from Account where Id IN :accountIds ]);
        
        Map<String, List<Account>> websiteToAccountMap = new Map<String, List<Account>>();
        for( Account acc : [ Select Id, Website, Phone, Description, Intel_City__c, Intel_Country__c, Intel_State__c,
                                ( Select Id, Email, Phone, Title, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                                Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                                Survey_Using_an_Agency__c, Calls_Made__c, Follow_up_Date__c, Relevant_ADR_Notes__c, ADR_Owner__c, Current_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, Demo_Result__c, 
                                LeadSource from Contacts where Email IN :emailAddressSet ),
                                Territory_New__c from Account where Website like :webSiteSet ])
        {
            List<Account> accs = new List<Account>();
            if( websiteToAccountMap.containsKey( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
            {
                accs = websiteToAccountMap.get( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
            }
            
            accs.add( acc );
            websiteToAccountMap.put( acc.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ), accs );
        }
        
        /*Map<String, Contact> emailAddressToContactMap = new Map<String, Contact>();
        for( Contact con : [ Select Id, Email, Phone, Description, Survey_Agency_Services__c, Survey_Current_Attribution_Model__c,
                            Survey_Marketing_Channels_in_Use__c, Survey_Name_of_Agency__c, Survey_Reporting_Tools_and_Apps_in_Use__c,
                            Survey_Using_an_Agency__c, MASTER_SDR_Contact_Attempts__c, MASTER_SDR_Follow_Up_Date__c, MASTER_SDR_Notes__c,
                            MASTER_SDR_Owner__c, MASTER_SDR_Stage__c, Snapengage__c, Demo_Scheduled_Date__c, 
                            Demo_Result__c,LeadSource from Contact where Email IN :emailAddressSet ])
        {
            emailAddressToContactMap.put( con.Email, con );
        }*/
        
        List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
        Map<Id, Account> accountsToBeUpdated = new Map<Id, Account>();
        Map<Id, Contact> contactsToBeUpdated = new Map<Id, Contact>();
        List<Lead> leadsToBeUpdated = new List<Lead>();
        
        for( Lead lead : leadsToBeconverted )
        {
            Lead l = new Lead( Id = lead.Id, Convert__c = true );
            leadsToBeUpdated.add( l );
            
            Database.LeadConvert lc = new Database.LeadConvert();
            lc.setDoNotCreateOpportunity( true );
            lc.setLeadId( lead.Id );
            lc.setConvertedStatus( convertStatus );
            
            Account acc;
            Contact con;
            if( lead.bizible2__Account__c != null && accountMap.containsKey( lead.bizible2__Account__c ))
            {
                acc = accountMap.get( lead.bizible2__Account__c );
                
                if( lead.Email != null && lead.Email != '' )
                {
                    for( Contact c : acc.Contacts )
                    {
                        if( c.Email != null && c.Email != '' && c.Email.equalsIgnoreCase( lead.Email ))
                        {
                            con = c;
                            break;
                        }
                    }
                }
            }
            else if( lead.Website != null && lead.WebSite != ''
                        && websiteToAccountMap.containsKey( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' )))
            {
                List<Account> accounts = websiteToAccountMap.get( lead.Website.replace( 'https://', '' ).replace( 'http://', '' ).replace( 'www.', '' ));
                
                if( lead.Email != null && lead.Email != '' )
                {
                    for( Account a : accounts )
                    {
                        for( Contact c : a.Contacts )
                        {
                            if( c.Email != null && c.Email != '' && c.Email.equalsIgnoreCase( lead.Email ))
                            {
                                acc = a;
                                con = c;
                                break;
                            }
                        }
                        
                        if( acc != null )
                            break;
                    }
                    
                    if( acc == null )
                        acc = accounts[0];
                }
            }
            
            if( acc != null )
            {
                lc.setAccountId( acc.Id );
                Boolean flag = false;
                
                if( acc.Phone == null || acc.Phone == '' )
                {
                    acc.Phone = lead.Phone;
                    flag = true;
                }
                
                if( acc.Description == null || acc.Description == '' )
                {
                    acc.Description = lead.Description;
                    flag = true;
                }
                
                if( acc.Intel_City__c == null || acc.Intel_City__c == '' )
                {
                    acc.Intel_City__c = lead.Intel_City__c;
                    flag = true;
                }
                
                if( acc.Intel_Country__c == null || acc.Intel_Country__c == '' )
                {
                    acc.Intel_Country__c = lead.Intel_Country__c;
                    flag = true;
                }
                
                if( acc.Territory_New__c == null || acc.Territory_New__c == '' )
                {
                    acc.Territory_New__c = lead.Territory_New__c;
                    flag = true;
                }
                
                if( acc.Intel_State__c == null || acc.Intel_State__c == '' )
                {
                    acc.Intel_State__c = lead.Intel_State__c;
                    flag = true;
                }
                
                if( flag )
                    accountsToBeUpdated.put( acc.Id, acc );
            }
            
            if( con != null )
            {
                lc.setContactId( con.Id );
                Boolean flag = false;
                //Contact con = emailAddressToContactMap.get( lead.Email );
                
                if( con.Phone == null || con.Phone == '' )
                {
                    con.Phone = lead.Phone;
                    flag = true;
                }
                
                if( con.Title == null || con.Title == '' )
                {
                    con.Title = lead.Title;
                    flag = true;
                }
                
                if( con.LeadSource == null || con.LeadSource == '' )
                {
                    con.LeadSource = lead.LeadSource;
                    flag = true;
                }
                
                if( con.Description == null || con.Description == '' )
                {
                    con.Description = lead.Description;
                    flag = true;
                }
                
                if( !con.Snapengage__c )
                {
                    con.Snapengage__c = lead.Snapengage__c;
                    flag = true;
                }
                
                if( con.Survey_Agency_Services__c == null || con.Survey_Agency_Services__c == '' )
                {
                    con.Survey_Agency_Services__c = lead.Survey_Agency_Services__c;
                    flag = true;
                }
                
                if( con.Survey_Current_Attribution_Model__c == null || con.Survey_Current_Attribution_Model__c == '' )
                {
                    con.Survey_Current_Attribution_Model__c = lead.Current_Attribution_Model_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Marketing_Channels_in_Use__c == null || con.Survey_Marketing_Channels_in_Use__c == '' )
                {
                    con.Survey_Marketing_Channels_in_Use__c = lead.Marketing_Channels_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Name_of_Agency__c == null || con.Survey_Name_of_Agency__c == '' )
                {
                    con.Survey_Name_of_Agency__c = lead.Survey_Name_of_Agency__c;
                    flag = true;
                }
                
                if( con.Survey_Reporting_Tools_and_Apps_in_Use__c == null || con.Survey_Reporting_Tools_and_Apps_in_Use__c == '' )
                {
                    con.Survey_Reporting_Tools_and_Apps_in_Use__c = lead.Reporting_Tools_and_Apps_in_Use__c;
                    flag = true;
                }
                
                if( con.Survey_Using_an_Agency__c == null || con.Survey_Using_an_Agency__c == '' )
                {
                    con.Survey_Using_an_Agency__c = lead.Survey_Using_an_Agency__c;
                    flag = true;
                }
                
                if( con.Calls_Made__c == null || con.Calls_Made__c == '' )
                {
                    con.Calls_Made__c = lead.MASTER_SDR_Contact_Attempts_2__c;
                    flag = true;
                }
                
                if( con.Follow_up_Date__c == null )
                {
                    con.Follow_up_Date__c = lead.MASTER_SDR_Follow_Up_Date__c;
                    flag = true;
                }
                
                if( con.Relevant_ADR_Notes__c == null || con.Relevant_ADR_Notes__c == '' )
                {
                    con.Relevant_ADR_Notes__c = lead.MASTER_SDR_Notes__c;
                    flag = true;
                }
                
                if( con.ADR_Owner__c == null )
                {
                    if( lead.MASTER_SDR_Owner__c != null && lead.MASTER_SDR_Owner__c != '' && nameToUserMap.containsKey( lead.MASTER_SDR_Owner__c ))
                    {
                        con.ADR_Owner__c = nameToUserMap.get( lead.MASTER_SDR_Owner__c ).Id;
                        flag = true;
                    }
                }
                
                if( con.Current_Stage__c == null || con.Current_Stage__c == '' )
                {
                    con.Current_Stage__c = lead.MASTER_SDR_Stage_2__c;
                    flag = true;
                }
                
                if( con.Demo_Result__c == null || con.Demo_Result__c == '' )
                {
                    con.Demo_Result__c = lead.Demo_Rejection_Reason__c;
                    flag = true;
                }
                
                if( con.Demo_Scheduled_Date__c == null )
                {
                    con.Demo_Scheduled_Date__c = lead.Demo_Scheduled_Date__c;
                    flag = true;
                }
                
                if( flag )
                    contactsToBeUpdated.put( con.Id, con );
            }
            
            leadConverts.add(lc);
        }
        
        if( leadConverts.size() > 0 )
            Database.convertLead( leadConverts );
        
        if( accountsToBeUpdated.size() > 0 )
            update accountsToBeUpdated.values();
            
        if( contactsToBeUpdated.size() > 0 )
            update contactsToBeUpdated.values();
        
        if( leadsToBeUpdated.size() > 0 )
        {
            LeadTriggerHelper.runTrigger = false;
            update leadsToBeUpdated;
            LeadTriggerHelper.runTrigger = true;
        }
    }
}