Thursday, 26 June 2014

Create a report using apex class and send as an Email Attachment

/*
Create a customize report to send specific user via email, using apex class and scheduler in email attachment.

Suppose we have object Job__c and specific user need daily email how much Job everyday created my his team. (here I am defining very simple scenario but it is very useful for complex and complected report)

I am using here single object Job__c and 3 apex classes to meet this requirement.
also i try to cover following scenario

a batch Apex job that contains 20,000 records and is executed without the optional scope parameter is considered five transactions of 200 records each
*/

Main class jobHelper (where i develop all logic)

public class jobHelper{
public List<Job__c>filterJob(List<Job__c>jobList, DateTime startDateTime, DateTime endDateTime){
    List<Job__c> filteredJobList = new List<Job__c>();        
         if (jobList != null && jobList.size() > 0){
            /* filtering cases created between given start date and end date */
            for(Job__c jobObj : jobList){
                if (jobObj.createdDate >= startDateTime && jobObj.createdDate <= endDateTime){
                    filteredJobList.add(jobObj );
                }
            }
        }        
        return filteredJobList ;
}

public void execute(List<Job__c> jobList , boolean jobNotificationDate, DateTime repDate)
   {
        String fromEmailId = '';
        String fromDisplayName = '';
        DateTime reportDateTime;
          fromDisplayName = 'daily auto mail';
        fromEmailId = 'Noreply@gmail.com';
        String emailContents = '';
        String emailAttachment = '';        
        emailContents = getEmailContentsForDailyJobReport(jobList,repDate);
        emailAttachment = getEmailAttachmentForDailyJobReport(jobList );       
        
         if(emailAttachment != null && !emailAttachment.equals('')){
           //AKG 
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setHTMLBody(emailContents);
        
            //from details
            //System.debug('before setting to mail ==> fromDisplayName = ' + fromDisplayName + ', fromEmailId =' + fromEmailId);
            mail.setSenderDisplayName(fromDisplayName );
            mail.setReplyTo(fromEmailId );        
            //to 
            Set<String> toEmailIdSet = new Set<String>();
            mail.setToAddresses(new List<String>(toEmailIdSet)); 
             
            //cc 
            Set<String> ccEmailIdSet = new Set<String>();
            System.debug('--------ccmEmailIdSet -----------' + ccEmailIdSet );
            mail.setCCAddresses(new List<String>(ccEmailIdSet));   

            //bcc 
            Set<String> bccEmailIdSet = new Set<String>();
            System.debug('--------bccEmailIdSet -----------' + bccEmailIdSet );
            mail.setBCCAddresses(new List<String>(bccEmailIdSet)); 
        List<String> l = new List<String>();
            
            l.add('aalokkumar@demomail.com'); 
            mail.setToAddresses(l);
            //subject
            String subject = 'today job report';
           
            mail.setSubject(subject );
        
            if (emailAttachment != null && !emailAttachment.equals('')){
                Messaging.EmailFileAttachment excelAttchment = new Messaging.EmailFileAttachment();
                blob excelBlob = Blob.valueOf(emailAttachment);
                
                String filename = 'Job Report for ' + repDate.day() + '-' + repDate.month() + '-' + repDate.year() + '.xls' ;
                System.debug('----------filename ------------' + filename );                        
                excelAttchment.setFileName(filename );
                
                excelAttchment.setBody(excelBlob );
                mail.setFileAttachments(new Messaging.EmailFileAttachment[]{excelAttchment});
            }
                    
           /* List<String> l = new List<String>();
           
            l.add('aalokkumar.gupta@demomail.com'); 
            mail.setToAddresses(l); */
           
           System.debug('===== Sending Email');
           Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
           System.debug('===== Email Sent');
        }
    }
    
    public String getEmailContentsForDailyJobReport(List<Job__c> jobList, DateTime reportDate ){
        String returnValue = '';
        if (jobList!= null && jobList.size() > 0){
            returnValue  ='Dear All,<br><br> PFA the report for all jobs  '+reportDate.format('dd-MM-yyyy')+'. <br><br>Regards,<br>Admin<br><br>Note: This is a system generated report. Do not reply to this email. ';
        }
        return returnValue ;
        
    }
      public String getEmailAttachmentForDailyJobReport(List<Job__C> jobList ){
        String contents = '';

        String tabChar = '\t';
        String emptyChar = '-';
        
      //  System.debug('1.......................caseDetailMap ' + caseDetailMap);
        if (jobList != null && jobList.size() > 0){
            contents = 'Job Title\tDate and time stamp of job creation \n';
            //system.debug('~~~~~~~~~~~~~~~~~~~~~~~~~~~~caseList order check '+caseList);
            for(Job__c jobObj: jobList ){
                String JobTitle= '';
                String Jobapp = '';    
                
                /* project name */          
                contents += jobObj.Name;
                contents += tabChar ;
    
                // Date and time stamp of case creation
                if (jobObj.createdDate != null){
                    contents += jobObj.createdDate.format('dd-MM-yyyy, hh:mm a') ;
                }else{
                    contents += '' ;
                }
                   contents += tabChar ;    
               contents += '\n';
            }
         }
         return contents;
    }   
}

class Job_ReportGenerator (batchable apex class to schedule class)

//Database.Stateful :- maintain all data of each chunk and send back to finish method

global class Job_ReportGenerator implements Database.batchable<sObject>, Database.Stateful

    public String query= '';
    
    global List<Job__c> listAllJob = new List<Job__c>();

    /* start */
    global Database.QueryLocator start(Database.BatchableContext obj){
       try{
            // Initializing Created date to filterize the Cases from Yesterday 8 AM to Today 8 AM -Aalok - 12/6
              DateTime dtCreatedDateFrom = DateTime.newInstance((System.today()-1).year(), (System.today()-1).month(), (System.today()-1).day(), 08, 00, 00);
              DateTime dtCreatedDateTo = DateTime.newInstance(System.today().year(), System.today().month(), System.today().day(), 08, 00, 00);
                query = 'Select Name, CreatedDate from Job__c ORDER BY Name';
                System.debug('Query => ' + query );
        }catch(Exception ex){
            System.debug('Error in  -> Start => '+ ex);
        }
            
        return Database.getQueryLocator(query);
    }
    
    
     global void execute(Database.BatchableContext obj, List<Job__C> jobList){
        if (jobList!= null && jobList.size() > 0){
            System.debug('~~~~~~~~~~~~~~joblist = '+ jobList.size());
            
            /* Creating date instance for YESTERDAY 0:0:0 */    

           DateTIme startDateTime = DateTime.newInstance((Date.today()).addDays(-20), Time.newInstance(0,0,0,0));
           
            System.debug('startDateTime => ' + startDateTime );
            
            /* Creating date instance for YESTERDAY 23:59:59 */

            DateTIme endDateTime = DateTime.newInstance((Date.today()).addDays(-1), Time.newInstance(23,59,59,0));
           
           jobHelper helperObj = new jobHelper();    
            
            listAllJob .addAll(jobList);
           
        }
    }    
        global void finish(Database.BatchableContext obj){    
        //Logic to Send one single Consolidated Email irrespective of the number of batches executed
        System.debug('============ Finish Consolidated Case List ' + listAllJob .size());
        jobHelper  objJobHelper = new jobHelper ();
        objJobHelper.execute(listAllJob , false, Date.today().addDays(-1));
    }
    
}


--------------------------
Scheduled class  
global class JobReportScheduler implements Schedulable 
{
     global void execute(SchedulableContext SC) {     
        Job_ReportGenerator JobReport = new Job_ReportGenerator ();
        Database.executeBatch(JobReport , 200 );        
   }
}