• SF Beginner 2019
  • NEWBIE
  • 95 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 50
    Questions
  • 34
    Replies
Hi All,

I am creating a batch job wherein should delete if the account if status is not changed for last 90 days when it was created, other wise if there is change for the last 90 days don't delete can you help me on how to do it, basically from the account object history, since it has only new value, old value and created date?

thank you

 
public static boolean insertExceptionRecs(List<Database.SaveResult> srList){
        try{
            List<ExceptionLog__c> excpLst = New List<ExceptionLog__c>();
            boolean isError = False;
            ExceptionLog__c objLog= new ExceptionLog__c();
            if(!srList.isEmpty()){
                for(Database.SaveResult obj : srList){
                    for(Database.Error objErr : obj.getErrors()){
                        if(!obj.isSuccess()){
                            objLog = new ExceptionLog__c(
                                Object_ID__c =obj.getId(),
                                ExceptionDescription__c = objErr.getMessage(),
                                ExceptionCode__c =  EXCPCODE,
                                NumberOfTimesOccured__c = OCCURENCE + 1,
                                ExceptionDetails__c = objErr.getMessage(),
                                Severity__c = EXCPSVRTY);
                            excpLst.add(objLog);
                        } 
                    }
                }
            }
            if(!excpLst.isEmpty()){
                Database.upsert(excpLst,false);
                isError = true;
            }
            return isError;
        }
        Catch(Exception e)
        {
            GA_LogExceptionCls.LogExcp(e, CLSNAME,METHODINSERTXCPTNRECDS);
           return false;
        } 
    }

I cannot covered the !obj.isSuccess()) is there an assertequals that might help? thank you
Hi, 

I have this trigger that sends an email if something was uploaded on a case. but my problem is how can I achive using the contentdocumentlink, wherein if I upload 5 files, I will only receive 1 email notification using the apex class? because when I upload 5 files I usually receive 5 emails as well. What I want is when I upload 5 files at the same time I will only be receiving one email. Thank you
 
trigger ContentDocumentLinkTrigger on ContentDocumentLink (before insert, after insert) {
    if(Trigger.isInsert) {
        if(Trigger.isAfter) {
            Set<Id> objectIds = new Set<Id>(); 
            for (ContentDocumentLink a: Trigger.new) {
                String keyPrefix = String.valueOf(a.LinkedEntityId).substring(0, 3);
                if(keyPrefix == '500'){
                    objectIds.add(a.LinkedEntityId);
                }
                ContentDocumentLinkEmailHandler.sendEmailNotification(objectIds);
            }
        }
    }
}
 
public class ContentDocumentLinkEmailHandler {
    public static final string emailTmpltDevName = 'TemplateCase';
 {
 List<Case> caselist = [SELECT Id, Owner.Id,CaseNumber, Subject, Owner.Type FROM Case WHERE Id In: objectIds];
                    for(Case cs:caselist){
                        cs.Send Notification= true;
                    }
                if(caselist.size() > 0)
                {
                    update caselist;
                }
            }
    }
}


 
Issue is that sometimes it deletes sometime it doesn't delete or update.
 
global class AccountContactTriggerHandler implements Database.Batchable<sObject>
{
    List<AccountContactRelation> ListtoInsert = new List<AccountContactRelation>();
    Set<accountContactRelation> ListToDelete = new Set<accountContactRelation>();
    Map<String, Account> accCodeMap = new Map<String,Account>();
    map<string,Contact> contactAccountMap = new map<string, Contact>();
    String query = 'Select Id,Name,License_ID__c FROM Account WHERE License_ID__c != null AND IsPartner = true AND License_ID__c LIKE \'__\'';
    final String CLSSNAME = 'AccountContactTriggerHandler';
 
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc,List<Account> batch){
        try{
            for(Account a : batch)
                accCodeMap.put(a.License_ID__c, a);

            for (Contact c : [Select ID, Name, Accountid, Person_ID__c, ABS_Person_ID__c, (SELECT AccountId, ContactId FROM AccountContactRelations) from Contact WHERE (ABS_Person_ID__c != null AND ABS_Person_ID__c LIKE '__') OR (Person_ID__c != null AND Person_ID__c LIKE '__')]){
                Set<String> acrIdList =new Set<String>();
                List<AccountContactRelation> acrList = c.AccountContactRelations;
                for(AccountContactRelation acrId : acrList){
                    contactAccountMap.put(acrId.AccountId, c); // Used for deleting code soql
                    acrIdList.add(acrId.AccountId);
                }

                Account a, a2;
                if(c.Person_ID__c != null)
                    a = accCodeMap.get(c.Person_ID__c);
                if(c.ABS_Person_ID__c != null)
                    a2 = accCodeMap.get(c.ABS_Person_ID__c);
                
                if(a != null && a2 != null && a == a2){
                    if(!acrIdList.contains(a.Id)){
                        if(c.Person_ID__c == a.License_ID__c){
                            AccountContactRelation   acr =  new AccountContactRelation();
                            acr.AccountId = a.id;
                            acr.contactId = c.Id;
                            ListtoInsert.add(acr);
                        }
                    }
                }
                else {
                    // Checks if the AccountContactRelations already connected to the Contact
                    if(a != null){
                        if(!acrIdList.contains(a.Id)){
                            if(c.Person_ID__c == a.License_ID__c){
                                AccountContactRelation   acr =  new AccountContactRelation();
                                acr.AccountId = a.id;
                                acr.contactId = c.Id;
                                ListtoInsert.add(acr);
                            }
                        }
                    } 
                    
                    if(a2 != null){
                        if(!acrIdList.contains(a2.Id)){
                            if(c.ABS_Person_ID__c == a2.License_ID__c){
                                AccountContactRelation   acr =  new AccountContactRelation();
                                acr.AccountId = a2.id;
                                acr.contactId = c.Id;
                                ListtoInsert.add(acr);
                            }
                        }
                    }
                }                
            }
            insert ListtoInsert;
            //loop only the accounts that are related/connected to AccountContactRelation Object
            map<string,Account> accountMap = new map<string, Account>();
            for(Account Acc: [SELECT id, Name, License_ID__c FROM Account WHERE Id =: contactAccountMap.keySet()])
            {
                accountMap.put(Acc.Id,acc);
            }
            //loop the AccountContactRelation to get the records where isDirect is not true
            for(AccountContactRelation AccountConDelete : [SELECT Id, AccountId, ContactId FROM AccountContactRelation WHERE Accountid =: contactAccountMap.keySet() AND isDirect != TRUE])
            {
                Account acc = accountMap.get(AccountConDelete.AccountId);
                contact con = contactAccountMap.get(AccountConDelete.AccountId);
                if(acc.License_ID__c != con.Person_ID__c && acc.License_ID__c != con.ABS_Person_ID__c)
                {
                    ListToDelete.add(AccountConDelete);    
                }
            }

            System.debug('TO BE DELETED: '+ListToDelete);  
            List<AccountContactRelation> AccountConNew = new List<AccountContactRelation>();
            for (AccountContactRelation acr : ListToDelete)
                AccountConNew.add(acr);
            
            delete AccountConNew;
        }																				
        catch(Exception e){
            
        }
    }	
    
    global void finish(Database.BatchableContext bc)
    {
        //DoNothing.
    }
}

 
I have this account contact relationship wherein runs in Batch, my issue is that the delete is kinda buggy wherein it sometimes delete and sometimes doesn't delete what could be the possible issue in here? thank you
 
global class AccountContactTriggerHandler implements Database.Batchable<sObject>
{
    List<AccountContactRelation> ListtoInsert = new List<AccountContactRelation>();
    Set<accountContactRelation> ListToDelete = new Set<accountContactRelation>();
    Map<String, Account> accCodeMap = new Map<String,Account>();
    map<string,Contact> contactAccountMap = new map<string, Contact>();
    String query = 'Select Id,Name,License_ID__c FROM Account WHERE License_ID__c != null AND IsPartner = true AND License_ID__c LIKE \'__\'';
    final String CLSSNAME = 'AccountContactTriggerHandler';
 
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc,List<Account> batch){
        try{
            for(Account a : batch)
                accCodeMap.put(a.License_ID__c, a);

            for (Contact c : [Select ID, Name, Accountid, Person_ID__c, ABS_Person_ID__c, (SELECT AccountId, ContactId FROM AccountContactRelations) from Contact WHERE (ABS_Person_ID__c != null AND ABS_Person_ID__c LIKE '__') OR (Person_ID__c != null AND Person_ID__c LIKE '__')]){
                Set<String> acrIdList =new Set<String>();
                List<AccountContactRelation> acrList = c.AccountContactRelations;
                for(AccountContactRelation acrId : acrList){
                    contactAccountMap.put(acrId.AccountId, c); // Used for deleting code soql
                    acrIdList.add(acrId.AccountId);
                }

                Account a, a2;
                if(c.Person_ID__c != null)
                    a = accCodeMap.get(c.Person_ID__c);
                if(c.ABS_Person_ID__c != null)
                    a2 = accCodeMap.get(c.ABS_Person_ID__c);
                
                if(a != null && a2 != null && a == a2){
                    if(!acrIdList.contains(a.Id)){
                        if(c.Person_ID__c == a.License_ID__c){
                            AccountContactRelation   acr =  new AccountContactRelation();
                            acr.AccountId = a.id;
                            acr.contactId = c.Id;
                            ListtoInsert.add(acr);
                        }
                    }
                }
                else {
                    // Checks if the AccountContactRelations already connected to the Contact
                    if(a != null){
                        if(!acrIdList.contains(a.Id)){
                            if(c.Person_ID__c == a.License_ID__c){
                                AccountContactRelation   acr =  new AccountContactRelation();
                                acr.AccountId = a.id;
                                acr.contactId = c.Id;
                                ListtoInsert.add(acr);
                            }
                        }
                    } 
                    
                    if(a2 != null){
                        if(!acrIdList.contains(a2.Id)){
                            if(c.ABS_Person_ID__c == a2.License_ID__c){
                                AccountContactRelation   acr =  new AccountContactRelation();
                                acr.AccountId = a2.id;
                                acr.contactId = c.Id;
                                ListtoInsert.add(acr);
                            }
                        }
                    }
                }                
            }
            insert ListtoInsert;
            //loop only the accounts that are related/connected to AccountContactRelation Object
            map<string,Account> accountMap = new map<string, Account>();
            for(Account Acc: [SELECT id, Name, License_ID__c FROM Account WHERE Id =: contactAccountMap.keySet()])
            {
                accountMap.put(Acc.Id,acc);
            }
            //loop the AccountContactRelation to get the records where isDirect is not true
            for(AccountContactRelation AccountConDelete : [SELECT Id, AccountId, ContactId FROM AccountContactRelation WHERE Accountid =: contactAccountMap.keySet() AND isDirect != TRUE])
            {
                Account acc = accountMap.get(AccountConDelete.AccountId);
                contact con = contactAccountMap.get(AccountConDelete.AccountId);
                if(acc.License_ID__c != con.Person_ID__c && acc.License_ID__c != con.ABS_Person_ID__c)
                {
                    ListToDelete.add(AccountConDelete);    
                }
            }

            System.debug('TO BE DELETED: '+ListToDelete);  
            List<AccountContactRelation> AccountConNew = new List<AccountContactRelation>();
            for (AccountContactRelation acr : ListToDelete)
                AccountConNew.add(acr);
            
            delete AccountConNew;
        }																				
        catch(Exception e){
            
        }
    }	
    
    global void finish(Database.BatchableContext bc)
    {
        //DoNothing.
    }
}

 
this may sounds funny, but I'm really struggling with this one.
 
if(p.Type__c == 'Contractor' &&  p.hasRecord__c == true && p.Visible__c == 'OFF'){
                p.Output__c= false;  
            }
            else if(p.Type__c == 'Contractor' &&  p.hasRecord__c == true && p.Visible__c == 'ON'){
                p.Output__c= true;
            }
            else if(p.Type__c == 'Contractor' &&  p.hasRecord__c == false && p.Visible__c == 'OFF'){
                p.Output__c= true; 
            }
            else if(p.Type__c == 'Contractor' &&  p.hasRecord__c == false && p.Visible__c == 'ON'){
                p.Output__c= true;
            }


can you convert that into formula field, I tried several time but I'm having issues with the 1st and 3rd statement.

 
IF (
    AND  
       (Type__c = 'Contractor',OR(
          AND(Visible__c = 'ON',hasRecord__c = true),
          AND(Visible__c = 'OFF', hasRecord__c = false,
          AND(Visible__c = 'ON',hasRecord__c = false)))
        ),
true,IF (
    AND  
       (Type__c = 'Contractor',
          AND(Visible__c = 'OFF', hasRecord__c = True)
        ),
false,

True)))



 
Hi,

is is possible to convert a for example

I have an object account, then I have a related list which is member then that member has a lookup to teller. is it possible to display that as a dynamic dropdownpicklist? under the account?  if yes can I have a reference. thank you
How can I store this on a picklist.

is my attribute correct?
<aura:attribute name="Type" type="String" />

this is my apex class to return list
@AuraEnabled
    
    public static List<String> getAuthorized(string recordId){
        List<ID> coid = new List<ID>();
        
        List<String> MemName = new List<String>();
        for( Member__c covmem :  [SELECT Id,Name, FROM Member__c WHERE Account__c =: recordId ] )
        {
            coid.add(covmem.Personel__c);  
        }
        for(Personel__c cov : [SELECT Id,Name FROM Personel__c WHERE Id =: coid ]){
            
            MemName.add(cov.Name);
        }
        return MemName;
    }

this is my helper
getAuthorized : function(component,event,helper){
        var recordId = component.get("v.recordId");
        var action = component.get("c.getAuthorized");
        action.setParams({recordId : recordId});
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
               //alert(JSON.stringify(response.getReturnValue()));
                 var coidpicklist = response.getReturnValue();
 				component.set("v.Type",coidpicklist);
                //var coidpicklist = response.getReturnValue()[0].ValuePicklist__c;
            }
        });
        $A.enqueueAction(action);
    },


 
Integer counter = UPDTACCOWNRLMT;
                    List<Account> newList = New List<Account>();
                    AccOwnerUpdateQueueble updateJob;
                    for (Integer j=0; j < updtAccLst.size() ;j++){
                        
                        if(j < counter ){
                            newList.add(updtAccLst[j]);
                            }
                        if(j == counter && Limits.getQueueableJobs() == 0){ 
                               newList.add(updtAccLst[j]);
                                updateJob = new AccOwnerUpdateQueueble(newList);
                                ID jobID = System.enqueueJob(updateJob);
                                counter = counter + UPDTACCOWNRLMT;
                                newList.clear();
                           }
                        
                    }
                    
                    if(!newList.isEmpty() && (Limits.getQueueableJobs() == 0)  ){
                             //  system.debug('newList size'+newList.size());
                                updateJob = new AccOwnerUpdateQueueble(newList);
                                ID jobID = System.enqueueJob(updateJob);
                                counter = counter + UPDTACCOWNRLMT;
                                newList.clear();
                           } 
                    
                }

HI,

I need help on queuable test class.

it doesn't cover this portion.

 
Is it possible to render a document in Community? any reference please. thank you!
is it possible to render documents in lightning community using content document? how can you help me with some reference thank you
I have this issue wherein the Account Owner is not updating correctly this is because of duplicate Country in a single zip code, can you help me on my apex class below? How can I identify the zip code and country so that the account owner will of the account will be updated correctly. it has one zip code but it updates between the three countries it first get.
 
public static void insertAccountOwner(Set<Account> accList){
            set<String> TerritoryIds = new Set<String>();
            Map<Id, String> mapAccountTerritory = new Map<Id, String>();
            Set<String> PostalCodes = new Set<String>();
            Set<String> CountryCodes = new Set<String>();
            Set<String> MarketSegments = new Set<String>();
            
            Map<String,String> TerrToAccMap = new Map<String,String>();
            Map<String,String> MolTerrToAccMap = new Map<String,String>();
            Map<String,String> DhlTerrToAccMap = new Map<String,String>();
            Map<String,String> SpgTerrToAccMap = new Map<String,String>();
            Map<String,String> ETeTerrToAccMap = new Map<String,String>();
            Map<String,String> IKAMTerrToAccMap = new Map<String,String>();
            
                     for(Account acc :accList){
                
                //Add account zipcode if not international
                //if(acc.Group__c != 'International') {
                if (acc.ShippingPostalCode != null) PostalCodes.add(acc.ShippingPostalCode);
                   if (acc.ShippingPostalCode == null) {
                       acc.ShippingPostalCode = '';
                       PostalCodes.add(acc.ShippingPostalCode);
                   }
                         
                if (acc.ShippingPostalCode != null && acc.Group__c == 'Corporate' ) PostalCodes.add('99999');
                if (acc.ShippingPostalCode != null && acc.ShippingCountry =='Canada' ) PostalCodes.add(acc.ShippingPostalCode.left(3));
                if (acc.ShippingCountry != null) CountryCodes.add(acc.ShippingCountry);
                if (acc.MarketSegment__c != null) MarketSegments.add(acc.MarketSegment__c);
            }

            if (!PostalCodes.isEmpty()) {
                for(Territory__c t: [SELECT Id, Name, Territory_ID__c, Market_Segment__c, IKAM__c, MOL__C, DHL__C, ZipCode_Unique__c, Country__c, 
                                     RSC__C, ETE__C  FROM Territory__c WHERE Name in :PostalCodes  and Country__c in :CountryCodes LIMIT 4000 ]){
                                         
                                         if(t.Territory_ID__c != null){
                                             TerritoryIds.add(t.Territory_ID__c);
                                         }
                                         if(t.MOL__C != null){
                                             TerritoryIds.add(t.MOL__C);
                                         }
                                         if(t.DHL__C != null){
                                             TerritoryIds.add(t.DHL__C);
                                         }
                                         if(t.RSC__C != null){
                                             TerritoryIds.add(t.RSC__C);
                                         }
                                         if(t.ETE__C != null){
                                             TerritoryIds.add(t.ETE__C);
                                         }
                                         if(t.IKAM__c != null){
                                             TerritoryIds.add(t.IKAM__c);
                                         }
   
                                         String zipMktSeg = t.ZipCode_Unique__c;
                                         TerrToAccMap.put(zipMktSeg, t.Territory_ID__c); 
                                         MolTerrToAccMap.put(zipMktSeg, t.MOL__C);
                                         DhlTerrToAccMap.put(zipMktSeg, t.DHL__C);
                                         SpgTerrToAccMap.put(zipMktSeg, t.RSC__C);
                                         ETeTerrToAccMap.put(zipMktSeg, t.ETE__C);
                                         IKAMTerrToAccMap.put(zipMktSeg, t.IKAM__c);
                                     }
            }
            
            //if (TerritoryIds.IsEmpty()) TerritoryIds.add('99999');
            TerritoryIds.add('99999');
            
            System.debug('@@ TerritoryIds: '+ TerritoryIds);
            Map<String, Id> mapTerritoryUser = new Map<String, Id>();
            
            for(User u: [SELECT Id, Name, Assigned_Territory_ID__c FROM User WHERE (Assigned_Territory_ID__c =:TerritoryIds) LIMIT 200]) {
                mapTerritoryUser.put(u.Assigned_Territory_ID__c, u.Id);
            }
            ///if(!mapTerritoryUser.IsEmpty()) {            
                for(Account acc :accList){
                    String zipMktSegAcc = acc.ShippingPostalCode; 
                    String zipMktSegAcccanada = acc.ShippingPostalCode.left(3); 
                    //if(acc.Group__c != 'International') {
                    //String t = mapAccountTerritory.get(acc.Id);
                    System.debug('@@ zipMktSegAcc: '+zipMktSegAcc);
                    System.debug('@@ zipMktSegAccCAnada: '+zipMktSegAcccanada);
                    String tc = TerrToAccMap.get(zipMktSegAcccanada);
                    String t = TerrToAccMap.get(zipMktSegAcc);
                    String m = MolTerrToAccMap.get(zipMktSegAcc);
                    String d = DhlTerrToAccMap.get(zipMktSegAcc);
                    String s = SpgTerrToAccMap.get(zipMktSegAcc);
                    String e = ETeTerrToAccMap.get(zipMktSegAcc);
                    String k = IKAMTerrToAccMap.get(zipMktSegAcc);
                    //Group is Key Accounts
                    if(acc.Group__c == 'Key Accounts') {
                        // Check if Accoutn Executive is Empty
                        System.debug('@@ acc.Ref_Lab_Dir__c1: '+acc.Ref_Lab_Dir__c);
                        System.debug('@@ acc.IDN_HSD__c1: '+acc.IDN_HSD__c);    
                        if(acc.IDN_HSD__c != null){
                            acc.OwnerId = acc.IDN_HSD__c;
                            System.debug('@@ acc.IDN_HSD__c: '+acc.IDN_HSD__c); 
                            //Check if Ref Lab Director
                        }else if(acc.Ref_Lab_Dir__c != null){
                            System.debug('@@ text test ');
                            System.debug('@@ acc.Ref_Lab_Dir__c: '+acc.Ref_Lab_Dir__c);                          
                            acc.OwnerId = acc.Ref_Lab_Dir__c;
                            
                        }               
                    }else if(acc.Group__c == 'Owned Accounts'){
                        if(t == null) {               
                            t = '99999';
                        } 
                        
                    }else if(acc.Group__c == 'Corporate'){
                        t = '99999';
                    }
                    /*else if(acc.Group__c == 'International'){
                        t = '99999';
                    }*/
                     System.debug('@@ testMap: '+mapTerritoryUser);
                    if(!mapTerritoryUser.isEmpty()){
                        //assign the owner id based on the territory id in territory object
                        if(mapTerritoryUser.containsKey(t) && (acc.Group__c != 'Key Accounts')) {                       
                            acc.OwnerId = mapTerritoryUser.get(t);
                        }
                        if(mapTerritoryUser.containsKey(tc) && (acc.Group__c != 'Key Accounts')) {                       
                            acc.OwnerId = mapTerritoryUser.get(tc);
                        }
                        //assign the Molecular Director based on the Mol Territory id in territory object
                        if(mapTerritoryUser.containsKey(m)) {
                            acc.MD__C = mapTerritoryUser.get(m);
                        }
                        else
                        {
                            acc.MD__C = Null;
                        }
                        //assign the DHI Specialist based on the DHI Territory id in territory object
                        if(mapTerritoryUser.containsKey(d)) {
                            acc.DHL__c = mapTerritoryUser.get(d); 
                        }
                        else {
                            acc.DHL__c = Null;
                        }
                        //assign the SPG Rep on the Reasearch Territory id in territory object
                        if(mapTerritoryUser.containsKey(s)) {
                            acc.SPG__c = mapTerritoryUser.get(s); 
                        }
                        else 
                        {
                            acc.SPG__c = Null; 
                            
                        }
                        //assign the Eye Health based on the Eye Territory id in territory object
                        if(mapTerritoryUser.containsKey(e)) {
                            acc.ETE_Rep__c = mapTerritoryUser.get(e); 
                        }
                        else 
                        {
                            acc.ETE_Rep__c = Null;
                        }
                        if(mapTerritoryUser.containsKey(k)) {
                            acc.Key_Account_Manager__c = mapTerritoryUser.get(k); 
                        }
                        else
                        {
                            acc.Key_Account_Manager__c = Null; 
                        }
                    }
            }

 
I have this issue wherein the account owner are not updating correctly, wherein, this lookup in a territoty object and user.

ex, the shipping country is united states, but the account owner is germany. how come that happen? I am not sure what to check in here, wherein when I update the record it will update correctly same goes with the batch. are there discrepancies in my apex class? thanks for the help!!

I have this trigger
 
trigger TerritoryAssignmentTrigger on Account (before insert, before update) {
    
    Set<Account> sIntAccountsCanada = new Set<Account>();
    Set<Account> sAccounts = new Set<Account>();
    /*
if(RecursionBlocker.flag){
if(trigger.isBefore && trigger.isInsert){
AccountTriggerHandler.InsertAccountOwner(trigger.new);
} 

if(trigger.isAfter && trigger.isUpdate){
AccountTriggerHandler.UpdateAccountOwner(trigger.new);
}   
}
*/    
    if(trigger.isBefore && trigger.isInsert){
        for(Account acc : Trigger.new) {
 if(acc.ShippingPostalCode != null ){
    sAccounts.add(acc);
}
            
        }
    } 
    
    if(trigger.isBefore && trigger.isUpdate){
        for(Account acc : Trigger.new) {
            system.debug(acc);
            if(acc.ShippingPostalCode != null ){
            sAccounts.add(acc);
            }
        }
    }
    
    Triggers__c t = Triggers__c.getInstance();
    if (t == null || t.Territory__c) {
        if(!sAccounts.isEmpty()){
        AccountTriggerHandler.InsertAccountOwner(sAccounts);         
        }
AccountTriggerHandler.insertAccountOwnerCanada(sIntAccountsCanada);
    }
}

I have this class
 
public static void insertAccountOwner(Set<Account> accList){
            set<String> TerritoryIds = new Set<String>();
            Map<Id, String> mapAccountTerritory = new Map<Id, String>();
            Set<String> PostalCodes = new Set<String>();
            Set<String> CountryCodes = new Set<String>();
            Set<String> MarketSegments = new Set<String>();
            
            Map<String,String> TerrToAccMap = new Map<String,String>();
            Map<String,String> MolTerrToAccMap = new Map<String,String>();
            Map<String,String> DhlTerrToAccMap = new Map<String,String>();
            Map<String,String> SpgTerrToAccMap = new Map<String,String>();
            Map<String,String> ETeTerrToAccMap = new Map<String,String>();
            Map<String,String> IKAMTerrToAccMap = new Map<String,String>();
            
                     for(Account acc :accList){
                
                //Add account zipcode if not international
                //if(acc.Group__c != 'International') {
                if (acc.ShippingPostalCode != null) PostalCodes.add(acc.ShippingPostalCode);
                   if (acc.ShippingPostalCode == null) {
                       acc.ShippingPostalCode = '';
                       PostalCodes.add(acc.ShippingPostalCode);
                   }
                         
                if (acc.ShippingPostalCode != null && acc.Group__c == 'Corporate' ) PostalCodes.add('99999');
                if (acc.ShippingPostalCode != null && acc.ShippingCountry =='Canada' ) PostalCodes.add(acc.ShippingPostalCode.left(3));
                if (acc.ShippingCountry != null) CountryCodes.add(acc.ShippingCountry);
                if (acc.MarketSegment__c != null) MarketSegments.add(acc.MarketSegment__c);
            }

            if (!PostalCodes.isEmpty()) {
                for(Territory__c t: [SELECT Id, Name, Territory_ID__c, Market_Segment__c, IKAM__c, MOL__C, DHL__C, ZipCode_Unique__c, Country__c, 
                                     RSC__C, ETE__C  FROM Territory__c WHERE Name in :PostalCodes  and Country__c in :CountryCodes LIMIT 4000 ]){
                                         
                                         if(t.Territory_ID__c != null){
                                             TerritoryIds.add(t.Territory_ID__c);
                                         }
                                         if(t.MOL__C != null){
                                             TerritoryIds.add(t.MOL__C);
                                         }
                                         if(t.DHL__C != null){
                                             TerritoryIds.add(t.DHL__C);
                                         }
                                         if(t.RSC__C != null){
                                             TerritoryIds.add(t.RSC__C);
                                         }
                                         if(t.ETE__C != null){
                                             TerritoryIds.add(t.ETE__C);
                                         }
                                         if(t.IKAM__c != null){
                                             TerritoryIds.add(t.IKAM__c);
                                         }
   
                                         String zipMktSeg = t.ZipCode_Unique__c;
                                         TerrToAccMap.put(zipMktSeg, t.Territory_ID__c); 
                                         MolTerrToAccMap.put(zipMktSeg, t.MOL__C);
                                         DhlTerrToAccMap.put(zipMktSeg, t.DHL__C);
                                         SpgTerrToAccMap.put(zipMktSeg, t.RSC__C);
                                         ETeTerrToAccMap.put(zipMktSeg, t.ETE__C);
                                         IKAMTerrToAccMap.put(zipMktSeg, t.IKAM__c);
                                     }
            }
            
            //if (TerritoryIds.IsEmpty()) TerritoryIds.add('99999');
            TerritoryIds.add('99999');
            
            System.debug('@@ TerritoryIds: '+ TerritoryIds);
            Map<String, Id> mapTerritoryUser = new Map<String, Id>();
            
            for(User u: [SELECT Id, Name, Assigned_Territory_ID__c FROM User WHERE (Assigned_Territory_ID__c =:TerritoryIds) LIMIT 200]) {
                mapTerritoryUser.put(u.Assigned_Territory_ID__c, u.Id);
            }
            ///if(!mapTerritoryUser.IsEmpty()) {            
                for(Account acc :accList){
                    String zipMktSegAcc = acc.ShippingPostalCode; 
                    String zipMktSegAcccanada = acc.ShippingPostalCode.left(3); 
                    //if(acc.Group__c != 'International') {
                    //String t = mapAccountTerritory.get(acc.Id);
                    System.debug('@@ zipMktSegAcc: '+zipMktSegAcc);
                    System.debug('@@ zipMktSegAccCAnada: '+zipMktSegAcccanada);
                    String tc = TerrToAccMap.get(zipMktSegAcccanada);
                    String t = TerrToAccMap.get(zipMktSegAcc);
                    String m = MolTerrToAccMap.get(zipMktSegAcc);
                    String d = DhlTerrToAccMap.get(zipMktSegAcc);
                    String s = SpgTerrToAccMap.get(zipMktSegAcc);
                    String e = ETeTerrToAccMap.get(zipMktSegAcc);
                    String k = IKAMTerrToAccMap.get(zipMktSegAcc);
                    //Group is Key Accounts
                    if(acc.Group__c == 'Key Accounts') {
                        // Check if Accoutn Executive is Empty
                        System.debug('@@ acc.Ref_Lab_Dir__c1: '+acc.Ref_Lab_Dir__c);
                        System.debug('@@ acc.IDN_HSD__c1: '+acc.IDN_HSD__c);    
                        if(acc.IDN_HSD__c != null){
                            acc.OwnerId = acc.IDN_HSD__c;
                            System.debug('@@ acc.IDN_HSD__c: '+acc.IDN_HSD__c); 
                            //Check if Ref Lab Director
                        }else if(acc.Ref_Lab_Dir__c != null){
                            System.debug('@@ text test ');
                            System.debug('@@ acc.Ref_Lab_Dir__c: '+acc.Ref_Lab_Dir__c);                          
                            acc.OwnerId = acc.Ref_Lab_Dir__c;
                            
                        }               
                    }else if(acc.Group__c == 'Owned Accounts'){
                        if(t == null) {               
                            t = '99999';
                        } 
                        
                    }else if(acc.Group__c == 'Corporate'){
                        t = '99999';
                    }
                    /*else if(acc.Group__c == 'International'){
                        t = '99999';
                    }*/
                     System.debug('@@ testMap: '+mapTerritoryUser);
                    if(!mapTerritoryUser.isEmpty()){
                        //assign the owner id based on the territory id in territory object
                        if(mapTerritoryUser.containsKey(t) && (acc.Group__c != 'Key Accounts')) {                       
                            acc.OwnerId = mapTerritoryUser.get(t);
                        }
                        if(mapTerritoryUser.containsKey(tc) && (acc.Group__c != 'Key Accounts')) {                       
                            acc.OwnerId = mapTerritoryUser.get(tc);
                        }
                        //assign the Molecular Director based on the Mol Territory id in territory object
                        if(mapTerritoryUser.containsKey(m)) {
                            acc.MD__C = mapTerritoryUser.get(m);
                        }
                        else
                        {
                            acc.MD__C = Null;
                        }
                        //assign the DHI Specialist based on the DHI Territory id in territory object
                        if(mapTerritoryUser.containsKey(d)) {
                            acc.DHL__c = mapTerritoryUser.get(d); 
                        }
                        else {
                            acc.DHL__c = Null;
                        }
                        //assign the SPG Rep on the Reasearch Territory id in territory object
                        if(mapTerritoryUser.containsKey(s)) {
                            acc.SPG__c = mapTerritoryUser.get(s); 
                        }
                        else 
                        {
                            acc.SPG__c = Null; 
                            
                        }
                        //assign the Eye Health based on the Eye Territory id in territory object
                        if(mapTerritoryUser.containsKey(e)) {
                            acc.ETE_Rep__c = mapTerritoryUser.get(e); 
                        }
                        else 
                        {
                            acc.ETE_Rep__c = Null;
                        }
                        if(mapTerritoryUser.containsKey(k)) {
                            acc.Key_Account_Manager__c = mapTerritoryUser.get(k); 
                        }
                        else
                        {
                            acc.Key_Account_Manager__c = Null; 
                        }
                    }
            }

 
I am experiencing DML Error 10001 ,

can you spot on which is needed to be optimize more in here.


public with sharing class UpdateStatus {
    public static final String ClsName  = 'UpdateStatus';
    public static boolean isExecuting=false;
    public static boolean isInvoked = false;
    public static boolean isCnclGSChkd = false;
    public static final String UpdateActiveStatus  = 'ActiveStatus' ;
    public static final String UpdateCancelStatus  = 'CancelStatus' ;
    public static final String UpdateRecType = 'RecTypeStat' ;
    public static final String UpdateCancelBff = 'CancelStats';
    public static final String  UpdateEndDate = 'UpdateEndDate';
    public static final string acctClient =Schema.SObjectType.Account.getRecordTypeInfosByName().get('Account - Client').getRecordTypeId();
    public static final string acctClientInt =  Schema.SObjectType.Account.getRecordTypeInfosByName().get('Account - InactiveClient').getRecordTypeId();
    public static final String  actv='Active';
    public static final String  cancl='Canceled';
    public static final String pendng =  'Pending';
    public static final String  accntCst= 'Account_Client';
    public static final String  cncled= 'Canceled';
    public static final String  inactv= 'Inactive';
    public static final Date enddateFuture = Date.newInstance(2100, 12, 31);
    public static  List<Id> cnclgmList = new List<Id>();
    public static final string profIntUser='Integration User';
    public static final string categNet='Verizon';
    

    public static void ActiveStatus(List<Group_Members> gmList)
    {

            Date EndDateFr;
            map<id,integer> prcOpn=new map<id,integer>();
            list<id> gpToProc=new list<id>();
            String profileName = [Select Name from Profile where Id = :UserInfo.getProfileId() limit 1].Name;
            for(Group_Members objGM : gmList){
                
                if(objGM.Status__c==pendng ){
                    gpToProc.add(objGM.Id);
                }
            }
            
            list<aggregateResult> PrcssLst=[select GM_ID,count(Id) OpenGM from WF_GM__c where GM_ID in:gpToProc 
                                              and (GA_Status__c='Closed') and GM_NS__c=null and GM_Sid__c !=null  group by GM_ID  limit 2000];
            for(aggregateResult agRst:PrcssLst)
            {
                prcOpn.put(string.valueof(agRst.get('GM_ID')),integer.valueof(agRst.get('OpenGM')));   
            }
            
            for(Group_Members objGM : gmList){
                if(objGM.EffDate__c<=system.today() && 
                   objGM.cancelDate__c==null){
                       EndDateFr = enddateFuture;
                   }
                else{
                    EndDateFr = objGM.cancelDate__c;
                }
                if(objGM.Status__c==pendng  && objGM.Network__c==categNet){
                    if(prcOpn.get(objGM.Id)>0)
                        objGM.Status__c=actv;
                }
                if(objGM.Status__c==pendng  && (objGM.Trans__c || objGM.Post__c)){
                    if(prcOpn.get(objGM.Id)>0)
                        objGM.Status__c=actv;
                }  
                if(profileName==profIntUser){
                    if(objGM.Status__c==cncled && EndDateFr>system.today() 
                       && objGM.EffDate__c<=system.today())
                    {
                        objGM.Status__c=actv;
                    }   
                }  
            }

    }

    public static void RecTypeStat(List<Group_Members> gmList)
    {
            set<id> accIds=new set<id>();
            Date gmEndDateFr;
            boolean isChnge=false;
            String profileName = [Select Name from Profile where Id = :UserInfo.getProfileId() limit 1].Name;
            Map<Id, Date> gmACCMap = new Map<Id, Date>();
            for(Group_Members objGM : gmList){
                gmACCMap.put(objGM.Account_c,objGM.EffDate__c);
                if(objGM.Status__c==actv && objGM.Network__c==categNet)
                {
                    accIds.add(objGM.Account_c);
                }
                if(objGM.Status__c==actv && (objGM.Trans__c || objGM.Post__c))
                {
                    accIds.add(objGM.Account_c);
                }
                
                if(profileName==profIntUser){
                    if(objGM.Status__c==cncled && gmEndDateFr>system.today() 
                       && objGM.EffDate__c<=system.today())
                    {
                        accIds.add(objGM.Account_c);
                    }
                }
                
            } 
            List<Account>  accLst =[Select id,RecordType.DeveloperName from Account WHERE ID IN :accIds Limit 50000] ;
            List<Account>  updtAccLst = New   List<Account>();
            
            if(!accIds.isEmpty()){
                for(Account objAcc : accLst){
                    if(objAcc.RecordType.DeveloperName != accntCst){
                        objAcc.RecordTypeId = acctClient;
                        objAcc.Account_Status__c=actv;
                        objAcc.CovCancelDate__c=null;
                        objAcc.EnrollDate__c = gmACCMap.get(objAcc.Id);
                        updtAccLst.add(objAcc);
                    }
                }
            }  
            
            if(!updtAccLst.isEmpty()){
                Database.update(updtAccLst);
            }
            isInvoked= true; 
        }
        
    }

    public static void CancelStats(List<Group_Members> grpmemList,map<id,Group_Members> grpmemListOld)
    {
            for(Group_Members grp:grpmemList)
            {
                boolean CnclChk=false;
                boolean CnclDteChk=false;
                if(grpmemListOld!=null)
                {
                    Group_Members grpOld=grpmemListOld.get(grp.Id);  
                    if(grp.cancelDate__c <> grpOld.cancelDate__c)
                        CnclChk=true;
                    if((grp.Status__c <> grpOld.Status__c) && grp.Status__c==cancl)
                    {
                        CnclDteChk=true;
                    }
                }
                else
                {
                    CnclChk=true;
                    if(grp.Status__c==cancl)
                    {
                        CnclDteChk=true; 
                    }
                }
                
                if(grp.cancelDate__c<=system.today() && CnclChk)
                {
                    grp.Status__c=cancl;
                    cnclgmList.add(grp.Id);
                    
                }
            }
            isCnclGSChkd = true;
        }
        
    }

    public static void CancelStatus(List<Group_Members> grpmemList,Map<ID,Group_Members> grpOldMap)
    {
            set<id> cnclAccIdsToPrcss=new set<id>();
            boolean isChnge=false;
            for(Group_Members grp:grpmemList)
            {
                if(grpOldMap !=null)
                {
                    Group_Members grpOld=grpOldMap.get(grp.Id);
                    if(grpOld.cancelDate__c !=grp.cancelDate__c  
                       || grpOld.Status__c !=grp.Status__c){
                           isChnge=true;     
                       }
                }
                
                else
                {
                    isChnge=true;
                }
                if(grp.cancelDate__c<=system.today() && isChnge)
                {
                    cnclAccIdsToPrcss.add(grp.Account_c);
                }
            }

            if(cnclAccIdsToPrcss.size() > 0){
                
                List<Account> accLst = [Select Id,Account_Status__c,RecordType.DeveloperName ,CovCancelDate__c,
                                        (select Status__c,cancelDate__c from Group_Member__r ORDER BY LastModifiedDate ASC)
                                        from Account where id in:cnclAccIdsToPrcss Limit 50000];
                List<Account>  acntIdsToPrcs = new List<Account>();
                List<Account>  finalacntIdsToPrcs = new List<Account>();
                Set<Id> processAccIds = New Set<Id>();
                boolean flag = false;
                Set<Id> accActv = New Set<Id> ();
                
                for(Account objAcc :accLst){
                    
                    if(!objAcc.Group_Member__r.isEmpty()){
                        for(Group_Members objGM : objAcc.Group_Member__r){
                            if(objGM.Status__c.equals(actv)){
                                flag = true;   
                                accActv.add(objAcc.id);
                                break;
                            }
                            else{
                                if(cnclgmList.contains(objGM.Id) && !processAccIds.contains(objAcc.id)  ){
                                    objAcc.CovCancelDate__c=objGM.cancelDate__c;
                                    objAcc.RecordTypeId =acctClientInt;
                                    objAcc.Account_Status__c=inactv;
                                    objAcc.EnrollDate__c=null;
                                    acntIdsToPrcs.add(objAcc); 
                                    processAccIds.add(objAcc.id);
                                }
                            }
                        }
                    }
                } 

                if(accActv.size() > 0){
                    processAccIds.removeAll(accActv);
                }

                for(Account accCus : acntIdsToPrcs){
                    if(processAccIds.contains(accCus.id)){
                        finalacntIdsToPrcs.add(accCus);
                    }
                }
                
                if(finalacntIdsToPrcs.size()>0 ){
                    
                    Database.update(acntIdsToPrcs);
                }
                
            }
            
            isExecuting=true;
      
    }
  
    public static void UpdateEndDate(List<Group_Members> grpmemList,map<id,Group_Members> grpmemListOld){
            List<id> gsIdLst = new List<id>();
            List<History__c> TCList = new List<History__c>(); 
            for(Group_Members grp:grpmemList)
            {
                if(grpmemListOld!=null)
                {
                    Group_Members grpOld=grpmemListOld.get(grp.Id);
                    
                    if(grp.History__c <> grpOld.History__c){
                        gsIdLst.add(grpOld.History__c);
                        
                    }
                } 
            }
            if(!gsIdLst.isEmpty()){
                for(History__c tp : [select id,EndDateTC__c,GA_TPB_Start_Date__c from History__c
                                                           where ID IN : gsIdLst Limit 50000]){
                                                               tp.EndDateTC__c = system.today()-1;
                                                               TCList.add(tp);                                                      
                                                           }
                Database.update(TCList);
            }
        }   
        
    }
}

 
global class UnlockRecordBatchJob implements Database.batchable<sObject> {
    //Start of this batch job
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id FROM Case LIMIT 50000000 '; //50 Million records
        return Database.getQueryLocator(query);
    }
    //Exeution of batch job
    global void execute(Database.BatchableContext BC, List<Case> scope) { //Scope max = 2000
        //List<Case> caseList = [SELECT Id From CaseLimit 2]; case already in scope varible
        //Check locked records
        List<Case> caseLockList = new List<Case>();
        for(Case c : scope)
        {
            if(Approval.isLocked(c.id)){
                caseLockList.add(c);
            }
        }
        
        if(!caseLockList.isEmpty()){
            //Unlock records
            List<Approval.UnlockResult> ulrList = Approval.unlock(caseLockList, false);
            
            // Iterate through each returned result
            for(Approval.UnlockResult  ulr : ulrList) {
                if (ulr.isSuccess()) {
                    //Operation was successful, so get the ID of the record that was processed
                    System.debug('Successfully locked account with ID: ' + ulr.getId());
                }
                else {
                    //Operation failed, so get all errors                
                    for(Database.Error err : ulr.getErrors()) {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Case fields that affected this error: ' + err.getFields());
                    }
                }
            }
        }
    }
    //finish job
    global void finish(Database.BatchableContext BC) {
    }
}

I am stuck at 22% the Execute is not being covered
 
Hi can you revise my code if it is not correct wherein I want to update all case records wherein I will unlock all of them. I tested one record and its updating but I think when its all or bulk its not updating.
 
global class UnlockRecordBatchJob implements Database.batchable<sObject> {
    //Start of this batch job
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id from Case Limit 2';
        return Database.getQueryLocator(query);
    }
    //Exeution of batch job
    global void execute(Database.BatchableContext BC, List<Case> scope) {
        List<Case> caseList = [SELECT Id From CaseLimit 2];
        //Check locked records
        List<Case> caseLockList = new List<Case>();
        for(Case c : caseList)
        {
            if(Approval.isLocked(c.id)){
                caseLockList.add(c);
            }
        }
        
        if(!caseLockList.isEmpty()){
            //Unlock records
            List<Approval.UnlockResult> ulrList = Approval.unlock(caseLockList, false);
            
            // Iterate through each returned result
            for(Approval.UnlockResult  ulr : ulrList) {
                if (ulr.isSuccess()) {
                    //Operation was successful, so get the ID of the record that was processed
                    System.debug('Successfully locked account with ID: ' + ulr.getId());
                }
                else {
                    //Operation failed, so get all errors                
                    for(Database.Error err : ulr.getErrors()) {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Case fields that affected this error: ' + err.getFields());
                    }
                }
            }
        }
    }
    //finish job
    global void finish(Database.BatchableContext BC) {
    }
}

 
public static void removeold(Set<Id> oldRecords){

    try{       
       ShareListoAgent = New List<SObject> ();
        ObjectName=new List<Id>(oldRecords).get(0).getSObjectType().getDescribe().getName();
        String queryStr ='select id,UserOrGroupId,parentid,RowCause  from';
        
        if(ObjectName == MemberUpper){
            queryStr = queryStr + ' MemberUpper_Share ';
        }
        if(ObjectName == MemberLower){
            queryStr = queryStr + ' MemberLower_Share ';
        }
        if(ObjectName == 'Account'){
            queryStr = 'select id,UserOrGroupId,AccountId,RowCause  from' + ' AccountShare where AccountId in:oldRecords and RowCause = \'Manual\'';
        }
        if(ObjectName == MemberLower || ObjectName == MemberUpper){
            queryStr = queryStr+'where ParentId in:oldRecords and RowCause = \'Manual\'';
        }
        ShareListoAgent.addAll(Database.query(queryStr));
        //ShareListoAgent = [select id,UserOrGroupId,parentid,RowCause  from MemberUpper_Share where parentid in: oldRecords and RowCause = 'Manual' ];
        system.debug('*******ShareListoAgent*******'+ShareListoAgent);
        if(ShareListoAgent !=null && ShareListoAgent.size()>0){
            delete ShareListoAgent;
        }
      }

 
public static void insertSharedRecord(Map<Id,Set<Id>>conRepMap, Map<Id,Set<ID>> conCovMemIDS){

     try{  
        createShareRecords = New List<Sobject>();
         for(id agentConId: conCovMemIDS.keyset()){
               if(conRepMap.containsKey(agentConId)){
                  for(id covRecID: conCovMemIDS.get(agentConId)){
                     for(id covUsrID: conRepMap.get(agentConId)){
                         SObject shareOBJ;
                         if(ObjectName == coverageMem){
                            shareOBJ = Schema.getGlobalDescribe().get('Coverage_Member__share').newSObject();  
                          }
                         if(ObjectName == coverage){
                         shareOBJ = Schema.getGlobalDescribe().get('Coverage__share').newSObject();  
                          } 
                         shareOBJ.put('ParentId', covRecId);
                         shareOBJ.put('UserOrGroupId', covUsrID);
                         shareOBJ.put('AccessLevel', 'Read');
                         shareOBJ.put('RowCause', 'Manual');
                         createShareRecords.add(shareOBJ);
                     }                    
                  }             
               }
         }             
        
      }

 
global class ChangingCapsLock{
    global static void Change( Account [] acc){
        for(Account a :acc){
            
            if(a.BillingPostalCode !=null )
                a.BillingPostalCode = allUpper(a.BillingPostalCode);
            
            if(a.BillingCountry !=null )
                a.BillingCountry= formatToUpper(a.BillingCountry);
            a.BillingCountry= formatToUpperLower(a.BillingCountry);
            
            if(a.BillingCountry ==null )
           String.isEmpty(a.BillingCountry);
            
            if(a.ShippingPostalCode !=null )
                a.ShippingPostalCode = allUpper(a.ShippingPostalCode);
            
            if(a.ShippingCountry !=null )
                a.ShippingCountry= formatToUpper(a.ShippingCountry);
            a.ShippingCountry= formatToUpperLower(a.ShippingCountry);
            
        }
    }
    public static String formatToUpper (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null  && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()) + ' ';
                }
                else
                    result += iter.substring(0,1).toUpperCase() + ' ';
            }
        }
        return result;
    }
    public static String allUpper (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()).toUpperCase() + ' ';
                }
                else
                    result += iter.substring(0,1).toUpperCase() + ' ';
            }
        }
        return result;
    }
    public static String formatToUpperLower (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()).toLowerCase() + ' ';
                }
                else
                    result += iter.substring(0,1).toLowercase() + ' ';
            }
        }
        return result;
    }
}
 
trigger AccountChangerFirstLetter on Account (before insert, before update) {
 ChangingCapsLock.Change(trigger.new);
      if(trigger.isBefore )
         if(trigger.IsInsert ||trigger.IsUpdate )
           ChangingCapsLock.Change(trigger.new);    
}

 
I have this code, wherein it deletes the record when there is a value, how can I achieve to update if the values like UserIdforCsr is just the same?
public static void NewSharing(Set<Id> oldRecords){
        try{       
            CSRShareList = New List<SObject> ();
            ObjectName=new List<Id>(oldRecords).get(0).getSObjectType().getDescribe().getName();
            String strqy ='select id,UserIdforCSR,parentid,RowCause  from';
            
            if(ObjectName == assMember){
                strqy = strqy + ' Assistant_Sharing ';
            }
            if(ObjectName == secMember){
                strqy = strqy + ' Secretary_Sharing ';
            }
            if(ObjectName == 'Account'){
                strqy = 'select id,UserIdforCSR,AccountId,RowCause  from' + ' AccountShare where AccountId in:oldRecords';
            }
            if(ObjectName == secMember || ObjectName == assMember){
                strqy = strqy+'where ParentId in:oldRecords ';
            }
            CSRShareList.addAll(Database.query(strqy));

            if(CSRShareList !=null && CSRShareList.size()>0){
                delete CSRShareList;
            }
        }

 
Issue is that sometimes it deletes sometime it doesn't delete or update.
 
global class AccountContactTriggerHandler implements Database.Batchable<sObject>
{
    List<AccountContactRelation> ListtoInsert = new List<AccountContactRelation>();
    Set<accountContactRelation> ListToDelete = new Set<accountContactRelation>();
    Map<String, Account> accCodeMap = new Map<String,Account>();
    map<string,Contact> contactAccountMap = new map<string, Contact>();
    String query = 'Select Id,Name,License_ID__c FROM Account WHERE License_ID__c != null AND IsPartner = true AND License_ID__c LIKE \'__\'';
    final String CLSSNAME = 'AccountContactTriggerHandler';
 
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc,List<Account> batch){
        try{
            for(Account a : batch)
                accCodeMap.put(a.License_ID__c, a);

            for (Contact c : [Select ID, Name, Accountid, Person_ID__c, ABS_Person_ID__c, (SELECT AccountId, ContactId FROM AccountContactRelations) from Contact WHERE (ABS_Person_ID__c != null AND ABS_Person_ID__c LIKE '__') OR (Person_ID__c != null AND Person_ID__c LIKE '__')]){
                Set<String> acrIdList =new Set<String>();
                List<AccountContactRelation> acrList = c.AccountContactRelations;
                for(AccountContactRelation acrId : acrList){
                    contactAccountMap.put(acrId.AccountId, c); // Used for deleting code soql
                    acrIdList.add(acrId.AccountId);
                }

                Account a, a2;
                if(c.Person_ID__c != null)
                    a = accCodeMap.get(c.Person_ID__c);
                if(c.ABS_Person_ID__c != null)
                    a2 = accCodeMap.get(c.ABS_Person_ID__c);
                
                if(a != null && a2 != null && a == a2){
                    if(!acrIdList.contains(a.Id)){
                        if(c.Person_ID__c == a.License_ID__c){
                            AccountContactRelation   acr =  new AccountContactRelation();
                            acr.AccountId = a.id;
                            acr.contactId = c.Id;
                            ListtoInsert.add(acr);
                        }
                    }
                }
                else {
                    // Checks if the AccountContactRelations already connected to the Contact
                    if(a != null){
                        if(!acrIdList.contains(a.Id)){
                            if(c.Person_ID__c == a.License_ID__c){
                                AccountContactRelation   acr =  new AccountContactRelation();
                                acr.AccountId = a.id;
                                acr.contactId = c.Id;
                                ListtoInsert.add(acr);
                            }
                        }
                    } 
                    
                    if(a2 != null){
                        if(!acrIdList.contains(a2.Id)){
                            if(c.ABS_Person_ID__c == a2.License_ID__c){
                                AccountContactRelation   acr =  new AccountContactRelation();
                                acr.AccountId = a2.id;
                                acr.contactId = c.Id;
                                ListtoInsert.add(acr);
                            }
                        }
                    }
                }                
            }
            insert ListtoInsert;
            //loop only the accounts that are related/connected to AccountContactRelation Object
            map<string,Account> accountMap = new map<string, Account>();
            for(Account Acc: [SELECT id, Name, License_ID__c FROM Account WHERE Id =: contactAccountMap.keySet()])
            {
                accountMap.put(Acc.Id,acc);
            }
            //loop the AccountContactRelation to get the records where isDirect is not true
            for(AccountContactRelation AccountConDelete : [SELECT Id, AccountId, ContactId FROM AccountContactRelation WHERE Accountid =: contactAccountMap.keySet() AND isDirect != TRUE])
            {
                Account acc = accountMap.get(AccountConDelete.AccountId);
                contact con = contactAccountMap.get(AccountConDelete.AccountId);
                if(acc.License_ID__c != con.Person_ID__c && acc.License_ID__c != con.ABS_Person_ID__c)
                {
                    ListToDelete.add(AccountConDelete);    
                }
            }

            System.debug('TO BE DELETED: '+ListToDelete);  
            List<AccountContactRelation> AccountConNew = new List<AccountContactRelation>();
            for (AccountContactRelation acr : ListToDelete)
                AccountConNew.add(acr);
            
            delete AccountConNew;
        }																				
        catch(Exception e){
            
        }
    }	
    
    global void finish(Database.BatchableContext bc)
    {
        //DoNothing.
    }
}

 
I have this issue wherein the account owner are not updating correctly, wherein, this lookup in a territoty object and user.

ex, the shipping country is united states, but the account owner is germany. how come that happen? I am not sure what to check in here, wherein when I update the record it will update correctly same goes with the batch. are there discrepancies in my apex class? thanks for the help!!

I have this trigger
 
trigger TerritoryAssignmentTrigger on Account (before insert, before update) {
    
    Set<Account> sIntAccountsCanada = new Set<Account>();
    Set<Account> sAccounts = new Set<Account>();
    /*
if(RecursionBlocker.flag){
if(trigger.isBefore && trigger.isInsert){
AccountTriggerHandler.InsertAccountOwner(trigger.new);
} 

if(trigger.isAfter && trigger.isUpdate){
AccountTriggerHandler.UpdateAccountOwner(trigger.new);
}   
}
*/    
    if(trigger.isBefore && trigger.isInsert){
        for(Account acc : Trigger.new) {
 if(acc.ShippingPostalCode != null ){
    sAccounts.add(acc);
}
            
        }
    } 
    
    if(trigger.isBefore && trigger.isUpdate){
        for(Account acc : Trigger.new) {
            system.debug(acc);
            if(acc.ShippingPostalCode != null ){
            sAccounts.add(acc);
            }
        }
    }
    
    Triggers__c t = Triggers__c.getInstance();
    if (t == null || t.Territory__c) {
        if(!sAccounts.isEmpty()){
        AccountTriggerHandler.InsertAccountOwner(sAccounts);         
        }
AccountTriggerHandler.insertAccountOwnerCanada(sIntAccountsCanada);
    }
}

I have this class
 
public static void insertAccountOwner(Set<Account> accList){
            set<String> TerritoryIds = new Set<String>();
            Map<Id, String> mapAccountTerritory = new Map<Id, String>();
            Set<String> PostalCodes = new Set<String>();
            Set<String> CountryCodes = new Set<String>();
            Set<String> MarketSegments = new Set<String>();
            
            Map<String,String> TerrToAccMap = new Map<String,String>();
            Map<String,String> MolTerrToAccMap = new Map<String,String>();
            Map<String,String> DhlTerrToAccMap = new Map<String,String>();
            Map<String,String> SpgTerrToAccMap = new Map<String,String>();
            Map<String,String> ETeTerrToAccMap = new Map<String,String>();
            Map<String,String> IKAMTerrToAccMap = new Map<String,String>();
            
                     for(Account acc :accList){
                
                //Add account zipcode if not international
                //if(acc.Group__c != 'International') {
                if (acc.ShippingPostalCode != null) PostalCodes.add(acc.ShippingPostalCode);
                   if (acc.ShippingPostalCode == null) {
                       acc.ShippingPostalCode = '';
                       PostalCodes.add(acc.ShippingPostalCode);
                   }
                         
                if (acc.ShippingPostalCode != null && acc.Group__c == 'Corporate' ) PostalCodes.add('99999');
                if (acc.ShippingPostalCode != null && acc.ShippingCountry =='Canada' ) PostalCodes.add(acc.ShippingPostalCode.left(3));
                if (acc.ShippingCountry != null) CountryCodes.add(acc.ShippingCountry);
                if (acc.MarketSegment__c != null) MarketSegments.add(acc.MarketSegment__c);
            }

            if (!PostalCodes.isEmpty()) {
                for(Territory__c t: [SELECT Id, Name, Territory_ID__c, Market_Segment__c, IKAM__c, MOL__C, DHL__C, ZipCode_Unique__c, Country__c, 
                                     RSC__C, ETE__C  FROM Territory__c WHERE Name in :PostalCodes  and Country__c in :CountryCodes LIMIT 4000 ]){
                                         
                                         if(t.Territory_ID__c != null){
                                             TerritoryIds.add(t.Territory_ID__c);
                                         }
                                         if(t.MOL__C != null){
                                             TerritoryIds.add(t.MOL__C);
                                         }
                                         if(t.DHL__C != null){
                                             TerritoryIds.add(t.DHL__C);
                                         }
                                         if(t.RSC__C != null){
                                             TerritoryIds.add(t.RSC__C);
                                         }
                                         if(t.ETE__C != null){
                                             TerritoryIds.add(t.ETE__C);
                                         }
                                         if(t.IKAM__c != null){
                                             TerritoryIds.add(t.IKAM__c);
                                         }
   
                                         String zipMktSeg = t.ZipCode_Unique__c;
                                         TerrToAccMap.put(zipMktSeg, t.Territory_ID__c); 
                                         MolTerrToAccMap.put(zipMktSeg, t.MOL__C);
                                         DhlTerrToAccMap.put(zipMktSeg, t.DHL__C);
                                         SpgTerrToAccMap.put(zipMktSeg, t.RSC__C);
                                         ETeTerrToAccMap.put(zipMktSeg, t.ETE__C);
                                         IKAMTerrToAccMap.put(zipMktSeg, t.IKAM__c);
                                     }
            }
            
            //if (TerritoryIds.IsEmpty()) TerritoryIds.add('99999');
            TerritoryIds.add('99999');
            
            System.debug('@@ TerritoryIds: '+ TerritoryIds);
            Map<String, Id> mapTerritoryUser = new Map<String, Id>();
            
            for(User u: [SELECT Id, Name, Assigned_Territory_ID__c FROM User WHERE (Assigned_Territory_ID__c =:TerritoryIds) LIMIT 200]) {
                mapTerritoryUser.put(u.Assigned_Territory_ID__c, u.Id);
            }
            ///if(!mapTerritoryUser.IsEmpty()) {            
                for(Account acc :accList){
                    String zipMktSegAcc = acc.ShippingPostalCode; 
                    String zipMktSegAcccanada = acc.ShippingPostalCode.left(3); 
                    //if(acc.Group__c != 'International') {
                    //String t = mapAccountTerritory.get(acc.Id);
                    System.debug('@@ zipMktSegAcc: '+zipMktSegAcc);
                    System.debug('@@ zipMktSegAccCAnada: '+zipMktSegAcccanada);
                    String tc = TerrToAccMap.get(zipMktSegAcccanada);
                    String t = TerrToAccMap.get(zipMktSegAcc);
                    String m = MolTerrToAccMap.get(zipMktSegAcc);
                    String d = DhlTerrToAccMap.get(zipMktSegAcc);
                    String s = SpgTerrToAccMap.get(zipMktSegAcc);
                    String e = ETeTerrToAccMap.get(zipMktSegAcc);
                    String k = IKAMTerrToAccMap.get(zipMktSegAcc);
                    //Group is Key Accounts
                    if(acc.Group__c == 'Key Accounts') {
                        // Check if Accoutn Executive is Empty
                        System.debug('@@ acc.Ref_Lab_Dir__c1: '+acc.Ref_Lab_Dir__c);
                        System.debug('@@ acc.IDN_HSD__c1: '+acc.IDN_HSD__c);    
                        if(acc.IDN_HSD__c != null){
                            acc.OwnerId = acc.IDN_HSD__c;
                            System.debug('@@ acc.IDN_HSD__c: '+acc.IDN_HSD__c); 
                            //Check if Ref Lab Director
                        }else if(acc.Ref_Lab_Dir__c != null){
                            System.debug('@@ text test ');
                            System.debug('@@ acc.Ref_Lab_Dir__c: '+acc.Ref_Lab_Dir__c);                          
                            acc.OwnerId = acc.Ref_Lab_Dir__c;
                            
                        }               
                    }else if(acc.Group__c == 'Owned Accounts'){
                        if(t == null) {               
                            t = '99999';
                        } 
                        
                    }else if(acc.Group__c == 'Corporate'){
                        t = '99999';
                    }
                    /*else if(acc.Group__c == 'International'){
                        t = '99999';
                    }*/
                     System.debug('@@ testMap: '+mapTerritoryUser);
                    if(!mapTerritoryUser.isEmpty()){
                        //assign the owner id based on the territory id in territory object
                        if(mapTerritoryUser.containsKey(t) && (acc.Group__c != 'Key Accounts')) {                       
                            acc.OwnerId = mapTerritoryUser.get(t);
                        }
                        if(mapTerritoryUser.containsKey(tc) && (acc.Group__c != 'Key Accounts')) {                       
                            acc.OwnerId = mapTerritoryUser.get(tc);
                        }
                        //assign the Molecular Director based on the Mol Territory id in territory object
                        if(mapTerritoryUser.containsKey(m)) {
                            acc.MD__C = mapTerritoryUser.get(m);
                        }
                        else
                        {
                            acc.MD__C = Null;
                        }
                        //assign the DHI Specialist based on the DHI Territory id in territory object
                        if(mapTerritoryUser.containsKey(d)) {
                            acc.DHL__c = mapTerritoryUser.get(d); 
                        }
                        else {
                            acc.DHL__c = Null;
                        }
                        //assign the SPG Rep on the Reasearch Territory id in territory object
                        if(mapTerritoryUser.containsKey(s)) {
                            acc.SPG__c = mapTerritoryUser.get(s); 
                        }
                        else 
                        {
                            acc.SPG__c = Null; 
                            
                        }
                        //assign the Eye Health based on the Eye Territory id in territory object
                        if(mapTerritoryUser.containsKey(e)) {
                            acc.ETE_Rep__c = mapTerritoryUser.get(e); 
                        }
                        else 
                        {
                            acc.ETE_Rep__c = Null;
                        }
                        if(mapTerritoryUser.containsKey(k)) {
                            acc.Key_Account_Manager__c = mapTerritoryUser.get(k); 
                        }
                        else
                        {
                            acc.Key_Account_Manager__c = Null; 
                        }
                    }
            }

 
I am experiencing DML Error 10001 ,

can you spot on which is needed to be optimize more in here.


public with sharing class UpdateStatus {
    public static final String ClsName  = 'UpdateStatus';
    public static boolean isExecuting=false;
    public static boolean isInvoked = false;
    public static boolean isCnclGSChkd = false;
    public static final String UpdateActiveStatus  = 'ActiveStatus' ;
    public static final String UpdateCancelStatus  = 'CancelStatus' ;
    public static final String UpdateRecType = 'RecTypeStat' ;
    public static final String UpdateCancelBff = 'CancelStats';
    public static final String  UpdateEndDate = 'UpdateEndDate';
    public static final string acctClient =Schema.SObjectType.Account.getRecordTypeInfosByName().get('Account - Client').getRecordTypeId();
    public static final string acctClientInt =  Schema.SObjectType.Account.getRecordTypeInfosByName().get('Account - InactiveClient').getRecordTypeId();
    public static final String  actv='Active';
    public static final String  cancl='Canceled';
    public static final String pendng =  'Pending';
    public static final String  accntCst= 'Account_Client';
    public static final String  cncled= 'Canceled';
    public static final String  inactv= 'Inactive';
    public static final Date enddateFuture = Date.newInstance(2100, 12, 31);
    public static  List<Id> cnclgmList = new List<Id>();
    public static final string profIntUser='Integration User';
    public static final string categNet='Verizon';
    

    public static void ActiveStatus(List<Group_Members> gmList)
    {

            Date EndDateFr;
            map<id,integer> prcOpn=new map<id,integer>();
            list<id> gpToProc=new list<id>();
            String profileName = [Select Name from Profile where Id = :UserInfo.getProfileId() limit 1].Name;
            for(Group_Members objGM : gmList){
                
                if(objGM.Status__c==pendng ){
                    gpToProc.add(objGM.Id);
                }
            }
            
            list<aggregateResult> PrcssLst=[select GM_ID,count(Id) OpenGM from WF_GM__c where GM_ID in:gpToProc 
                                              and (GA_Status__c='Closed') and GM_NS__c=null and GM_Sid__c !=null  group by GM_ID  limit 2000];
            for(aggregateResult agRst:PrcssLst)
            {
                prcOpn.put(string.valueof(agRst.get('GM_ID')),integer.valueof(agRst.get('OpenGM')));   
            }
            
            for(Group_Members objGM : gmList){
                if(objGM.EffDate__c<=system.today() && 
                   objGM.cancelDate__c==null){
                       EndDateFr = enddateFuture;
                   }
                else{
                    EndDateFr = objGM.cancelDate__c;
                }
                if(objGM.Status__c==pendng  && objGM.Network__c==categNet){
                    if(prcOpn.get(objGM.Id)>0)
                        objGM.Status__c=actv;
                }
                if(objGM.Status__c==pendng  && (objGM.Trans__c || objGM.Post__c)){
                    if(prcOpn.get(objGM.Id)>0)
                        objGM.Status__c=actv;
                }  
                if(profileName==profIntUser){
                    if(objGM.Status__c==cncled && EndDateFr>system.today() 
                       && objGM.EffDate__c<=system.today())
                    {
                        objGM.Status__c=actv;
                    }   
                }  
            }

    }

    public static void RecTypeStat(List<Group_Members> gmList)
    {
            set<id> accIds=new set<id>();
            Date gmEndDateFr;
            boolean isChnge=false;
            String profileName = [Select Name from Profile where Id = :UserInfo.getProfileId() limit 1].Name;
            Map<Id, Date> gmACCMap = new Map<Id, Date>();
            for(Group_Members objGM : gmList){
                gmACCMap.put(objGM.Account_c,objGM.EffDate__c);
                if(objGM.Status__c==actv && objGM.Network__c==categNet)
                {
                    accIds.add(objGM.Account_c);
                }
                if(objGM.Status__c==actv && (objGM.Trans__c || objGM.Post__c))
                {
                    accIds.add(objGM.Account_c);
                }
                
                if(profileName==profIntUser){
                    if(objGM.Status__c==cncled && gmEndDateFr>system.today() 
                       && objGM.EffDate__c<=system.today())
                    {
                        accIds.add(objGM.Account_c);
                    }
                }
                
            } 
            List<Account>  accLst =[Select id,RecordType.DeveloperName from Account WHERE ID IN :accIds Limit 50000] ;
            List<Account>  updtAccLst = New   List<Account>();
            
            if(!accIds.isEmpty()){
                for(Account objAcc : accLst){
                    if(objAcc.RecordType.DeveloperName != accntCst){
                        objAcc.RecordTypeId = acctClient;
                        objAcc.Account_Status__c=actv;
                        objAcc.CovCancelDate__c=null;
                        objAcc.EnrollDate__c = gmACCMap.get(objAcc.Id);
                        updtAccLst.add(objAcc);
                    }
                }
            }  
            
            if(!updtAccLst.isEmpty()){
                Database.update(updtAccLst);
            }
            isInvoked= true; 
        }
        
    }

    public static void CancelStats(List<Group_Members> grpmemList,map<id,Group_Members> grpmemListOld)
    {
            for(Group_Members grp:grpmemList)
            {
                boolean CnclChk=false;
                boolean CnclDteChk=false;
                if(grpmemListOld!=null)
                {
                    Group_Members grpOld=grpmemListOld.get(grp.Id);  
                    if(grp.cancelDate__c <> grpOld.cancelDate__c)
                        CnclChk=true;
                    if((grp.Status__c <> grpOld.Status__c) && grp.Status__c==cancl)
                    {
                        CnclDteChk=true;
                    }
                }
                else
                {
                    CnclChk=true;
                    if(grp.Status__c==cancl)
                    {
                        CnclDteChk=true; 
                    }
                }
                
                if(grp.cancelDate__c<=system.today() && CnclChk)
                {
                    grp.Status__c=cancl;
                    cnclgmList.add(grp.Id);
                    
                }
            }
            isCnclGSChkd = true;
        }
        
    }

    public static void CancelStatus(List<Group_Members> grpmemList,Map<ID,Group_Members> grpOldMap)
    {
            set<id> cnclAccIdsToPrcss=new set<id>();
            boolean isChnge=false;
            for(Group_Members grp:grpmemList)
            {
                if(grpOldMap !=null)
                {
                    Group_Members grpOld=grpOldMap.get(grp.Id);
                    if(grpOld.cancelDate__c !=grp.cancelDate__c  
                       || grpOld.Status__c !=grp.Status__c){
                           isChnge=true;     
                       }
                }
                
                else
                {
                    isChnge=true;
                }
                if(grp.cancelDate__c<=system.today() && isChnge)
                {
                    cnclAccIdsToPrcss.add(grp.Account_c);
                }
            }

            if(cnclAccIdsToPrcss.size() > 0){
                
                List<Account> accLst = [Select Id,Account_Status__c,RecordType.DeveloperName ,CovCancelDate__c,
                                        (select Status__c,cancelDate__c from Group_Member__r ORDER BY LastModifiedDate ASC)
                                        from Account where id in:cnclAccIdsToPrcss Limit 50000];
                List<Account>  acntIdsToPrcs = new List<Account>();
                List<Account>  finalacntIdsToPrcs = new List<Account>();
                Set<Id> processAccIds = New Set<Id>();
                boolean flag = false;
                Set<Id> accActv = New Set<Id> ();
                
                for(Account objAcc :accLst){
                    
                    if(!objAcc.Group_Member__r.isEmpty()){
                        for(Group_Members objGM : objAcc.Group_Member__r){
                            if(objGM.Status__c.equals(actv)){
                                flag = true;   
                                accActv.add(objAcc.id);
                                break;
                            }
                            else{
                                if(cnclgmList.contains(objGM.Id) && !processAccIds.contains(objAcc.id)  ){
                                    objAcc.CovCancelDate__c=objGM.cancelDate__c;
                                    objAcc.RecordTypeId =acctClientInt;
                                    objAcc.Account_Status__c=inactv;
                                    objAcc.EnrollDate__c=null;
                                    acntIdsToPrcs.add(objAcc); 
                                    processAccIds.add(objAcc.id);
                                }
                            }
                        }
                    }
                } 

                if(accActv.size() > 0){
                    processAccIds.removeAll(accActv);
                }

                for(Account accCus : acntIdsToPrcs){
                    if(processAccIds.contains(accCus.id)){
                        finalacntIdsToPrcs.add(accCus);
                    }
                }
                
                if(finalacntIdsToPrcs.size()>0 ){
                    
                    Database.update(acntIdsToPrcs);
                }
                
            }
            
            isExecuting=true;
      
    }
  
    public static void UpdateEndDate(List<Group_Members> grpmemList,map<id,Group_Members> grpmemListOld){
            List<id> gsIdLst = new List<id>();
            List<History__c> TCList = new List<History__c>(); 
            for(Group_Members grp:grpmemList)
            {
                if(grpmemListOld!=null)
                {
                    Group_Members grpOld=grpmemListOld.get(grp.Id);
                    
                    if(grp.History__c <> grpOld.History__c){
                        gsIdLst.add(grpOld.History__c);
                        
                    }
                } 
            }
            if(!gsIdLst.isEmpty()){
                for(History__c tp : [select id,EndDateTC__c,GA_TPB_Start_Date__c from History__c
                                                           where ID IN : gsIdLst Limit 50000]){
                                                               tp.EndDateTC__c = system.today()-1;
                                                               TCList.add(tp);                                                      
                                                           }
                Database.update(TCList);
            }
        }   
        
    }
}

 
Hi can you revise my code if it is not correct wherein I want to update all case records wherein I will unlock all of them. I tested one record and its updating but I think when its all or bulk its not updating.
 
global class UnlockRecordBatchJob implements Database.batchable<sObject> {
    //Start of this batch job
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id from Case Limit 2';
        return Database.getQueryLocator(query);
    }
    //Exeution of batch job
    global void execute(Database.BatchableContext BC, List<Case> scope) {
        List<Case> caseList = [SELECT Id From CaseLimit 2];
        //Check locked records
        List<Case> caseLockList = new List<Case>();
        for(Case c : caseList)
        {
            if(Approval.isLocked(c.id)){
                caseLockList.add(c);
            }
        }
        
        if(!caseLockList.isEmpty()){
            //Unlock records
            List<Approval.UnlockResult> ulrList = Approval.unlock(caseLockList, false);
            
            // Iterate through each returned result
            for(Approval.UnlockResult  ulr : ulrList) {
                if (ulr.isSuccess()) {
                    //Operation was successful, so get the ID of the record that was processed
                    System.debug('Successfully locked account with ID: ' + ulr.getId());
                }
                else {
                    //Operation failed, so get all errors                
                    for(Database.Error err : ulr.getErrors()) {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Case fields that affected this error: ' + err.getFields());
                    }
                }
            }
        }
    }
    //finish job
    global void finish(Database.BatchableContext BC) {
    }
}

 
global class ChangingCapsLock{
    global static void Change( Account [] acc){
        for(Account a :acc){
            
            if(a.BillingPostalCode !=null )
                a.BillingPostalCode = allUpper(a.BillingPostalCode);
            
            if(a.BillingCountry !=null )
                a.BillingCountry= formatToUpper(a.BillingCountry);
            a.BillingCountry= formatToUpperLower(a.BillingCountry);
            
            if(a.BillingCountry ==null )
           String.isEmpty(a.BillingCountry);
            
            if(a.ShippingPostalCode !=null )
                a.ShippingPostalCode = allUpper(a.ShippingPostalCode);
            
            if(a.ShippingCountry !=null )
                a.ShippingCountry= formatToUpper(a.ShippingCountry);
            a.ShippingCountry= formatToUpperLower(a.ShippingCountry);
            
        }
    }
    public static String formatToUpper (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null  && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()) + ' ';
                }
                else
                    result += iter.substring(0,1).toUpperCase() + ' ';
            }
        }
        return result;
    }
    public static String allUpper (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()).toUpperCase() + ' ';
                }
                else
                    result += iter.substring(0,1).toUpperCase() + ' ';
            }
        }
        return result;
    }
    public static String formatToUpperLower (String Str) {
        String result = '';
        for (String iter : Str.split('[ ]+')) {
            if (iter != null && iter != '') {
                if (iter.length() > 1) {
                    result += iter.substring(0,1).toUpperCase() + iter.substring(1,iter.length()).toLowerCase() + ' ';
                }
                else
                    result += iter.substring(0,1).toLowercase() + ' ';
            }
        }
        return result;
    }
}
 
trigger AccountChangerFirstLetter on Account (before insert, before update) {
 ChangingCapsLock.Change(trigger.new);
      if(trigger.isBefore )
         if(trigger.IsInsert ||trigger.IsUpdate )
           ChangingCapsLock.Change(trigger.new);    
}

 
How to call this apex class to make it a batch job?
 
public class ApplicationYearsinService{

    public static void YearsinService(List<Application__c> appList){
        //Declares the Variables, List, ID to be used
        Date dat = System.today();
        Integer yr = dat.year();   
        Map<Id, Set<Integer>> setofYear = new Map<Id, Set<Integer>>();
        Set<Id> accountIdSet = new set<Id>();
        
        //Gets the values of the Account(Account__c from the Application
        for(Application__c cs: appList ){
            accountIdSet.add(cs.Account__c);            
        }
        
        //Query in the Application to get the value from the Account
        for(Application__c p : [SELECT ID, Account__c, Received_Date__c from Application__c where Account__c IN : accountIdSet ]){
            if(p.Received_Date__c != null){
                if(setofYear.containskey(p.Account__c)){
                    if(p.Received_Date__c != NULL) {
                        setofYear.get(p.Account__c).add(p.Received_Date__c.Year());
                    }
                }
                else {
                    setofYear.put(p.Account__c, new Set<Integer>{p.Received_Date__c.Year()});
                }     
            }
        }
        
        Map<String, List<Application__c>> appMap = new Map<String ,List<Application__c>>();
        Map<String, Account> lisAcct = new  Map<String, Account>();
        List<Account> acctToUpdate = new  List<Account>();
        List<Account> accountListToLoop = [Select Id, YearsinService__c, (Select Id FROM Applications__r LIMIT 1) from Account where Id=:accountIdSet];
        for(Account acc: accountListToLoop){
            lisAcct.put(acc.Id+'', acc);
        }       
        for(Account act : accountListToLoop ){
            if(setofYear.containskey(act.id)){
                act.YearsinService__c = setofYear.get(act.id).size();
                acctToUpdate.add(act);
                lisAcct.remove(act.Id+'');
            }
            else {
                act.YearsinService__c = 0;
                acctToUpdate.add(act);
            }
        }
        Database.upsert(acctToUpdate, false); 
    }
}

 
How do I assign a permission set on  newly created partner user?
 
public class AssignPermissionSet {
    
    public static void assignperm(List<user> userlist){
        Set<ID> usersId = new Set<Id>();
        Set<Id> contactIdsSet = new Set<Id>();
        List<PermissionSetAssignment> permissionSetList = new List<PermissionSetAssignment>();
        
        
        for (User u : [Select Id, Name, ProfileId FROM User Where Id IN : userlist]){ // Add fields as per your requirement...
            if(u.ProfileId == '00e360003429432'){
            PermissionSetAssignment psa = new PermissionSetAssignment (PermissionSetId = '0PS33609skjojsae', AssigneeId = u.Id);
            permissionSetList.add(psa);
                }
        }
        insert permissionSetList;
    }
}

 
HI 

I am encountering and error while doing a data load.

here is my code when dataloading. is there anything that needs to be optimize in here so far?
 
public class depToAccount {
    public static void deptpAccountV1(List<Dependent__c> depmem) {
        Set<Id> accountIdSet = new Set<Id>();
        Set<Id> coverIdSet = new Set<Id>();
        Map<Id, List<Dependent__c>> atoDep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ctomeddep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> cto19belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ato19belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> cto20belowdep = new Map<Id, List<Dependent__c>>();
        Map<Id, List<Dependent__c>> ato20updep = new Map<Id, List<Dependent__c>>();//
        List<CampaignMember> cmList = new List<CampaignMember>();
        
        Map<Id, Account> accountToUpdateMap = new Map<Id, Account>();
        
        
        for(Dependent__c depm : depmem){
            if(depm.status__c == 'ACTIVE' && depm.Catg__c == 'Vision'){
                if(depm.Account__c != null){
                    accountIdSet.add(depm.Account__c);
                }
                if(depm.Cover__c != null){
                    coverIdSet.add(depm.Cover__c); 
                }
            }
        }
        
        List<Dependent__c> existingDependent = [SELECT Id, Account__c, Account__r.Name, Cover__c, Cover__r.Comply__c,Rel__c, status__c, Catg__c, Age_Today__c 
                                                            FROM Dependent__c 
                                                            WHERE ((Cover__c IN: coverIdSet AND Cover__c != null)
                                                                   OR (Account__c IN: accountIdSet AND Account__c != null))
                                                            AND status__c ='ACTIVE' AND Plan_Name__c != NULL aND Catg__c != NULL];
        for(Dependent__c depM : existingDependent){
            if(depM.Age_Today__c < 19){
                if(cto19belowdep.containsKey(depM.Cover__c)){
                    cto19belowdep.get(depM.Cover__c).add(depM);
                }
                else {
                    cto19belowdep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
                
                if(ato19belowdep.containsKey(depM.Account__c)){
                    ato19belowdep.get(depM.Account__c).add(depM);
                }
                else {
                    ato19belowdep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
            if(depM.Age_Today__c >= 19){
                if(cto20belowdep.containsKey(depM.Cover__c)){
                    cto20belowdep.get(depM.Cover__c).add(depM);
                }
                else {
                    cto20belowdep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
                
                if(ato20updep.containsKey(depM.Account__c)){
                    ato20updep.get(depM.Account__c).add(depM);
                }
                else {
                    ato20updep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
            if(depM.Catg__c == 'Vision'){
                if(ctomeddep.containsKey(depM.Cover__c)){
                    ctomeddep.get(depM.Cover__c).add(depM);
                }
                else {
                    ctomeddep.put(depM.Cover__c, new List<Dependent__c>{ depM });
                }
            }
            
            if(depM.Catg__c == 'Dental'){
                if(atoDep.containsKey(depM.Account__c)){
                    atoDep.get(depM.Account__c).add(depM);
                }
                else {
                    atoDep.put(depM.Account__c, new List<Dependent__c>{ depM });
                }
            }
        }
        Map<Id, Account> acctAttesAppMap = new Map<Id, Account>([Select ID,Good__c,Age_in_Numbers__pc,PersonContactId,Phone__c ,NumberofYears__c  FROM Account where ID IN : accountIdSet ]);
        
        for(Id acctId : accountIdSet){
            for(Dependent__c depM : existingDependent){
                for(Id covId : coverIdSet){
                    if(cto19belowdep.containsKey(covId) && depM.Cover__c==covId){ 
                        for(Dependent__c depU19 : cto19belowdep.get(covId)){
                            if(depU19.Age_Today__c < 19){ 
 
                                if((atoDep.containsKey(acctId)) || (acctAttesAppMap.get(acctId).Good__c == true) || (acctAttesAppMap.get(acctId ).NumberofYears__c > 0 )){ 
                                    if(ctomeddep.containsKey(covId)){
                                        for(Dependent__c depMemMedi : ctomeddep.get(covId)){ 
                                            accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=true, Comply__c=false));
                                        }
                                    }
                                    
                                }
                                else {
                                    if((!atoDep.containsKey(acctId)) || (acctAttesAppMap.get(acctId).Good__c == false) || (acctAttesAppMap.get(acctId ).NumberofYears__c == 0 )){ 
                                        if(ctomeddep.containsKey(covId)){
                                            for(Dependent__c depMemMedi : ctomeddep.get(covId)){
                                                accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=false, Comply__c=false));
                                            }
                                        }
                                        
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c != NULL ){
                                        {
                                           
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Doctor_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));

                                            
                                        }
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c == NULL && acctAttesAppMap.get(acctId).Age_in_Numbers__pc >= 19){
                                        {
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Nurse_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));
                                        }
                                    }
                                    IF(acctAttesAppMap.get(acctId).Phone__c == NULL &&  acctAttesAppMap.get(acctId).Age_in_Numbers__pc < 19){
                                        {
                                            cmList.add( new CampaignMember(
                                                CampaignId  = System.Label.Staff_Campaign,
                                                ContactId = acctAttesAppMap.get(acctId).PersonContactId,
                                                Status = 'Completed'
                                            ));
                                        }
                                    }
                                }
                            }
                            
                        }
                    else if(cto20belowdep.containsKey(covId) && depM.Cover__c==covId){
                        for(Dependent__c depU20 : cto20belowdep.get(covId)){
                            if(depU20.Age_Today__c >= 19){ 
                                if(atoDep.containsKey(acctId) ){
                                    if(ctomeddep.containsKey(covId)){
                                        for(Dependent__c depMemMedi : ctomeddep.get(covId)){
                                            accountToUpdateMap.put(depMemMedi.Account__c, new Account(Id=depMemMedi.Account__c, Compliant__c=false, Comply__c=true));
                                        }
                                    }
                                }
                            }
                            
                        }
                    }
                    if(depM.Cover__r.Comply__c==true && depM.Cover__c == covId){
                        if(ctomeddep.containsKey(covId)) 
                            for(Dependent__c CMmed : ctomeddep.get(covId)){
                                accountToUpdateMap.put(CMmed.Account__c, new Account(Id=CMmed.Account__c, Compliant__c=false, Comply__c=true));
                            }
                    } 
                    
                }
            }
        }
        database.insert(cmlist, false);
        update accountToUpdateMap.values();
        
    }
    
}

 
Hi

I am getting this issue to many soql, is there something wrong with my code when try to save a record this error appers that too many soql
public class AccountTask {
    
    
    
    public static void accountTaskCopy(List<Account> acclist){
        Id EmailRT = SObjectType.Task.getRecordTypeInfosByDeveloperName().get('Email').getRecordTypeId();
        Id CallRT = SObjectType.Task.getRecordTypeInfosByDeveloperName().get('Call').getRecordTypeId(); 
        
        Set<Id> forWhatID = new Set<Id>();
        Set<Id> accID = new Set<Id>();
        Set<Id> coverageIds = new Set<Id>();
        Map<ID, List<CM__c>> accountIdToListCMOMap = new Map<Id, List<CM__c>>(); 
        Map<ID, List<CM__c>> coverageIdToListCVMMap = new Map<Id, List<CM__c>>();
        Map<ID, List<Task>> accountIdToListTaskCompletedMap = new Map<Id, List<Task>>();
        Map<ID, List<Task>> accountIdToListTaskNotCompletedMap = new Map<Id, List<Task>>();
        Map<Id, Account> accountsToUpdate = new Map<Id, Account>();
       
        for(Account acc: acclist){
            {
            accID.add(acc.ID);
            }
       }

        
        for(Task tsk : [SELECT ID,whatid FROM TASK where WHATID IN : accID]){
            if(tsk.WhatID != Null && tsk.WhatID.getSObjectType() == Account.SobjectType){
                forWhatID.add(tsk.WhatId);
                System.debug('forWhatID' + forWhatID);
            }
        }
         
        List<CM__c> existingCMs = [SELECT Id, Account__c, Account__r.Name, CVR__c, Coverage__r.Good__c,rel__c, status__c, BusinessType__c, Age_Today__c 
                                                            FROM CM__c 
                                                            WHERE (CVR__c != null AND Account__c IN: forWhatID AND Account__c != null) AND status__c ='ACTIVE' AND BusinessType__c = 'Medical'];
        
        for(CM__c cMo : existingCMs){
            if(accountIdToListCMOMap.containsKey(cMo.Account__c)){
                accountIdToListCMOMap.get(cMo.Account__c).add(cMo);
            }
            else{
                accountIdToListCMOMap.put(cMo.Account__c, new List<CM__c>{cMo});
            }
            
            if(coverageIdToListCVMMap.containsKey(cMo.CVR__c)){
                coverageIdToListCVMMap.get(cMo.CVR__c).add(cMo);
            }
            else{
                coverageIdToListCVMMap.put(cMo.CVR__c, new List<CM__c>{cMo});
            }
            
            coverageIds.add(cMo.CVR__c);
        }
        
        List<CM__c> existingCMFromCov = [SELECT Id, Account__c, Account__r.Name, CVR__c, Coverage__r.Good__c,rel__c, status__c, BusinessType__c, Age_Today__c 
                                                                   FROM CM__c 
                                                                   WHERE (CVR__c != null AND CVR__c IN: coverageIds AND Account__c != null) AND status__c ='ACTIVE' AND BusinessType__c = 'Medical'];
        for(CM__c cMo : existingCMFromCov){
            if(coverageIdToListCVMMap.containsKey(cMo.CVR__c)){
                coverageIdToListCVMMap.get(cMo.CVR__c).add(cMo);
            }
            else{
                coverageIdToListCVMMap.put(cMo.CVR__c, new List<CM__c>{cMo});
            }
        }
        System.debug('accountIdToListCMOMap ' + accountIdToListCMOMap);
        System.debug('coverageIdToListCVMMap ' + coverageIdToListCVMMap);
        
        
        List<Task> taskCompletedOrInvalidPhone = [SELECT Id, whatid, CallCustom__c, RecordtypeId 
                                                  FROM Task 
                                                  WHERE Whatid IN :forWhatID 
                                                  AND (CallCustom__c = 'Completed Campaign Requirements' OR CallCustom__c = 'Invalid Phone') AND WhatID != null];
        for(Task tsk : taskCompletedOrInvalidPhone){
            if(accountIdToListTaskCompletedMap.containsKey(tsk.WhatId)){
                accountIdToListTaskCompletedMap.get(tsk.WhatId).add(tsk);
            }
            else{
                accountIdToListTaskCompletedMap.put(tsk.WhatId, new List<Task>{tsk});
            }
        }
        
        List<Task> taskNotCompleteCampaign = [SELECT Id, whatid,CallCustom__c, RecordtypeId  FROM Task WHERE Whatid IN :forWhatID AND RecordTypeID =: CallRT AND (CallCustom__c = 'Left Message' OR  CallCustom__c = 'Unable to Reach') AND WhatID != null ];
        for(Task tsk : taskNotCompleteCampaign){
            if(accountIdToListTaskNotCompletedMap.containsKey(tsk.WhatId)){
                accountIdToListTaskNotCompletedMap.get(tsk.WhatId).add(tsk);
            }
            else{
                accountIdToListTaskNotCompletedMap.put(tsk.WhatId, new List<Task>{tsk});
            }
        }
        
        System.debug('accountIdToListTaskCompletedMap ' + accountIdToListTaskCompletedMap);
        System.debug('accountIdToListTaskNotCompletedMap ' + accountIdToListTaskNotCompletedMap);
        
        for(Id acctId : forWhatID){
            System.debug('acctId ' + acctId);
            if(accountIdToListTaskCompletedMap.containsKey(acctId)){
            system.debug('acctIdlist' + accountIdToListTaskCompletedMap);
                if(accountIdToListCMOMap.containsKey(acctId)){
                    for(CM__c cMo : accountIdToListCMOMap.get(acctId)){
                        System.debug('cMo ' + cMo);
                        if(coverageIdToListCVMMap.containsKey(cMo.CVR__c)){
                            for(CM__c covMem2 : coverageIdToListCVMMap.get(cMo.CVR__c)){
                                System.debug('covMem2 ' + covMem2);
                                accountsToUpdate.put(covMem2.Account__c, new Account(Id=covMem2.Account__c, PDC__c=true));
                            }
                        }
                        
                    } 
                } 
            }
        
        }
        
        System.debug('accountsToUpdate ' + accountsToUpdate);
        update accountsToUpdate.values();
        
    }
}

 
I have this Custom Object Named Stored XML.

and one of the field stores an XML strings.

<?xml version="1.0" encoding="UTF-8"?><consumers xmlns="http://test.com/feed/">
<SupplyResult>
 <MarketId>xxxxxxxx</MarketId>
 <SupplyList>
    <member>
        <Quantity>9</Quantity>
        <InStock>5</InStock>
        <SellerSKU>Test- 1111</SellerSKU>
    </member>
  </SupplyList>
  </SupplyResult>


How do I parse this and store all the field on on a new Custom Object Named XML Parsed?

Thank you!

Hey Guys,

 

Im struggling abit with figuring out how to parse some xml into a custom object. Ive been working with the xmlstreamreader example, but I cant quite wrap my head around how step through the xml elements values that I want to insert into my custom object....

 

The xml response Im getting back from my webcallout looks like this:

 

<advertisers type="array">
  <advertiser>
    <id type="integer">7</id>
    <name>ABC Telecom</name>
  </advertiser>
  <advertiser>
    <id type="integer">106</id>
    <name>ABC_Ozone</name>
  </advertiser><advertiser>
    <id type="integer">13</id>
    <name>Acme Corp</name>
  </advertiser>
</advertisers>

 

My goal is loop through this and extract the value of id and name of each advertiser. I would then like to insert the id and name of each advertiser into a custom object. I would use the name field for the name of the advertiser and I have a custom field realationship setup to store the id value.

 

Any help is much appreciated.

  • August 05, 2011
  • Like
  • 0