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
iKnowSFDCiKnowSFDC 

Convert Lead and attach to existing Account if Available - Having trouble with Query

I'm working on a solution to convert leads automatically to Account/Contacts/Opportunities. The process is as follows: 

 

1. Lead with Lead Source = "Deal Registration" inserted (Trigger after insert puts them into set<id> and passes to class/static method. 

2. Query Opportunity object, looking for existing open opportunity for company name/city/state combination

3. If none exists, query Account object looking for matching account/city/state combination 

4. If Account exists, look for matching contact, if none exists insert new contact

5. If Account exists, insert opportunity for account and if contact exists set as contact role on opportunity,

         ELSE insert Account and Contact and insert opportunity 

 

I can get the lead convert working and can add the opportunity to the account if the account name matches exactly. I know I need to use a SOSL query to look for a matching account to my lead, however, I can only figure out how to do this one record at a time - I can't figure out how to bulkify this. Any help you can offer me would be greatly appreciated!

 

My setup code is below: 

 

/**************************
Use to determine if the deal reg is valid, then call convertLead to do the conversion work
**************************/

public class dealRegHandling{
    
    public static void dealRegProcess(Set<id> dealRegIds){
     	List<Lead> dealRegs = [SELECT id, Name, FirstName, LastName, Email, Phone, Registered_Partner_Preferred_Partner__c,
                               Registering_Rep__c, Registering_Rep_Email__c, Registering_Rep_Name__c,Deal_Registration_Status__c,
                               Deal_Registration_Product__c, Deal_Registration_Expiration_Date__c, City, State, PostalCode,
                               Company
                               FROM Lead WHERE id IN :dealRegIds];
        
        List<Opportunity> regdOpptys = [SELECT id, AccountId, Account.Name, Account.BillingState, Account.BillingCity, 
                                        Registered_Partner_Preferred_Partner__c, Registering_Rep__c, Registering_Rep_Email__c, 
                                        Deal_Registration_Status__c, Deal_Registration_Product__c, 
                                        Deal_Registration_Expiration_Date__c 
                                        FROM Opportunity WHERE isClosed = False
                                        AND Registered_Partner_Preferred_Partner__c != NULL];
        
        Map<String, Opportunity> openOpptys = new Map<String, Opportunity>();
        for(Opportunity o : regdOpptys){
            String opptyKey = o.Account.Name.remove(' ').toLowerCase() + o.Account.BillingCity + o.Account.BillingState;
            system.debug('opportunity search key>>>'+opptyKey);
            openOpptys.put(opptyKey, o);
		}
        List<Lead> leadsToConvert = new List<Lead>();
        List<Lead> leadsToUpdate = new List<Lead>();
        map<id, boolean> leadToWhat = new map<Id, boolean>();
        for(Lead l : dealRegs){
            String leadKey = l.Company.remove(' ').toLowerCase() +  l.City + l.State;
            system.debug('lead search key is >>>'+leadKey);
            system.debug('lead search result is>>>'+openOpptys.get(leadKey));
            Boolean matchedDR = false;
            if(openOpptys.get(leadKey) == NULL){
                matchedDR = false;
                l.Deal_Registration_Status__c = 'Approved';
                leadToWhat.put(l.id, matchedDR);
                leadsToUpdate.add(l);
                leadsToConvert.add(l);
            } else {
                matchedDR = true;
                l.Deal_Registration_Status__c = 'Denied';
                leadToWhat.put(l.id, matchedDR);
                leadsToUpdate.add(l);
            }
        }
        update leadsToUpdate;
        convertLead con = new convertLead();
        con.convertLeads(leadToWhat, leadsToConvert);
    }
}

 My conversion code is here: 

public class convertLead{

    public void convertLeads(map<id, boolean> matchedAcct, List<Lead> leadsToConvert){
        
        for(Lead l : leadsToConvert){
            
            Database.leadConvert lc = new Database.LeadConvert();
                lc.setLeadId(l.id);
                
                LeadStatus convertStatus = [SELECT id, MasterLabel FROM LeadStatus WHERE IsConverted = True LIMIT 1];
                lc.setConvertedStatus(convertStatus.MasterLabel);
                Date close = date.today().addDays(30);
                lc.setOpportunityName(l.Registered_Partner_Preferred_Partner__c + ' - ' + l.Name + ' - ' + close);
                
            if(matchedAcct.get(l.id) == true){
                Id acctId = [SELECT id, Name FROM Account WHERE Name LIKE :l.Company AND BillingState = :l.State].id;
                lc.setAccountId(acctId);
                Id contactId = [SELECT id FROM Contact WHERE LastName like :l.LastName AND Email = :l.email].id;
                lc.setContactId(contactId);
            }
            Database.LeadConvertResult lcr = Database.convertLead(lc);
            system.assert(lcr.isSuccess());
            system.debug('lead converted>>>'+lcr.isSuccess());
            }
    }
}

 

Best Answer chosen by Admin (Salesforce Developers) 
nj07nj07

Hi Joan,

 

You would need to make below changes in your  convertLead class.

 

public class convertLead{

public void convertLeads(map<id, boolean> matchedAcct, List<Lead> leadsToConvert){
Set<String> setName = new Set<String>();
Set<String> setBillingState = new Set<String>();
Set<String> setLastName = new Set<String>();
Set<String> setEmail = new Set<String>();
Map<String, List<Id>> mapAccKey = new List<String, List<Id>>();
Map<String, List<Id>> mapContactKey = new List<String, List<Id>>();
Map<Id, Id> mapLeadAccounts = new Map<Id, Id>();
Map<Id, Id> mapLeadContacts = new Map<Id, Id>();
for(Lead l : leadsToConvert)
{
if(matchedAcct.get(l.id) == true)
{
String strAccKey = l.Company + ',' + l.State;
String strConKey = l.LastName + ',' + l.email;
setName.add(l.Company);
setBillingState.add(l.State);
setLastName.add(l.LastName);
setEmail.add(l.email);

if(strAccKey != null && strAccKey != '' && mapAccKey.containsKey(strAccKey))
mapAccKey.get(strAccKey),add(l.Id);
else if(strAccKey != null && strAccKey != '')
mapAccKey.put(strAccKey, new List<Id>{l.Id});

if(strConKey != null && strConKey != '' && mapContactKey.containsKey(strConKey))
mapContactKey.get(strConKey),add(l.Id);
else if(strConKey != null && strConKey != '')
mapContactKey.put(strConKey, new List<Id>{l.Id});
}
}
for(Account objAcc : [SELECT id, Name, BillingState FROM Account WHERE Name IN :setName AND BillingState IN : setBillingState])
{
String strAccKey = objAcc.Name + ',' + objAcc.BillingState;
if(mapAccKey != null && mapAccKey.containsKey(strAccKey) && mapAccKey.get(strAccKey) != null)
{
for(Id objLeadId : mapAccKey.get(strAccKey))
mapLeadAccounts.put(objLeadId, objAcc,Id);
}
}
for(Contact objCon : [SELECT id, LastName, Email FROM Contact WHERE LastName IN :setLastName AND Email IN :setEmail])
{
String strConKey = objCon.LastName + ',' + objCon.Email;
if(mapContactKey != null && mapContactKey.containsKey(strConKey) && mapContactKey.get(strConKey) != null)
{
for(Id objLeadId : mapContactKey.get(strConKey))
mapLeadContacts.put(objLeadId, objCon,Id);
}

 

}
List<Database.LeadConvert> leadConversions = new List<Database.LeadConvert>();
LeadStatus convertStatus = [SELECT id, MasterLabel FROM LeadStatus WHERE IsConverted = True LIMIT 1];
for(Lead l : leadsToConvert)
{
Database.leadConvert lc = new Database.LeadConvert();
lc.setLeadId(l.id);
lc.setConvertedStatus(convertStatus.MasterLabel);
Date close = date.today().addDays(30);
lc.setOpportunityName(l.Registered_Partner_Preferred_Partner__c + ' - ' + l.Name + ' - ' + close);

if(matchedAcct.get(l.id) == true)
{
if(mapLeadAccounts != null && mapLeadAccounts.containsKey(l.id))
lc.setAccountId(mapLeadAccounts.get(l.Id));
if(mapLeadContacts != null && mapLeadContacts.containsKey(l.id))
lc.setContactId(mapLeadContacts.get(l.Id));
}
leadConversions.add(lc);
}
List<Database.LeadConvertResult> results = Database.convertLead( leadConversions);
System.assert(results[0].isSuccess());
}
}

 

If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

 

Thanks,

Nilesh Jain