+ Start a Discussion
Trif Cristian 7Trif Cristian 7 

error in my batch class

Hi, I wrote a batch class to send email notification to users from Queue. 
This is my class:

 

global class sendEmailBatchClass implements Database.Batchable < sobject > {
   
    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date dt = date.today().addDays(1);
        System.debug('scope ' + dt);
        return Database.getquerylocator([SELECT Id,OwnerId,Name,Owner.Email,
        (Select Id,OwnerId,Name,Owner.Email from SVMXC__Work_Orders__r where SIG_Due_Date__c =:dt and SVMXC__Order_Status__c NOT IN ('Closed','Completed')),
        (Select Id,OwnerId,Name,Owner.Email from Administrative_Tasks__r where SIG_Due_Date__c =:dt and SIG_Status__c Not IN ('Closed','Completed')) 
        From SVMXC__Service_Request__c  WHERE SVMXC__Status__c = 'Open' and SVMX_SIG_Due_Date__c  =: dt]);
    }
    
    global void execute(Database.BatchableContext bc, List <SVMXC__Service_Request__c> scope) {
       System.debug('scope ' + scope); 
        String userStringVal = '005';
        List<SVMXC__Service_Order__c> emailUsers = new List<SVMXC__Service_Order__c>();
        Map<Id,set<SVMXC__Service_Request__c>> srMap = new Map<Id, set<SVMXC__Service_Request__c>>();
        System.debug('#####srMap ' + srMap);
        Map<Id, Set<SVMXC__Service_Order__c>> woMap = new Map<Id, Set<SVMXC__Service_order__c>>();
        System.debug('#####woMap ' + woMap);
        Map<Id, Set<SIG_Administrative_Task__c>> atMap = new Map<Id, Set<SIG_Administrative_Task__c>>();
        System.debug('#####atMap ' + atMap);
        Map<String, set<SVMXC__Service_Request__c>> userSRMap = new Map< String, set<SVMXC__Service_Request__c>>();
        System.debug('#####userSRMap ' + userSRMap);
        Map<String, set<SVMXC__Service_Order__c>> userWoMap = new Map< String, set<SVMXC__Service_Order__c>>();
        System.debug('#####userWoMap ' + userWoMap);
        Map<String, set<SIG_Administrative_Task__c>> userATMap = new Map< String, set<SIG_Administrative_Task__c>>();
        System.debug('#####userATMap ' + userATMap);
        OrgWideEmailAddress[] owea = [select Id,DisplayName,Address from OrgWideEmailAddress where DisplayName = 'SIG OrgWideAddress'];

        For(SVMXC__Service_Request__c srVal:scope){
            If(string.valueOf(srVal.OwnerId).startsWith(userStringVal)){
                if(!userSRMap.containsKey(srVal.Owner.Email)){
                userSRMap.put(srVal.Owner.Email,new set<SVMXC__Service_Request__c>{srVal} );
                }else
                {
                   userSRMap.get(srVal.Owner.Email).add(srVal);
                   system.debug('**userSRMap'+userSRMap);
                }                   system.debug('**userSRMap'+userSRMap);

            }
            else{
                if(!srMap.containsKey(srVal.OwnerId)){
                    srMap.put(srVal.OwnerId,new set<SVMXC__Service_Request__c>{srVal} );
                }else
                {
                   srMap.get(srVal.OwnerId).add(srVal);
                   system.debug('***srMap'+srMap);
                }                   system.debug('**userSRMap'+userSRMap);

            }
            
            For(SVMXC__Service_Order__c woVal :srVal.SVMXC__Work_Orders__r){
                If(string.valueOf(srVal.OwnerId).startsWith(userStringVal)){
                if(!userWoMap.containsKey(woVal.Owner.Email)){
                userWoMap.put(woVal.Owner.Email,new set<SVMXC__Service_Order__c>{woVal} );
                }else
                {
                   userWoMap.get(woVal.Owner.Email).add(woVal);
                }
            }
            else{
                if(!woMap.containsKey(woVal.OwnerId)){
                    woMap.put(woVal.OwnerId,new set<SVMXC__Service_Order__c>{woVal} );
                }else
                {
                   woMap.get(woVal.OwnerId).add(woVal);
                }
            }
            }
            
            For(SIG_Administrative_Task__c atVal :srVal.Administrative_Tasks__r){
                If(string.valueOf(atVal.OwnerId).startsWith(userStringVal)){
                if(!userATMap.containsKey(atVal.Owner.Email)){
                userATMap.put(atVal.Owner.Email,new set<SIG_Administrative_Task__c>{atVal} );
                }else
                {
                   userATMap.get(atVal.Owner.Email).add(atVal);
                }
            }
            else{
                if(!atMap.containsKey(atVal.OwnerId)){
                    atMap.put(atVal.OwnerId,new set<SIG_Administrative_Task__c>{atVal} );
                }else
                {
                   atMap.get(atVal.OwnerId).add(atVal);
                }
            }
            }
         }
         /***  Group Member Extracting ***/
         
         Set<Id> groupIds = new Set<Id>();
         groupIds.addAll(srMap.keyset());
         groupIds.addAll(woMap.keyset());
         groupIds.addAll(atMap.keyset());
         Map<Id,Set<user>> GpMap = new Map<Id,Set<User>>();
         
         Map<Id,User> userVal = new Map<Id,User>([SELECT User.Id, User.Email FROM User WHERE Id IN 
                                                (SELECT UserOrGroupId FROM GroupMember WHERE GroupId in : groupIds)]);
         
         
         For(GroupMember gm :[Select groupId, UserOrGroupId From GroupMember where groupId IN : groupIds]){
             if(GpMap.containsKey(gm.groupId)){
                 GpMap.get(gm.groupId).add(userVal.get(gm.UserOrGroupId));
             }else{
                 GpMap.put(gm.groupId,new set<User>{userVal.get(gm.UserOrGroupId)});
             }
         }
         // Extracting group member from Service Request
         
         If(!GpMap.isEmpty() && !srMap.isEmpty()){
         For(Id gVal : GpMap.keyset()){
              For(User usVal : GpMap.get(gVal)){
                if(!userSRMap.containsKey(usVal.Email)){
                userSRMap.put(usVal.Email,new set<SVMXC__Service_Request__c>(srMap.get(gVal)));
                }
                else
                {
                   userSRMap.get(usVal.Email).addAll(srMap.get(gVal));
                }
              }
         }
         }
        
         
          // Extracting group member from Work Order
          
         If(!GpMap.isEmpty() && !woMap.isEmpty()){
         For(Id gVal : GpMap.keyset()){
              For(User usVal : GpMap.get(gVal)){
                 if(!userWoMap.containsKey(usVal.Email)){
                 userWoMap.put(usVal.Email,new set<SVMXC__Service_Order__c>(woMap.get(gVal)));
                }
                else
                {
                   userWoMap.get(usVal.Email).addAll(woMap.get(gVal));
                }
              }
         }
         }
          // Extracting group member from Service Request
          
          If(!GpMap.isEmpty() && !atMap.isEmpty()){
         For(Id gVal : GpMap.keyset()){
              For(User usVal : GpMap.get(gVal)){
                  
                if(!userSRMap.containsKey(usVal.Email)){
                userATMap.put(usVal.Email,new set<SIG_Administrative_Task__c>(atMap.get(gVal)));
                }
                else
                {
                   userATMap.get(usVal.Email).addAll(atMap.get(gVal));
                }
              }
         }
         }
         
         // Sending Email for Service Request
          For(String userval1: userSRMap.keyset()){
           For(SVMXC__Service_Request__c srlistval: userSRMap.get(userval1)){
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

                Id templateId =  [select id, name from EmailTemplate where developername = 'SIG_Service_Request_Escalation_Email'].id;
                // Create Contact
                    Contact con;
                    con = new Contact();
                    con.FirstName = 'Test';
                    con.LastName = 'Contact';
                    con.Email = 'no-reply@organization.com';
                    insert con;
                    email.setTargetObjectId(con.Id);
               // email.setTargetObjectId(srlistval.ownerId);
               String[] toAddresses ;
                    
              // I have hardcoded my Id for testing , please update the logic to add the respective email addresses.
                toAddresses   = new String[] {'vivek.agrawal@servicemax.com'};
                
                email.setOrgWideEmailAddressId(owea[0].Id);
                email.setCcAddresses(toAddresses);

                email.setWhatId(srlistval.Id);
                email.setTemplateId(templateId);
                email.setSaveAsActivity(false);
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
                                   system.debug('***email Message'+email);

            }
          }
          
          // Sending Email For Work Order
    
          For(String userval1: userWoMap.keyset()){
           For(SVMXC__Service_Order__c woListVal: userWoMap.get(userval1)){
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                Id templateId =  [select id, name from EmailTemplate where developername = 'SIG_Work_Order_Escalation_Email'].id;
                //email.setTargetObjectId(woListVal.ownerId);
                // Create Contact
                    Contact con;
                    con = new Contact();
                    con.FirstName = 'Test';
                    con.LastName = 'Contact';
                    con.Email = 'no-reply@organization.com';
                    insert con;
                    email.setTargetObjectId(con.Id);
                String[] toAddresses ;
  
              // I have hardcoded my Id for testing , please update the logic to add the respective email addresses.
              //  toAddresses   = new String[] {'vivek.agrawal@servicemax.com'};
                 toAddresses = new String [] {};
                for (String emaill : emailUsers.SIG_Queue_Members_Email_Address__c.split(',')) {
                                    String trimmed = email.trim();
                                    if (trimmed.length() > 0) {
                                     
                                     toAddresses.add(trimmed);
                                    }
                                  
                             }
                       
                             
                email.setOrgWideEmailAddressId(owea[0].Id);
                email.setCcAddresses(toAddresses);

                email.setWhatId(woListVal.Id);
                email.setTemplateId(templateId);
                email.setSaveAsActivity(false);
               Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            }
          }
          
          // Sending Email For Admin  Task
           For(String userval1: userATMap.keyset()){
           For(SIG_Administrative_Task__c adListVal: userATMap.get(userval1)){
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                Id templateId =  [select id, name from EmailTemplate where developername = 'SIG_Service_Request_Escalation_Email'].id;
                // Create Contact
                    Contact con;
                    con = new Contact();
                    con.FirstName = 'Test';
                    con.LastName = 'Contact';
                    con.Email = 'no-reply@organization.com';
                    insert con;
                    email.setTargetObjectId(con.Id);
               // email.setTargetObjectId(adListVal.ownerId);
               
               String[] toAddresses ;

              // I have hardcoded my Id for testing , please update the logic to add the respective email addresses.
                toAddresses   = new String[] {'vivek.agrawal@servicemax.com'};
                
                email.setOrgWideEmailAddressId(owea[0].Id);
                email.setCcAddresses(toAddresses);

                email.setWhatId(adListVal.Id);
                email.setTemplateId(templateId);
                email.setSaveAsActivity(false);
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            }
          }
          
          
          
    }
    
    global void finish(database.BatchableContext bc) {
        
    }
}


I'm trying to loop through each user from the Queue but i'm not sure how to do it...Also I have this error, I think from here I can solve my problem
User-added image

harsha__charsha__c
I think emailUsers is a list variable. Iterate through emailUsers first and then in an inner loop, access the field and split it.
 
for(User u : emailUsers) {   // I assumed emailUsers as list<User>. Replace it with the type of list
     if(!String.isBlank(u.SIG_Queue_Members_Email_Address__c)) {
             for(String email : u.SIG_Queue_Members_Email_Address__c.split(',') {
                   // have your logic here
             }
      }
}

Hope this helps.

-Harsha
harsha__charsha__c
Iterate through emailUsers first and then in an inner loop, access the field and split it.
 
for(SVMXC__Service_Order__c serviceOrder : emailUsers) {  
     if(!String.isBlank(serviceOrder.SIG_Queue_Members_Email_Address__c)) { 
          for(String email : serviceOrder.SIG_Queue_Members_Email_Address__c.split(',') { 
              // have your logic here 
          } 
     } 
}

Hope this helps.

NOTE - The loop is already inside 2 for loops which is a bad practice. Please try to use maps and aviod multiple levels of nested loops. This affect the performance.

-Harsha