[SalesForce] Converting Multiple Leads in apex

I am trying to convert multiple leads in apex. Here is the process i am following.

First check there is an account / contact similar to the lead,
if there is then assign the accountid in the leadconvert record else leave them blank so that a new account is created.

This works fine, till the point where i dont have a similar account in the system but there are similar leads. For example i have leads with different names but with same company. So now if i convert the lead i have multiple duplicate accounts because when i do a duplicate account check before the conversion, the accounts dont exist and i dont set the setAccountId and when the first leadconvert record gets converted, new account gets created, the second leadconvert record with same company is converted it also creates a new account. Since i am converting multiple leads in list i dont want to be doing the check every leadconvert record just before the conversion for the fear of hitting the governor limits.

Can anyone think of an alternate way to avoid duplicate accounts if there are similar company leads

Best Answer

Prady, without knowing exactly how you've implemented your business logic, I suggest the following approach, which may be least disruptive to your existing code: Create a utility method (e.g., LeadUtil.mapAccountIds()) that takes a List<Lead> parameter and returns a Map<Id, Id>.

The idea is that LeadUtil.mapAccountIds() performs a few key functions:

  1. Compile a unique set of expected Account records, based on values in the given leads. For example, if you have two leads with Company being "Acme Corporation", the unique set should only contain one item for "Acme Corporation".
  2. Search the system for matching Account records
  3. For any remaining expected Account records that were not found, meaning that these are net-new accounts, create new Account records
  4. Map the Account IDs of the matching Account records and newly created Account records to the given leads, using each Lead ID as a key
  5. Return the map of Account IDs

Then, in your existing code, all you need to do is:

// Map the leads to accounts for conversion
Map<Id, Id> accountIdsByLeadId =
    LeadUtil.mapAccountIds(selectedLeads);

// Use the map of Account IDs to inform the
// conversion of the selected leads
...
Related Topic