We have an Apex trigger that automatically converts a lead to a PersonAccount. We want to make sure that if there is already a PersonAccount with an email that matches that of the lead that we merge the lead with that existing PersonAccount.
We have the attached code running and in Sandbox it works. However, in live production environment it yields inconsistent results when used with web-to-lead, often creating duplicate PersonAccounts. I.e. even though there is an existing PersonAccount with an email address that matches that of the lead, the lead is not merged with it.
Any ideas why this might be happening? There are no other apps running in production.
trigger ConvertLeadToPersonAccountCheckDupesTrigger on Lead (after insert, after update) {
List<Lead> newLeads = [select Id, isConverted, Email from Lead where Id IN :trigger.new];
Set<Id> leads = new Set<Id>();
Set<String> leademails = new Set<String>();
for(Lead l : newLeads){
leads.add(l.Id);
leademails.add(l.email);
}
List<LeadStatus> convertedLeadStatuses = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
Map<Id, String> leadstatuses = new Map<Id, String>();
for(LeadStatus ls : convertedLeadStatuses){
leadstatuses.put(ls.Id, ls.MasterLabel);
}
List<Account> AccountList = [select Id,PersonEmail from Account where PersonEmail in: leademails];
Map<String, ID> accounts = new Map<String, ID>();
for(Account a : AccountList){
accounts.put(a.PersonEmail, a.Id);
}
Id DupeAccountId=null;
for (Lead lead : newleads) {
if (lead.isConverted == false) //to prevent recursion
{
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(lead.Id);
DupeAccountId = null;
DupeAccountId = accounts.get(lead.Email);
if (DupeAccountId != null) {
lc.setAccountId(DupeAccountId);
}
lc.setDoNotCreateOpportunity(true);
lc.setConvertedStatus(convertedLeadStatuses[0].MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());
}
}
}