• Nishant Shah 9
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 3
    Replies
How to clone task related to the cases. The business is on the anniversary of an account, clone the case which is working. What is the thing needed to clone the task . Below is my code but not working.
 
public class Account_CloneCasesOnAnniversary implements   Database.Batchable<SObject>
{
    String errors = '';
    integer todayday = date.today().day();
    Integer currentmonth = date.today().month();

 public Database.QueryLocator start(Database.BatchableContext bc)
{
   return Database.getQueryLocator('SELECT Anniversary__c,(Select Id from cases order by CreatedDate),Id from Account WHERE DAY_IN_MONTH(Anniversary__c) =:todayday AND CALENDAR_MONTH(Anniversary__c ) =: currentmonth') ;
}

 public void execute(Database.BatchableContext bc, List<Account> scope)
 {
    if(scope.isEmpty()) return;
    List<Case> caseToCreateList = new List<Case>();
    List<Task> taskToCreateList = new List<Task>();

    system.debug('Scope is'+scope);

     for(account objS : scope){

         for(task objT : scope) {

             system.debug('Account with case'+objS);

        if(objS.cases.size() > 0 && objT.Task.size() >0 )
        {

            system.debug('aAccount.cases.size()'+objS.cases.size());
            list<Case> lstCase = new list<Case>();
            for(Case objcase : objS.cases){
                Case cloneCase = new Case();
                cloneCase  = objcase.clone();

                // collecting the Cases to create
                caseToCreateList.add(cloneCase);
            }

            for(Task objTask : objT.Task) {

                Task cloneTask = new cloneTask();
                cloneTask=objTask.clone();

                taskToCreateList.add(cloneTask);

            }

        }
         system.debug('caseToCreateList'+caseToCreateList);
     }
   }

       if(!caseToCreateList.isEmpty()) 
       { 

         Database.SaveResult[] srList = Database.insert(caseToCreateList, false);
         Integer index = 0;
         system.debug('---srList  first'+ srList );

         for(Database.SaveResult result : srList )
         {
            if(!result.isSuccess())
            {
                String errMsg = result.getErrors()[0].getMessage();

            } // End Inner If
            index++;
          } // End for
         } // End Outer If
       } // End try


public void finish(Database.BatchableContext context)
{

    }
   }
  }

 
Hello Experts,

Below is the batch class that I've written, however, the functionality is all the cases should be cloned on anniversary (date field) of an account but this is not working. Experts, please help me to write test class for the below batch as i'm beginner and need it urgent
 
public class CaseCloneOnAccountAnniversary implements Database.Batchable<SObject>,Schedulable
{
    public static final String BATCH_JOB_TITLE = 'My Batch Job';
    String errors = '';
    
    integer todayday = date.today().day();
    Integer currentmonth = date.today().month();

    public Map<Id, String> errorMap = new Map<Id, String>();
    public Map<Id,Case> IdToSObjectMap = new Map<Id, Case>();
    
    public Database.QueryLocator start(Database.BatchableContext bc)
    {
       return Database.getQueryLocator('SELECT Anniversary__c,Id from Account WHERE Anniversary__c = DAY_IN_MONTH(Anniversary__c) =:todayday AND CALENDAR_MONTH(Anniversary__c ) =: currentmonth') ;
    }
        
    
    public void execute(Database.BatchableContext bc, List<SObject> scope)
    {
        if(scope.isEmpty()) return;
        //List<Account> accts = (List<Account>) scope;
        // Lis<Account> acctsList = new List<Account>();
        List<Case> caseToCreateList = new List<Case>();
        
        
       // for( Account aAccount : (Account)scope )
       for(Account aAccount:[Select Id,(Select Id from cases order by CreatedDate limit 1) from account where Id IN : scope]) //Add all field in case query which you want to copy
        {
            if(aAccount.cases.size() > 0)
            {
                Case objCase = new Case();
                objCase  = aAccount.cases[0].clone(false, true);

                // collecting the Cases to create
                caseToCreateList.add(ObjCase);
            }
            
       }
        try
        {
           if(!caseToCreateList.isEmpty()) 
           { 
                        
             Database.SaveResult[] srList = Database.insert(caseToCreateList, false);
             Integer index = 0;
             system.debug('---srList  first'+ srList );
             
             for(Database.SaveResult result : srList )
             {
                if(!result.isSuccess())
                {
                    String errMsg = result.getErrors()[0].getMessage();
                    errorMap.put(caseToCreateList[index].Id, errMsg);
                    IdToSObjectMap.put(caseToCreateList[index].Id, caseToCreateList[index]);
                } // End Inner If
                index++;
              } // End for
            
            } // End Outer If
        } // End try
        catch( Exception ex )
        {
                this.errors += ex.getMessage();
        }
     }

    public void finish(Database.BatchableContext context)
    {
       //Send an email to the User after your batch completes 
       if(!errorMap.isEmpty()){
       AsyncApexJob a = [SELECT id,ApexClassId,JobItemsProcessed,TotalJobItems,NumberOfErrors, CreatedBy.Email FROM AsyncApexJob WHERE id = :context.getJobId()];
       
       String body = 'Your batch job '
             + 'CaseCloneOnAccountAnniversary'
             + 'has finished. \n' 
             + 'There were '
             + errorMap.size()
             + ' errors. Please find the error list attached to the mail.';
             
       // Creating the CSV file
        String finalstr = 'Id, Subject, Error \n';
        String subject = 'CaseCloneOnAccountAnniversary- Apex Batch Error List';
        String attName = 'CaseCloneOnAccountAnniversary Errors.csv';      
        
        for(Id id  : errorMap.keySet()){
                string err = errorMap.get(id);
                Case objCase = (Case) IdToSObjectMap.get(Id);
                String recordString = '"'+id+'","'+ objCase.Subject +'","'+ err +'"\n';
                finalstr = finalstr +recordString;
            } 
            
            // Define the email
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
 
            // Create the email attachment    
            Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
            efa.setFileName(attName);
            efa.setBody(Blob.valueOf(finalstr));
 
            // Sets the paramaters of the email
            email.setSubject( subject );
            email.setToAddresses( new String[] {'abc@gmail.com'} );
            email.setPlainTextBody( body );
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
 
            // Sends the email
            Messaging.SendEmailResult [] r = 
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
       
      }       
    }

    public void execute(SchedulableContext sc)
    {
        CaseCloneOnAccountAnniversary scheduleBatch= new CaseCloneOnAccountAnniversary();
        Database.executeBatch(scheduleBatch);
    }

        
   }

 

I'm new to Batch apex and trying to figure out how to create a scheduled job. In subsequent years, on the anniversary date of the related account, need to clone the existing cases for the new year, and trigger the related task workflows for these cases.

Please help me to achieve this using batch apex. Thanks in advance
This would be first my batch apex and need urgent help with batch apex code

The requirement is, if 
(Account: NC EQUALS True) // This is checkbox field
 AND 
(Account: StatusEQUALSActive) // Status field on Account
 AND
 (Case: Case Record Type EQUALS NC Action Plan) // NC Action Plan is a record  type on case
 
Then,
Create a Task which would be on Case Object (Owner is CaseOwner) . Till here , everything worked fine with Workflow.
But, this workflow rule should every year on Anniversary (Anniversary is field on Account)

Please help me to achieve this using Batch Apex and schedular.
 
Hello Experts,

Below is the batch class that I've written, however, the functionality is all the cases should be cloned on anniversary (date field) of an account but this is not working. Experts, please help me to write test class for the below batch as i'm beginner and need it urgent
 
public class CaseCloneOnAccountAnniversary implements Database.Batchable<SObject>,Schedulable
{
    public static final String BATCH_JOB_TITLE = 'My Batch Job';
    String errors = '';
    
    integer todayday = date.today().day();
    Integer currentmonth = date.today().month();

    public Map<Id, String> errorMap = new Map<Id, String>();
    public Map<Id,Case> IdToSObjectMap = new Map<Id, Case>();
    
    public Database.QueryLocator start(Database.BatchableContext bc)
    {
       return Database.getQueryLocator('SELECT Anniversary__c,Id from Account WHERE Anniversary__c = DAY_IN_MONTH(Anniversary__c) =:todayday AND CALENDAR_MONTH(Anniversary__c ) =: currentmonth') ;
    }
        
    
    public void execute(Database.BatchableContext bc, List<SObject> scope)
    {
        if(scope.isEmpty()) return;
        //List<Account> accts = (List<Account>) scope;
        // Lis<Account> acctsList = new List<Account>();
        List<Case> caseToCreateList = new List<Case>();
        
        
       // for( Account aAccount : (Account)scope )
       for(Account aAccount:[Select Id,(Select Id from cases order by CreatedDate limit 1) from account where Id IN : scope]) //Add all field in case query which you want to copy
        {
            if(aAccount.cases.size() > 0)
            {
                Case objCase = new Case();
                objCase  = aAccount.cases[0].clone(false, true);

                // collecting the Cases to create
                caseToCreateList.add(ObjCase);
            }
            
       }
        try
        {
           if(!caseToCreateList.isEmpty()) 
           { 
                        
             Database.SaveResult[] srList = Database.insert(caseToCreateList, false);
             Integer index = 0;
             system.debug('---srList  first'+ srList );
             
             for(Database.SaveResult result : srList )
             {
                if(!result.isSuccess())
                {
                    String errMsg = result.getErrors()[0].getMessage();
                    errorMap.put(caseToCreateList[index].Id, errMsg);
                    IdToSObjectMap.put(caseToCreateList[index].Id, caseToCreateList[index]);
                } // End Inner If
                index++;
              } // End for
            
            } // End Outer If
        } // End try
        catch( Exception ex )
        {
                this.errors += ex.getMessage();
        }
     }

    public void finish(Database.BatchableContext context)
    {
       //Send an email to the User after your batch completes 
       if(!errorMap.isEmpty()){
       AsyncApexJob a = [SELECT id,ApexClassId,JobItemsProcessed,TotalJobItems,NumberOfErrors, CreatedBy.Email FROM AsyncApexJob WHERE id = :context.getJobId()];
       
       String body = 'Your batch job '
             + 'CaseCloneOnAccountAnniversary'
             + 'has finished. \n' 
             + 'There were '
             + errorMap.size()
             + ' errors. Please find the error list attached to the mail.';
             
       // Creating the CSV file
        String finalstr = 'Id, Subject, Error \n';
        String subject = 'CaseCloneOnAccountAnniversary- Apex Batch Error List';
        String attName = 'CaseCloneOnAccountAnniversary Errors.csv';      
        
        for(Id id  : errorMap.keySet()){
                string err = errorMap.get(id);
                Case objCase = (Case) IdToSObjectMap.get(Id);
                String recordString = '"'+id+'","'+ objCase.Subject +'","'+ err +'"\n';
                finalstr = finalstr +recordString;
            } 
            
            // Define the email
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
 
            // Create the email attachment    
            Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
            efa.setFileName(attName);
            efa.setBody(Blob.valueOf(finalstr));
 
            // Sets the paramaters of the email
            email.setSubject( subject );
            email.setToAddresses( new String[] {'abc@gmail.com'} );
            email.setPlainTextBody( body );
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
 
            // Sends the email
            Messaging.SendEmailResult [] r = 
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
       
      }       
    }

    public void execute(SchedulableContext sc)
    {
        CaseCloneOnAccountAnniversary scheduleBatch= new CaseCloneOnAccountAnniversary();
        Database.executeBatch(scheduleBatch);
    }

        
   }

 
This would be first my batch apex and need urgent help with batch apex code

The requirement is, if 
(Account: NC EQUALS True) // This is checkbox field
 AND 
(Account: StatusEQUALSActive) // Status field on Account
 AND
 (Case: Case Record Type EQUALS NC Action Plan) // NC Action Plan is a record  type on case
 
Then,
Create a Task which would be on Case Object (Owner is CaseOwner) . Till here , everything worked fine with Workflow.
But, this workflow rule should every year on Anniversary (Anniversary is field on Account)

Please help me to achieve this using Batch Apex and schedular.