global class leadCloseAfter6Months implements Database.Batchable<sObject>,Database.Stateful{ global Database.QueryLocator start(Database.BatchableContext BC) { string noOfDays =System.Label.LeadCloseMonthsValue; String query = 'select id,name,Email,MobilePhone,status from Lead where CreatedDate < LAST_N_DAYS:'+noOfDays+' and Follow_Up_By_Date__c != THIS_MONTH and Status=\'Open\' and Email != null'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<Lead> scope) { for(Lead le : scope) { le.Status= 'Disqualified'; le.Update_Status__c='Disqualify'; le.Status_Reason__c='Cold Lead'; } update scope; EmailTemplate emailTemplate = [select Id, Body from EmailTemplate where DeveloperName = 'lead_NotifyCustomerAfterLeadClose']; OrgWideEmailAddress[] owea = [SELECT Id,Address FROM OrgWideEmailAddress WHERE DisplayName ='System User']; //AsyncApexJob asyn = [Select Status, CreatedBy.Email, TotalJobItems, NumberOfErrors From AsyncApexJob Where id=:BC.getJobId()]; list<SMS_Message__c> smslist = new list<SMS_Message__c>(); list<task> SMSTaskList = new list<task>(); list<task> tasklist = new list<task>(); Messaging.SingleEmailMessage[] emailList = new list<Messaging.SingleEmailMessage>(); for(Lead le: scope){ Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); if(le.email != '' && le.Status == 'Disqualified') { if (owea.size() > 0) { email.setOrgWideEmailAddressId(owea.get(0).Id); } email.setToAddresses(new String[] {le.Email}); email.setSaveAsActivity(false); email.setTargetObjectId(le.Id); email.setTemplateId(emailTemplate.Id); emailList.add(email); // Messaging.SendEmailResult[] ser = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); } if(le.MobilePhone != '' && le.Status == 'Disqualified'){ SMS_Message__c sms = new SMS_Message__c(); sms.Lead__c = le.Id; sms.Message__c='Thank you for contacting JANA SA. In the interest of a test drive or quotation, please reply YES, and we will contact you. Regards JANA.'; // sms.Msisdn__c =le.MobilePhone; smslist.add(sms); //Create activity history for SMS Task newtask = new Task(); newtask.Subject = 'SMS: Test temp '; newtask.WhoId = le.Id; // newtask.Description = 'To:'+le.MobilePhone+'\n\n'; newtask.Description += 'Message:please reply YES, and we will contact you. Regards Jana.\n\n'; newtask.Priority = 'Normal'; newtask.Status = 'Completed'; Date myDate = Date.TODAY(); newtask.ActivityDate = myDate; SMSTaskList.add(newtask); } } //send an email Messaging.SendEmailResult[] results = Messaging.sendEmail(emailList); //Send an SMS try{ if(smslist.size()>0) { insert smslist; } }catch(Exception e){ system.debug('SMS records Inseration Error:'+e); } //insert SMSTaskList try{ if(SMSTaskList.size()>0) { insert SMSTaskList; } }catch(Exception e){ system.debug('SMS Task List records Inseration Error:'+e); } system.debug('eeeeee'+results); for(integer i=0;i<scope.size();i++){ if(results[i].isSuccess()) { //Create Activity History Task newtask = new Task(); newtask.Subject = 'Email: Jana test'; newtask.WhoId = scope[i].Id; newtask.Description = 'To:'+scope[i].Email+'\n\n'; newtask.Description += 'Good day '+scope[i].name+'\n\n'; newtask.Description += 'Kind Regards,\n'; newtask.Priority = 'Normal'; newtask.Status = 'Completed'; Date myDate = Date.TODAY(); newtask.ActivityDate = myDate; tasklist.add(newtask); } } try{ if(tasklist.size()>0) { insert tasklist; } }catch(Exception e){ system.debug('Task Record Inseration Error:'+e); } } global void finish(Database.BatchableContext BC) { OrgWideEmailAddress[] owea = [SELECT Id,Address FROM OrgWideEmailAddress WHERE DisplayName ='System User']; AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email, ExtendedStatus from AsyncApexJob where id=:BC.getJobId()]; if(a.Status == 'Failed') { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {a.CreatedBy.Email}; mail.setToAddresses(toAddresses); if (owea.size() > 0) { mail.setOrgWideEmailAddressId(owea.get(0).Id); } mail.setSubject('Automatically closing Leads after 6 months - Status: '+ a.Status); mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures. ExtendedStatus: ' + a.ExtendedStatus+'. Please check with System Administrator'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } } } ------------------------- To Run/Scheduler Class --------------------------------- global class Scheduler_class implements Schedulable{ global void execute(SchedulableContext sc) { leadCloseAfter6Months b1 = new leadCloseAfter6Months(); Database.executeBatch(b1); } } ----------Run below lines in Salesforce developer console to schedule job-------- Scheduler_class sx = new Scheduler_class(); String sch = '0 0 23 * * ?'; system.schedule('Test', sch, sx);
------------------------ Test class sample ------------------------------------ @isTest public class leadCloseAfter6MonthsTest { static testmethod void test1() { Id pSystemAdminId = [Select Id, Name from Profile where Name = 'System Administrator' Or Name ='Administrateur Système'].Id; User u = new User(Alias = 'standt', Email='standarduserUS@testorg1.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US', ProfileId = pSystemAdminId ,TimeZoneSidKey='America/Los_Angeles', UserName='standardUSuser@testorg.com'); insert u; system.runAs(u){ lead[] leadList = new List<Lead>(); Lead m = new lead(LastName = 'Lead1',Email='test@test1.com' ,status='Open',Mobile_Phone__c='999999999' ,Comments__c='good'); leadList.add(m); insert leadList; Datetime DT=Datetime.now().addDays(-183); Test.setCreatedDate(leadList[0].id, DT); Test.startTest(); leadCloseAfter6Months c = new leadCloseAfter6Months(); Database.executeBatch(c); Test.stopTest(); } } static testmethod void test2() { Scheduler_class sx = new Scheduler_class(); String sch = '0 0 23 * * ?'; system.schedule('Test', sch, sx); } }
Comments
Post a Comment