0

Error on Line 154: Update failed. First exception on row 0 with id ******; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, LeadTrigger: maximum trigger depth exceeded

public class MatchLeadsToHCPOnInsert {  
    @InvocableMethod
    public static void getHCPonInsert(List<Lead> Leads){
        Set<Id> Ids = new Set<Id>();
        for(Lead l: Leads){Ids.add(l.Id);}
        List<Lead> NewLeads = [Select Id, Latitude, Longitude from Lead where Id in: Ids];

    Account HCPAssigned;
    List<Account> HCPsInDefinedShorterRadius = new List<Account>();
    List<Account> HCPsInDefinedLongerRadius = new List<Account>(); 

    Decimal radius1;
    Decimal radius2;
    String CampaignId;
    List<HCP_Parameters__c> s1 = HCP_Parameters__c.getall().values();
    for(HCP_Parameters__c c : s1)
    {if(c.Name =='Parameters' && c.Country__c =='US'){radius1 = c.Radius1__c; 
                          radius2 =c.Radius2__c;
                          CampaignId = c.Campaign_Id__c;
                          /*system.debug('radius1 :'+radius1);
                          system.debug('radius2 :'+radius2);
                          system.debug('CampaignId :'+CampaignId);*/}}


    List<CampaignAccount__c> allCampaignAccounts = [Select Id, Name, Account__c from CampaignAccount__c where Campaign__c =:CampaignId];
    Set<Id> leadIds = new Set<Id>();
    Set<Id> accountIds = new Set<Id>();
    Set<Id> DeclinedAccIds = new Set<Id>();
    Set<Id> noResponseAccIds = new Set<Id>();

    for(CampaignAccount__c c: allCampaignAccounts){accountIds.add(c.Account__c);}


    List<Account> accountWithCampaigns = [Select Id, Name, BillingLatitude, BillingLongitude, Priority_for_Leads__c, Last_Lead_Appointment__c from Account where Id in : accountIds Order By Last_Lead_Appointment__c asc];


    List<Lead_Appointment__c> appointments = [Select Id, CreatedDate, Account__c from Lead_Appointment__c where Account__c in : accountIds order by CreatedDate asc];

    Set<Id> accIdsfromLA = new Set<Id>();


    List<Lead_Appointment__c> declinedLAs = [Select Id, CreatedDate, Lead__c, Account__c, Appointment_Status__c from Lead_Appointment__c where Account__c in : accountIds AND HCP_Request_status__c =:'Declined' order by CreatedDate asc];
    Map<Id, Lead_Appointment__c> mapdeclinedLAs = new Map<Id, Lead_Appointment__c>(declinedLAs);

    if(declinedLAs!= Null){
        for(Lead_Appointment__c la: declinedLAs){
            DeclinedAccIds.add(la.Account__c);
        }
    }

    List<Lead_Appointment__c> noResponseLAs = [Select Id, CreatedDate, Account__c, Lead__c from Lead_Appointment__c where Account__c in : accountIds AND HCP_Request_status__c =:'Pending' AND CallGetHCP__c=:True order by CreatedDate asc];
    if(noResponseLAs!= Null){
        for(Lead_Appointment__c la: noResponseLAs){
            noResponseAccIds.add(la.Account__c);
        }
    }


    Map<Id, Account> mapHCPsAssigned = new Map<Id, Account>();
    for(Lead lead: NewLeads){
    for(Account acc: accountWithCampaigns){
        Location loc1 = Location.newInstance(acc.BillingLatitude, acc.BillingLongitude);
        system.debug('acc.BillingLatitude: '+acc.BillingLatitude);
        Location loc2 = Location.newInstance(lead.Latitude,lead.Longitude);
        system.debug('lead.Latitude: '+lead.Latitude);
        system.debug('loc1: '+loc1);
        system.debug('loc2: '+loc2);
        Double dist = Location.getDistance(loc1, loc2, 'mi'); // Distance calculated in miles

        if(dist<=radius1){HCPsInDefinedShorterRadius.add(acc);}
        if(dist<=radius2){HCPsInDefinedLongerRadius.add(acc);}
        }

        List<Account> finalAccounts = new List<Account>();
        if(HCPsInDefinedShorterRadius!=Null){finalAccounts = HCPsInDefinedShorterRadius.clone();}
        else{finalAccounts = HCPsInDefinedLongerRadius.clone();}


        Boolean flag = false;
        for(Account a: finalAccounts){
            if(declinedLAs!=Null){
        for(Lead_Appointment__c decLa :declinedLAs){

               if(decLa.Lead__c != lead.Id && decLa.Account__c != a.Id){ 

                    HCPAssigned = a;
                   if(noResponseLAs!=Null){
                    for(Lead_Appointment__c nrLa :noResponseLAs){
                   if(nrLa.Lead__c == Null || nrLa.Account__c== Null || nrLa.Lead__c != lead.Id && nrLa.Account__c != a.Id){ 
                       HCPAssigned = a; break;}
                }     

                   }}}}}

        if(HCPAssigned!=Null){
        mapHCPsAssigned.put(lead.Id,HCPAssigned);}
        else{leadIds.add(lead.Id);
        }
    }
    createLeadAppointment(mapHCPsAssigned);
    if(leadIds!=Null){updateUnallocatedLeads(leadIds);}

}

public static void createLeadAppointment(Map<Id, Account> mapHCPsAssigned ){
    Lead_Appointment__c leadApp = new Lead_Appointment__c();
    List<Lead_Appointment__c> LeadApps = new List<Lead_Appointment__c>();
    Lead lead = new Lead();
    List<Lead> Leads = new List<Lead>();

    for(Id idValue : mapHCPsAssigned.keyset())
    {
    if(mapHCPsAssigned.containsKey(idValue)){
    if(idValue!=null && mapHCPsAssigned.get(idValue)!=null){

    leadApp.Lead__c = idValue; 
    leadApp.Account__c = mapHCPsAssigned.get(idValue).Id; leadApp.HCP_Request_status__c ='Pending';
    LeadApps.add(leadApp);
    //Populate Lead Record to be updated
    lead.Id = idValue;
    lead.Lead_Appointment_Status__c = 'Allocated';
    Leads.add(lead);
    }}
    }
    if(LeadApps!=null){system.debug('LeadApps: '+LeadApps); insert LeadApps;
                      }
    if(Leads!=null){system.debug('Leads: '+Leads);  update Leads;
                   }
}

public static void updateUnallocatedLeads(Set<Id> leadIds ){
    Lead lead = new Lead();
    List<Lead> Leads = new List<Lead>();
    for(Id i: leadIds){
        lead.Id = i;
        lead.Lead_Appointment_Status__c = 'Unallocated';
        Leads.add(lead);
      }
    if(Leads!=null){system.debug('Leads: '+Leads);  update Leads;
    }
}

}

2
  • 2
    Hey there, you should try to add more details to your question so we can help you. What research have you done on the error message? What debugging have you tried so far? Did you read similar questions? Where in your code do you think there might be a problem? What exactly is your code doing? Jul 25, 2019 at 8:12
  • I am trying to get the geolocation from the lead address to match it to the nearest account. I am also creating a record for custom Object lead Appointment when this happens. Also, I mentioned that the error is on line 154. The lead record I am trying to update here in update call has a single record. I think there is something wrong with the structure which is causing the issue but I am not sure what.
    – user68419
    Jul 25, 2019 at 8:34

2 Answers 2

1

The issue actually was that the recursion on trigger call wasn't checked properly. I created a new check so that the after update trigger that I am using is only called once and solved the issue.

0

The LeadApps contains Lead_Appointment__c which have Ids, it means these Lead_Appointment__c are already inserted in the Org. You can not insert an object which is already in the Org.

So this can't be done:

if(LeadApps!=null){system.debug('LeadApps: '+LeadApps); insert LeadApps;
}

You may try updating the objects:

if(LeadApps!=null){system.debug('LeadApps: '+LeadApps); update LeadApps;
}
8
  • Actually LeadApps is a custom object Lead_Appointment__c list which I am inserting based on certain conditions. Can you see something else that's wrong? Also, the error is in line where I am trying to update the leads next to LeadApps: if(Leads!=null){system.debug('Leads: '+Leads); update Leads; }
    – user68419
    Jul 25, 2019 at 8:02
  • You are adding the same lead object in Leads. Jul 25, 2019 at 8:28
  • Yes to later call an Update action outside of for loop for the List "Leads" which contains all of the Lead records that were added.
    – user68419
    Jul 25, 2019 at 8:38
  • But you are initializing the lead only once outside the loop. So the same object being added to the Leads. The lead object should be instantiated in the loop. Jul 25, 2019 at 8:45
  • I tried but still getting the error, work when I comment out the update Leads statement.
    – user68419
    Jul 25, 2019 at 8:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .