[SalesForce] Convert lead failure- Cannot update converted lead

Line: 128, Column: 1

System.DmlException: ConvertLead failed. First exception on row 70; first error: CANNOT_UPDATE_CONVERTED_LEAD, cannot reference converted lead: []

Got above Error from Below Code.

 public class Test_SL_Batch_Match_LeadsWithAccounts {
    
    public static List <Opportunity> oppListToUpdateFlag;
    public static map<Id,Account> accountMap = new map<Id,Account>();
    public static id leadRecordTypeId = Schema.SObjectType.Lead.getRecordTypeInfosByName().get('Sun Homes - LPS').getRecordTypeId();
    
    Public Static String getOppFlagNew()
    {
        oppListToUpdateFlag = new List<Opportunity>();
        List <Opportunity> oppList = new List <Opportunity>([Select AccountId, Flag__c from Opportunity where flag__c = 'New' AND Batch_Flag__c = null Limit 100]);
        for(Opportunity opp : oppList){
            accountMap.put(opp.AccountId, null);
            opp.Batch_Flag__c = 'Processed';
            oppListToUpdateFlag.add(opp);
        }
        accountMap.remove(null);
        accountMap.putAll([Select Name, Phone, PersonEmail, OwnerId From Account Where ID In : accountMap.keyset()]);
        
        List <String> acctAndLeadIdList = new List <String>();
        List <String> accountNameList = new LIST <String>();
        List <String> accountPhoneList = new LIST <String>();
        List <String> accountEmailList = new LIST <String>();
        
        for(Account acc : accountMap.values()){
            String tempName = acc.Name;
            accountNameList.add(tempName);
            String tempPhone = acc.Phone;
            accountPhoneList.add(tempPhone);
            String tempPersonEmail = acc.PersonEmail;
            accountEmailList.add(tempPersonEmail);
        }
        Map<ID, Lead> leadMap = new Map<ID, Lead>([Select Name, Phone, Email, IsConverted from Lead Where 
                                                       Name  =:accountNameList//]);
                                                       AND (Phone =:accountPhoneList//]); 
                                                        OR Email =:accountEmailList)//]);
                                                       AND RecordTypeId =: leadRecordTypeId
                                                       AND IsConverted != true]);
        System.debug(leadMap);
        Integer count = 0;
        for(ID leadId : leadMap.keySet()){
            String leadPhone = leadMap.get(leadId).Phone;
            if (leadPhone != null)
            {
                if(!leadPhone.isNumeric())
                {
                    leadPhone = leadPhone.trim();
                    leadPhone = getNumeric(leadPhone);
                }
            }
            //System.debug('This is Lead phone' + leadPhone);
            
            String leadEmail = leadMap.get(leadId).Email;
            if(leadEmail != null){leadEmail = leadEmail.trim();}
            
            for(ID acctID : accountMap.keySet()){
                String accountPhone = accountMap.get(acctID).Phone;
                if(accountPhone != null)
                {
                    if(!accountPhone.isNumeric())
                    {
                        accountPhone = accountPhone.trim();
                        accountPhone = getNumeric(accountPhone);
                    }
                } 
                String accountPersonEmail = accountMap.get(acctID).PersonEmail;
                if(accountPersonEmail != null){accountPersonEmail = accountPersonEmail.trim();}
               
                if(leadMap.get(leadId).Name == accountMap.get(acctID).Name )
                {
                    //System.debug('This is Account phone' + accountPhone);
                    //System.debug('Name Matched');
                    String temp;
                    if(leadPhone == accountPhone)
                    {
                        count += 1;
                        //System.debug('Phone is Matched');
                        temp = 'accId'+accountMap.get(acctID).Id+'accId'+'-'+'leadId'+leadMap.get(leadId).Id+'leadId'+'-'+'ownerId'+accountMap.get(acctID).OwnerId+'ownerId';
                        acctAndLeadIdList.add(temp);
                        //System.debug(temp + '\n');
                    }
                    else if(leadEmail == accountPersonEmail)
                    {    
                        count += 1;
                        //System.debug('Email is matched');
                        temp = 'accId'+accountMap.get(acctID).Id+'accId'+'-'+'leadId'+leadMap.get(leadId).Id+'leadId'+'-'+'ownerId'+accountMap.get(acctID).OwnerId+'ownerId';
                        acctAndLeadIdList.add(temp);
                        //System.debug(temp + '\n');
                    }
                }
                
            }
            //System.debug('Nothing matched');
        }
        //System.debug(acctAndLeadIdList);
        System.debug(count);
        if(!acctAndLeadIdList.isEmpty()){
            mergLeadWithExistingAccount(acctAndLeadIdList);
        }
        if(!oppListToUpdateFlag.isEmpty()){
            try
            {
                update oppListToUpdateFlag;
            }
            catch (Exception e)
            {
                System.debug(e);
            }
        }
        
        System.debug(leadRecordTypeId);
        return null;
    }
    public static void mergLeadWithExistingAccount(List <String> acctAndLeadIdListRecieved){
        list<Database.LeadConvert> leadConverts = new list<Database.LeadConvert>();
        Integer count = 0;
        for(String acctAndLeadId: acctAndLeadIdListRecieved){
            String tempAcctId = acctAndLeadId.substringBetween('accId');
            String tempLeadId = acctAndLeadId.substringBetween('leadId');
            String tempOwnerId = acctAndLeadId.substringBetween('ownerId');
            Database.LeadConvert lc = new database.LeadConvert();
            lc.setLeadId(tempLeadId);
            lc.setAccountId(tempAcctId);
            lc.setOwnerId(tempOwnerId);
            lc.setConvertedStatus('Application Submitted');
            lc.setDoNotCreateOpportunity(true);
            leadConverts.add(lc);
        }
        List <Database.LeadConvertResult> results = Database.convertLead(leadConverts);
        for(Integer i=0; i < results.size(); i++){
        System.assert(results[i].isSuccess());
        count += 1;
        }
        System.debug(' '+count+' Leads are Converted');
        System.debug(results);
    }
    
    public static String getNumeric(String anyValue)
    {
        String str = anyValue;
        String numericString = '';
        integer strLength = str.length();
        for(integer i =0;i<str.length();i++){
            String s= str.mid(i,1);
            if(s.isNumeric()){
                numericString +=s;
            }
        }
        return numericString;
    }
}

Best Answer

There are two following possible solutions to this problem.

  1. Add @future annotation before below function. What exactly it will do is assign a different thread to execute your function which is taking too much time to execute.

If first Solution has not worked fine for you then there is something wrong in your Lead data. In that case try the second one.

  1. try this 'List results =Database.convertLead(leadConverts, false);'
    instead of 'List results = Database.convertLead(leadConverts);'

    The reason behind using false in the Database.convertLead is to allow partial success i.e if there is problem with some Lead then skip it and go to next to execute the whole list of leadConverts. After that you can iterate the result set and you can easily figure out why that specific Lead conversion fail.

    @future public static void mergLeadWithExistingAccount(List <String> acctAndLeadIdListRecieved){ list<Database.LeadConvert> leadConverts = new list<Database.LeadConvert>(); Integer count = 0; for(String acctAndLeadId: acctAndLeadIdListRecieved){ String tempAcctId = acctAndLeadId.substringBetween('accId'); String tempLeadId = acctAndLeadId.substringBetween('leadId'); String tempOwnerId = acctAndLeadId.substringBetween('ownerId'); Database.LeadConvert lc = new database.LeadConvert(); lc.setLeadId(tempLeadId); lc.setAccountId(tempAcctId); lc.setOwnerId(tempOwnerId); lc.setConvertedStatus('Application Submitted'); lc.setDoNotCreateOpportunity(true); leadConverts.add(lc); } List <Database.LeadConvertResult> results = Database.convertLead(leadConverts, false); for (Database.LeadConvertResult lcr : results) { if(!lcr.isSuccess()) { count += 1; showErrorMsg(lcr.getErrors(), 'Lead conversion error'); } } System.debug(' '+count+' Leads are not Converted'); //System.debug(results); } public static void showErrorMsg(List<Database.Error> errorList, String firstLine) { String errors = firstLine + '\n'; for(Database.Error e : errorList) { errors += e.statusCode + ': ' + e.message + '\n'; } System.debug(errors); }

Related Topic