• Kristine Sheehan 5
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 1
    Replies
Hello - 

I am an admin with no development experience. I've inherited an org that uses custom apex triggers, classes, etc. We have recently setup an integration with Marketo. Occasionally, the marketo sync will fail to update Lead records in salesforce, the error thrown is:

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: updateLead: execution of BeforeUpdate caused by: System.LimitException: Apex CPU time limit exceeded (System Code)

Working with sfdc support, I believe we've identified the piece of code that we are coming up against. The problem is, I have no idea what it is doing (or what should/could be done to optimize it)

Is there anyone out there who can translate this for me? 

Thanks!User-added image


public class UpdateLeadForUpdateOnly 
{
    private static integer NameWeightage = 3;
    private static integer WebSiteWeightage = 2;
    private static integer EmailWeightage = 1;
    public void updateLeads(Lead [] Leads)
    {
          integer minLeadLength = LeadTriggerSettings.MinimumNameSize;
          integer minDomainLength = LeadTriggerSettings.MinimumDomainSize;
          Set<String> ExceptionNames = LeadTriggerSettings.GetExceptionNames();
          
          String companyname;
          List<string> query=new List<string>();//This List is used to run query
          Integer countquery=0;
          Integer countLeads=0;
          Integer RecordLimit = 1000 * Leads.size();
          if(Leads.size()==1){
            RecordLimit = 100;
          }
          Integer ListSize = 1000 * Leads.size();
      String website ;
      String StrLeadCompany ;
      String StrLeadWebsite ;
        String StrLeadEmail = '';
          String strLeadAccName = '';
      String[] getEmail1 ;
          //Set<Account> accList=new Set<Account>();
          Integer counter=0;
          //This loop is used to get no. of leads
          countquery = Leads.size();
          //Hashmaps used for searching name 
          Map<String,ID> FullNameMap = new Map<String,ID>();
          Map<String,ID> PartNameMap = new Map<String,ID>();
          Map<String,ID> NameWordMap = new Map<String, ID>();
          Map<String,ID> websiteMap = new Map<String, ID>();
          
          Map<ID,Account> AccountMap = new Map<ID, Account>();
          String filterCondition='';
          for (Lead ld :Leads)
          {
              countLeads++;
              getEmail1 =new String[]{};
              StrLeadCompany = ld.Company+''; 
              StrLeadCompany = StrLeadCompany.replace('.',' ');
              StrLeadCompany = StrLeadCompany.replace(',',' ');
              StrLeadWebsite = '';
              if(ld.website!=null && ld.website.length()>0){
                  StrLeadWebsite  = ld.website.trim().replace('http://','');
                  StrLeadWebsite = StrLeadWebsite.trim().replace('www.','');              
              }
  
              
        System.debug('Email is here ' + ld.Email);
              if (ld.Email!='' && ld.Email!=null)
              {
                  getEmail1=ld.Email.split('@',0);
          System.debug('Got it split here ');
              }
              else
              {
                  //getEmail1 = new String[]{'',''};
                  getEmail1.add('');
                  getEmail1.add('');
              }
              if( (strLeadWebsite!='' ) || getEmail1[1]!='' || StrLeadCompany!=''){
                  if (getEmail1[1]!='' && getEmail1[1].length()>=minDomainLength)
                  {
                    System.debug('here 1');
                      filterCondition = AddFilter(filterCondition,' Website like \'%'+ String.escapeSingleQuotes(getEmail1[1]) + '%\'');
                  }
                  if(StrLeadCompany!='' && StrLeadCompany.length()>=minLeadLength  && (!ExceptionNames.contains(StrLeadCompany) ) ){
                      filterCondition = AddFilter(filterCondition,' name like \'%'+ String.escapeSingleQuotes(StrLeadCompany) + '%\'');
                    System.debug('here 2');                }
                  if(strLeadWebsite!='' && strLeadWebsite.length()>=minDomainLength ){
                      filterCondition = AddFilter(filterCondition,' Website like \'%'+ String.escapeSingleQuotes(strLeadWebsite) + '%\'');
                    System.debug('here 3');
  
                  }                   
      
                  if (filterCondition.length()>7000)
                  {
                      companyname='Select Id,name,type,OwnerId,Website,SplitName__c,LastModifiedDate from Account where ' + filterCondition; 
                      filterCondition = '';
                      query.add(companyname);
                  }
              }
          }       
          if(filterCondition.length()>0){
              companyname='Select Id,name,type,OwnerId,Website,SplitName__c,LastModifiedDate from Account where ' + filterCondition; 
              System.debug('Here6===' + filterCondition);
              filterCondition = '';
              query.add(companyname);
          }
          System.debug('Query size : ' + query.size());
          Integer limitSize=1000;
          for (integer i=0;i<query.size();i++)
          {
              query[i]=query[i]+'order by LastModifiedDate limit ' + RecordLimit;
              System.debug('Query to be executed : ' + query[i]);
              //Fill Hashmaps with values. a loop on account is required 
        integer k=0;
              for(Account acc: Database.query(query[i])){
        if(Math.mod(k++,25)==0)
          System.debug('==========Heap size ' + Limits.getHeapSize());
  
                  if(AccountMap.values().size() < ListSize) {
                      AccountMap.put(acc.id, acc); 
                  }
                  if(FullNameMap.values().size() < ListSize && acc.name.length()>2) {
                      FullNameMap.put(acc.name, acc.id); 
                  }
                  //Website name, remove www and http, if found 
  
                  if(acc.website!=null && acc.website.length()>0){
                      website = (acc.website.trim().replace('http://','')).replace('www.','');
                      if(WebsiteMap.values().size() < ListSize && website.length()>2) {
                          WebsiteMap.put(website,acc.id);
                      }
                  }
                  
              }
              //AccountMap.putAll(AccountList);
          }
  
          List<string> score=new List<string>();
          Map<ID, Map<ID, Integer>> LeadMainMap = new Map<ID, Map<ID, Integer>> ();
          //This for loop is used to update Lead
      Map<ID, Integer> ScoreMap;
          for (Lead ld1 :Leads)
          {
              StrLeadEmail = '';
              strLeadWebsite = '';
              strLeadAccName = '';
              //Scores: 
              //Exact Name Match: 10
              //Partial Name Match: 8
              //One Word Match : 6
              //website to website Match : 4
              //Email Domain to website Match : 2 
  
  
  
              if (ld1.Company!=null && ld1.Company.trim().length()>0){
                  strLeadAccName=ld1.Company;
              }
  
              if (ld1.Email!=null && ld1.email.trim().length()>0){
                  String[] temp = ld1.Email.split('@',0);
                  if(temp.size()==2){
                      StrLeadEmail = temp[1];
                  }
              }
              if(ld1.website!=null && ld1.website.length()>0){
                  strLeadWebsite  = ld1.website.trim().replace('http://','');
                  strLeadWebsite = strLeadWebsite.trim().replace('www.','');              
              }
              ScoreMap = new Map<ID, Integer>();
  
              if(FullNameMap.containsKey(strLeadAccName)){
                  ID accID = FullNameMap.get(strLeadAccName);
                  if(ScoreMap.containsKey(accID)){
                      ScoreMap.put(accID, ScoreMap.get(accID)+10);
            System.debug('=======First Pass ' + ld1.id + ', ' + accID + ' , ' + ScoreMap.get(accID));
                  }
                  else{
                      ScoreMap.put(accID, 10);
                  }
              }
              if(WebsiteMap.containsKey(StrLeadEmail)){
                  ID accID = WebsiteMap.get(StrLeadEmail);
                  if(ScoreMap.containsKey(AccID)){
                      ScoreMap.put(AccID, ScoreMap.get(AccID)+2);
            System.debug('=======First Pass ' + ld1.id + ', ' + accID + ' , ' + ScoreMap.get(accID));
                  }
                  else{
                      ScoreMap.put(AccID, 2);
                  }
              }
  
              if(WebsiteMap.containsKey(strLeadWebsite)){
                  ID accID = WebsiteMap.get(strLeadWebsite);
                  if(ScoreMap.containsKey(AccID)){
                      ScoreMap.put(AccID, ScoreMap.get(AccID)+4);
            System.debug('=======First Pass ' + ld1.id + ', ' + accID + ' , ' + ScoreMap.get(accID));
                  }
                  else{
                      ScoreMap.put(AccID, 4);
                  }
              }
              LeadMainMap.put(ld1.id, ScoreMap);
          }
      //Second Pass QUery 
      FullNameMap.clear();
      websiteMap.clear();
      
          for (integer i=0;i<query.size();i++)
          {
  
              System.debug('Query to be executed : ' + query[i]);
              //Fill Hashmaps with values. a loop on account is required 
              for(Account acc: Database.query(query[i])){
                  if(acc.SplitName__c!=null && acc.SplitName__c.length()>0){
                      String[] partialNameList = acc.SplitName__c.split('\n');
                      for(String PartName : partialNameList){
                          if(PartNameMap.values().size() < ListSize && PartName.length()>2) {
                              PartNameMap.put(PartName,acc.id);
                          }
                      }
                  }
                  //check if there are more than one words in name, 
                  //add them to the namewordmap 
                  String[] WordList = acc.name.trim().split(' ');
                  if(WordList.size()>1){
                      for(String word: WordList){
                          if(NameWordMap.values().size() < ListSize && word.length()>2) {
                              NameWordMap.put(word,acc.id);       
                          }
                      }
                  } 
              }
              //AccountMap.putAll(AccountList);
          }
  
      
      //Second Pass 
          for (Lead ld1 :Leads)
          {
              StrLeadEmail = '';
              strLeadWebsite = '';
              strLeadAccName = '';
              //Scores: 
              //Exact Name Match: 10
              //Partial Name Match: 8
              //One Word Match : 6
              //website to website Match : 4
              //Email Domain to website Match : 2 
  
  
  
              if (ld1.Company!=null && ld1.Company.trim().length()>0){
                  strLeadAccName=ld1.Company;
              }
  
              if (ld1.Email!=null && ld1.email.trim().length()>0){
                  String[] temp = ld1.Email.split('@',0);
                  if(temp.size()==2){
                      StrLeadEmail = temp[1];
                  }
              }
              if(ld1.website!=null && ld1.website.length()>0){
                  strLeadWebsite  = ld1.website.trim().replace('http://','');
                  strLeadWebsite = strLeadWebsite.trim().replace('www.','');              
              }
        ScoreMap = LeadMainMap.get(ld1.id);  
  
              if(PartNameMap.containsKey(strLeadAccName)){
                  ID accID = PartNameMap.get(strLeadAccName);
                  if(ScoreMap.containsKey(accID)){
                      ScoreMap.put(accID, ScoreMap.get(accID)+8);
            System.debug('=======Second Pass ' + ld1.id + ', ' + accID + ' , ' + ScoreMap.get(accID));
                  }
                  else{
                      ScoreMap.put(accID, 8);
                  }
              }
              if(NameWordMap.containsKey(strLeadAccName)){
                  ID accID = NameWordMap.get(strLeadAccName);
                  if(ScoreMap.containsKey(accID)){
                      ScoreMap.put(accID, ScoreMap.get(AccID)+6);
            System.debug('=======Second Pass ' + ld1.id + ', ' + accID + ' , ' + ScoreMap.get(accID));
                  }
                  else{
                      ScoreMap.put(AccID, 6);
                  }
              }
              LeadMainMap.put(ld1.id, ScoreMap);
          }
      
  
  
  
          for (Lead ld1 :Leads)
          {
              ScoreMap = LeadMainMap.get(ld1.id);
              integer AccScore = 0; 
              ID AccountId; 
              for(ID AccId : ScoreMap.keySet()){
                  Integer Score1 = ScoreMap.get(AccID); 
                  if(Score1 > AccScore){
                      AccountID = AccID; 
                      AccScore = Score1; 
                  }
                  else if(Score1 == AccScore){
                      Account acc = AccountMap.get(AccountId);
                      Account acc2 = AccountMap.get(AccID);
                      if(acc2.LastModifiedDate>acc.LastModifiedDate){
                          AccountId = AccId; 
                      }
                  }
              }
              if(AccountID!=null){
                  Account tempAccount = AccountMap.get(AccountId);
                  ld1.Account__c=tempAccount.id;
                  ld1.AccountOwner__c=tempAccount.ownerId;
                  ld1.Account_Type__c=tempAccount.Type;
                  ld1.Account_Match_Score__c = AccScore;
              }
  
          }
    
    }
    public String AddFilter(String Filter, String str){
        if(Filter.length()>0){
            return Filter+' or ' + str;
        }
        else{
            return str;
        }
    }
            
    public static testMethod void testupdateLeadForUpdateOnly()  
    {
        updateLeadForUpdateOnly updtlead = new updateLeadForUpdateOnly();
        List<Lead> leadLst = new List<Lead>();
        
        Account newAcc = new Account(Name = 'Test',Type = 'Parent');
        insert newAcc;
        Lead newlead  = new Lead(LastName = 'TestLast', Company = 'Test', Status = 'Qualified', Type__c = 'Brainshark',Lead_Source_Team__c='CSC',LeadSource='Direct Mail',Website = 'http://www.final.com');
        insert newlead;
        leadLst.add(newlead);
        updtlead.updateLeads(leadLst);  
        updtlead.AddFilter('Filter','str');
    }
}

 

I have a hunch I'm missing something obvious, but I've finished making a flow, set as start location, saved it to make sure there were no warnings, then clicked "run" and I get:

 



Insufficient Privileges

 

You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary. 

 

 

Anyone have any ideas as to what I'm doing wrong?

 

*Note:  I'm using the cloud Flow Designer. I use a mac, so I can't even try the locally run version