1

I have a custom lead covert functionality in apex. I am using salesforce provided lead convert methods to convert lead.

With this i also have duplicate rules for Accounts and Contacts. The issue here is whenever i am firing lead convert, i am getting either account or contact duplicate rule is getting fired.

So to check this one.. I created a record which has both duplicate and contact records. I deactivated account duplicate rule. Now i can see contact duplicate records.

Below is my code. What modification i can do so that both account and contact duplicate rule should fire and i can get both the Account and contact duplicate records

Below method is fired from LWC

@AuraEnabled
public static Result convertLeads(String leadId, String accountId, String contactId, Boolean bypassDupeCheck) {
    Result result = new Result();
    result.isSuccess = true;
    result.isDupe = false;         
    Result leadResult = leadConvert(leadId, accountId, contactId, bypassDupeCheck);
    
    result.accountId = leadResult.convertedAccountId;
    result.opportunityId = leadResult.convertedOppId;
    result.contactId = leadResult.convertedcontactId;
    result.accountLists = leadResult.accountLists;
    result.contactLists = leadResult.contactLists;
    system.debug(result.contactLists);
    result.columnsLists =  leadResult.columnsLists;
    result.message = leadResult.errorMessage;
    
    if(result.accountLists != null || result.contactLists != null ){
        result.isDupe = true;
    }
    
    if(leadResult.convertedAccountId == null){
        result.isSuccess = false;
    }
    
    return result;
}

leadConvert method -

  public static Result leadConvert(String leadId, String accountId, String contactId, Boolean dupeBypass)
    {
        
        If(!String.isEmpty(contactId) && String.isEmpty(accountId)){
            
            Contact cont = [SELECT Id, FirstName, LastName, Email, MobilePhone, AccountId, Name
                            FROM Contact WHERE Id =:contactId];
            accountId = cont.AccountId;
        }

        LeadStatus CLeadStatus= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 1];
        Database.LeadConvert leadconvert = new Database.LeadConvert();
        leadconvert.setLeadId(leadId);
        leadconvert.setAccountId(accountId);
        leadconvert.setContactId(contactId);                   
        leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
        leadconvert.setDoNotCreateOpportunity(false); 
        Database.LeadConvertResult lcr;            
        if(dupeBypass){ 
**> /*dupeBypass, this will become true whenever i select a record from UI
> and*/**
            Database.DMLOptions dml = new Database.DMLOptions(); 
            dml.DuplicateRuleHeader.AllowSave = true;
            dml.optAllOrNone = false;
            lcr = Database.convertLead(leadconvert, dml);
        } else {
            lcr = Database.convertLead(leadconvert, false);
            system.debug(lcr.getErrors());
        }
        
        Result result;
        
        if(lcr.isSuccess()){
            result = new Result();
            result.convertedAccountId = lcr.getAccountId();
            result.convertedOppId = lcr.getOpportunityId();
            result.convertedcontactId = lcr.getContactId();
        } else {
            result = getDupes(lcr);
        }
        
        return result;
    }

getDupes() method

 private static Result getDupes(Database.LeadConvertResult lcr){
        
        Set<Id> setDuplicateIds = new Set<id>();
        Datacloud.DuplicateResult duplicateResult;
        List<String> errorMessages = new List<String>();
        
        // Insertion failed due to duplicate detected
        for(Database.Error error : lcr.getErrors()){
            
            errorMessages.add(error.getMessage());
            
            if (error instanceof Database.DuplicateError) {
                duplicateResult = ((Database.DuplicateError)error).getDuplicateResult();
                system.debug(duplicateResult.getDuplicateRule()); **/*At this place i get only one duplicate rule name */**
                // Fetch the Ids of the existing duplicate records
                for(Datacloud.MatchResult duplicateMatchResult : duplicateResult.getMatchResults()) {
                    for(Datacloud.MatchRecord duplicateMatchRecord : duplicateMatchResult.getMatchRecords()) {
                        setDuplicateIds.add(duplicateMatchRecord.getRecord().Id);
                    }
                }
            }
        }
        
        Result results = getDupeAccountsAndContacts(setDuplicateIds);
        results.errorMessage = String.Join(errorMessages, ', ');
        
        return results;
    }

getDupeAccountsAndContacts --> Method

 private static Result getDupeAccountsAndContacts(Set<Id> dupeIds){
        system.debug(dupeIds);
        Result result = new Result();
        List<Schema.FieldSetMember> lstreadFieldSet = readFieldSet('SE_Lead_Convert_Duplicate_Check', 'Account');
       // system.debug('lstreadFieldSet' + lstreadFieldSet);
        String query = 'SELECT ';
        result.columnsLists = new List<columns>();
        for(Schema.FieldSetMember fieldSetMemberObj : lstreadFieldSet){
           // system.debug('Label ====>' + fieldSetMemberObj.getSObjectField());
            result.columnsLists.add(new columns(fieldSetMemberObj.getLabel(), String.valueof(fieldSetMemberObj.getSObjectField()), null));
          //  system.debug('Label ====>' + result.columnsLists);
            query += fieldSetMemberObj.getFieldPath() + ', ';
        }

        Set<Id> accountIds = new Set<Id>();
        Set<Id> contactIds = new Set<Id>();
        
        for(Id i:dupeIds){
            Schema.SObjectType sobjectType = i.getSObjectType();
            String sobjectName = sobjectType.getDescribe().getName();
            if(sobjectName == 'Account'){
                accountIds.add(i);
            } else if (sobjectName == 'Contact'){
                contactIds.add(i);
                system.debug(contactIds);
            } 
        }
        query += 'Id FROM Account WHERE Id IN: accountIds';
        
        result.accountLists = Database.query(query);     
        system.debug(result.accountLists);
        //result.accountLists = [SELECT Id, Name, ShippingStreet, ShippingCity, ShippingState, ShippingPostalCode, 
                          //    ShippingCountry, Industry, Phone FROM Account WHERE Id IN: accountIds];        
        result.contactLists = [SELECT Id, FirstName, LastName, Email, MobilePhone, AccountId, Name, Account.Name
                            FROM Contact WHERE Id IN: contactIds];
        system.debug(result.contactLists);
        
        return result;
    }
1
  • You can use the Apex FindDuplicates class to handle duplicate checking and matching in your code. Aug 10, 2021 at 19:08

0

You must log in to answer this question.

Browse other questions tagged .