function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
F SmoakF Smoak 

Need to reduce query rows and CPU Time and debug log size for apex after insert trigger

Hi I have written an after insert record which validates when CMS_Rule_Line_Item__c is created in bulk for a particular CMS_Rule__c (which has a lookup to CMS_MC_Cycle__c), create MC_Cycle_Plan_vod__c record. My debug log size is 10mb+ and qury rows count = 11k+ and my CPU Time is 3.5k I have just tested small records and inserted 174 recs. I would like to bring all these limits under control, but I cant seem to get rid of nested for loops. Any help is much appreciated!
Code:

trigger CMS_Insert_MCCP on CMS_Rule_Line_Item__c (after Insert) {
    List<Territory> territoryList = new List<Territory>();
    List<MC_Cycle_Plan_vod__c> mccp =  new List<MC_Cycle_Plan_vod__c>();
    Map<id,Set<String>> poateamMap =  new Map<id,Set<String>>(); //cycleid vs set of team
    List<CMS_Rule_Line_Item__c> cbList= [Select id,CMS_Team__c,Rule_Name__c,Rule_Name__r.CMS_MC_Cycle__c from CMS_Rule_Line_Item__c
                                         where id in: trigger.new];
    Set<String> teamSet = new Set<String>();
    for(CMS_Rule_Line_Item__c crRecord: cbList){
        if(!poateamMap.containsKey(crRecord.Rule_Name__r.CMS_MC_Cycle__c)){
            poateamMap.put(crRecord.Rule_Name__r.CMS_MC_Cycle__c,new Set<String>{crRecord.CMS_Team__c});
            teamSet.add(crRecord.CMS_Team__c);
        }
        else{
                poateamMap.get(crRecord.Rule_Name__r.CMS_MC_Cycle__c).add(crRecord.CMS_Team__c);
                teamSet.add(crRecord.CMS_Team__c);
        } }
    system.debug('poa vs team list>>>'+poateamMap.size() +poateamMap);
   
    Map<String,List<Territory>> teamterrMap = new Map<String,List<Territory>>(); //team vs list of territory
    List<Territory> teamterrList =  [Select id,name,CMS_Salesforce__c from Territory where CMS_Salesforce__c in: teamSet];
    Set<id> terrSet = new Set<id>();
    Map<id,id> terruseridMap =new Map<id,id>();
   
            for(Territory t1:teamterrList){
            if(teamSet.contains(t1.CMS_Salesforce__c)){
                if(!teamterrMap.containsKey(t1.CMS_Salesforce__c)){
                teamterrMap.put(t1.CMS_Salesforce__c,new List<Territory>{t1});
                    terrSet.add(t1.id);
            }
            else{
                teamterrMap.get(t1.CMS_Salesforce__c).add(t1);
                terrSet.add(t1.id);
            }  
            }
        }
    Map<id,id> userterridMap =new Map<id,id>(); //userid with corresponding territoryid
    for(UserTerritory ut:[Select territoryid,userid from UserTerritory where territoryid in : terrSet]){
        userterridMap.put(ut.userid,ut.territoryid);
        terruseridMap.put(ut.territoryid,ut.userid);
    }
    Map<id,string> userterrMap= new Map<id,string>(); // territoryid with corresponding username
    for(User u:[Select id,name from User where id = : userterridMap.keyset()]){
        userterrMap.put(userterridMap.get(u.id),u.name);
    }
   
  //  system.debug('team vs terr list>>>'+teamterrMap.size() +teamterrMap);
    Map<id,List<Territory>> poaterrMap = new Map<id,List<Territory>>(); //cycleid with corresponding territory ids
    for(Id i1:poateamMap.keySet()){
        for(String s1:poateamMap.get(i1)){
            if(teamterrMap.containsKey(s1)){
                if(!poaterrMap.containsKey(i1)){
                    List<Territory> tList = new List<Territory>();
                    tList=teamterrMap.get(s1);
                    poaterrMap.put(i1,tList);
                }
                else{
                    List<Territory> tList2 = new List<Territory>();
                    tList2=teamterrMap.get(s1);
                    for(Territory tt:tList2){
                    poaterrMap.get(i1).add(tt);
                    }
                }
            }
        }
    }
    //system.debug('poa vs terr list>>>'+poaterrMap.size() +poaterrMap);
   
    List<MC_Cycle_Plan_vod__c> existingcycleMccp = [Select id,Cycle_vod__c,Territory_vod__c from MC_Cycle_Plan_vod__c where Cycle_vod__c in:poaterrMap.keyset()];
    Map<id,List<Territory>> finalMap = new Map<id,List<Territory>>();
    if(existingcycleMccp.size()>0){
    for(MC_Cycle_Plan_vod__c mcplan: existingcycleMccp){
        if(!poaterrMap.containsKey(mcplan.Cycle_vod__c)){
                for(Territory t2:poaterrMap.get(mcplan.Cycle_vod__c)){
                    if(t2.name!=mcplan.Territory_vod__c){
                        if(!finalMap.containsKey(mcplan.Cycle_vod__c)){
                            finalMap.put(mcplan.Cycle_vod__c, new List<Territory>{t2});
                        }
                        else{
                            finalMap.get(mcplan.Cycle_vod__c).add(t2);
                        }
                    }
                }
        }
    } }
    else{
        finalMap.putAll(poaterrMap);
    }
//system.debug('finalMap list>>>'+finalMap.size() +finalMap);
   
    List<MC_Cycle_vod__c> mccycleList = new List<MC_Cycle_vod__c>();
    mccycleList= [Select Id,Start_date_vod__c from MC_Cycle_vod__c where Id in: finalMap.keyset()];
    List<CMS_MC_Cycle_Month__mdt> mdtList = new List<CMS_MC_Cycle_Month__mdt>();
    mdtList= [Select Id,DeveloperName,CMS_Month_Number__c from CMS_MC_Cycle_Month__mdt];
   
    try{
        if(trigger.isInsert && finalMap.size()>0){
    for(Id rule:finalMap.keyset()){
        Integer monthval=null;
        Integer CycleYear=null;
        String CycleMonth ='';
        String mccpName = '';
        for(MC_Cycle_vod__c mccyclerec: mccycleList){
            if(mccyclerec.id==rule){
            monthval=mccyclerec.Start_date_vod__c.month();
            CycleYear = mccyclerec.Start_date_vod__c.year();
            for(CMS_MC_Cycle_Month__mdt monthmdt : mdtList){
                if(monthmdt.CMS_Month_Number__c==monthval){
                CycleMonth = monthmdt.DeveloperName;
                mccpName= 'MCCP_'+cycleMonth+'_'+cycleYear+'_';
                }}
            }}
        for(Territory terrname: finalMap.get(rule)){
            if(terruseridmap.containsKey(terrname.id)){
            MC_Cycle_Plan_vod__c mcRecord =  new MC_Cycle_Plan_vod__c();
            mcRecord.Cycle_vod__c= rule;
            mcRecord.CMS_Team__c=terrname.CMS_Salesforce__c;
            mcRecord.Territory_vod__c= terrname.name;
            mcRecord.Status_vod__c='In Progress';
            mcRecord.Ownerid=terruseridMap.get(terrname.id);
               
            if(userterrMap.containsKey(terrname.id)){
                    mcRecord.Name=mccpName+userterrMap.get(terrname.id);
                }
            mccp.add(mcRecord);
            }} }
    if(mccp.size()>0){
        insert mccp;
    }  } }
    catch (DmlException e) {
        System.debug('A DML exception has occurred: ' +e.getMessage() +e.getLineNumber());
    }          
}
ANUTEJANUTEJ (Salesforce Developers) 
Hi Smoak,

You can use the below methods to get the apex cpu consumption until the point you have placed in the code:

>> Limits.getCPUTime() - Returns the CPU time(in milliseconds) accumulated on the salesforce.com server in the current transaction. -
>>Limits.getLimitCPUTime() - Returns the total CPU time (in milliseconds) accumulated on the salesforce.com servers in the current transaction.

I hope this helps and in case if this comes in handy can you please choose this as the best answer so that it can be used by others in the future.

Regards,
Anutej