I Had a same kind of requirement the above code helped me and its working perfectly (Thanks @Phil Hawthorn):
Requirement:- is Generate the PDF and and send email notification and insert new related record to keep track of the pdf and attachment to the record.
Below is my complete process, modified few things:
set up remote site Setup->Security Controle->Remote Site setting. click on New Remote Site
Schedule class:-
global class ScheduleFinacialNotification implements Schedulable {
global string sendSessionId;
global ScheduleFinacialNotification(String sessionId){
this.sendSessionId = sessionId;
}
global void execute(SchedulableContext SC) {
BatchSendFinacialNotification batchApex=new BatchSendFinacialNotification();
batchApex.sessionId = this.sendSessionId;
Database.executeBatch(batchApex,1); }}
Batch class:-
global class BatchSendFinacialNotification implements Database.Batchable<sObject>,Database.Stateful,Database.AllowsCallouts {
public String query;
global string sessionId;
global BatchSendFinacialNotification(){
this.sessionId = sessionId;
query = 'Select Id,Name,Project__r.Go_Live_Date__c from Service_Project_Junction__c ';
}
global Database.QueryLocator start(Database.BatchableContext BC){
System.debug('=========='+Database.getQueryLocator(query));
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Service_Project_Junction__c> scope) {
//List<Service_Project_Junction__c> pojJunRecList = [Select Id,Name,Project__c,Opportunity_Deal__c,Project__r.Id,Project__r.Go_Live_Date__c,Product_Opportunity_Junction__r.Service__r.Service_Type__c,Product_Opportunity_Junction__r.Service__r.Product_Price__c,Product_Opportunity_Junction__r.No_Of_Months__c,Product_Opportunity_Junction__r.Total_Price__c,Product_Opportunity_Junction__r.No_Of_Listings__c from Service_Project_Junction__c where Opportunity_Deal__c != null AND Project__r.Go_Live_Date__c != null];
for(Service_Project_Junction__c proRec: scope){
Integer duration = integer.valueOf(proRec.Product_Opportunity_Junction__r.No_Of_Months__c);
Integer totMonthTillToday = proRec.Project__r.Go_Live_Date__c.monthsBetween(System.today());
System.debug('Test in for loop==>'+proRec);
if(totMonthTillToday <= duration && proRec.Project__r.Go_Live_Date__c.Day() == Date.today().day()){
System.debug(sessionId+'Test in if loop==>'+this.sessionId);
ServiceInvoiceRedirectController.attachPdfToRecord( proRec.Project__r.Id, this.sessionId);
System.debug('Test in if loop after condiyion==>');
}
}
}
global void finish(Database.BatchableContext BC){
}
}
Call of REST Api class:-
@RestResource(urlMapping='/AttachPDF/*')
global class ServiceInvoiceRedirectController
{
@HttpGet
global static void AttachPDFtoRecordREST()
{
RestRequest req = RestContext.request;
id recordId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
PageReference pdfPage = new PageReference('/apex/ServiceInvoicePDF?Id='+recordId);
pdfPage.getParameters().put('id',recordId);
Blob pdf = pdfPage.getContentAsPdf(); //!Test.isRunningTest() ? pdfPage.getContentAsPdf() : Blob.ValueOf('dummy text');
Project__c prjRec = [Select Id,Name,Builder_Name__c from Project__c where Id =: recordId];
//Insert Invoice record for related project
Invoice__c invoRec = new Invoice__c();
invoRec.RecordTypeId = Constants_PicklistVariables.serInvoice;
invoRec.Project__c = recordId;
invoRec.Account__c = prjRec.Builder_Name__c;
try{
insert invoRec;
}catch(Exception e){
System.debug('Invoice=Exception-->'+e);
}
System.debug('Invoice=invoRec.id-->'+invoRec);
//Insert Attacment to the invoice
Attachment a = New Attachment();
a.body = pdf;
a.parentID = invoRec.id;
a.ContentType = 'application/pdf';
a.Name = 'SER-INV-'+invoRec.id+'.pdf';
try{
insert a;
}catch(Exception e){
System.debug('Attachment=Exception-->'+e);
}
//Create the email attachment
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName('pdfName.pdf');//Pleace ad pdf name from contact name project and oppty concatinate
efa.setContentType('application/pdf');
efa.setBody(pdf);
// Create the Singal Email Message
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setSubject('Financial Notification');
email.setToAddresses(new String[] { '[email protected]' });//add account email id
email.setPlainTextBody( 'Please Find Attachment your financial report Attached with this email.');
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
// Sends the email
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
// call this method from your Batch Apex
global static void attachPdfToRecord( Id recordId, String sessionId )
{
System.debug('recordId==>'+recordId);
System.debug('sessionId==>'+sessionId);
System.debug('Iam in REST API Call method');
// String addr = 'https://cs5.salesforce.com/services/apexrest/AttachPDF/' + recordId;
HttpRequest req = new HttpRequest();
req.setEndpoint('https://cs5.salesforce.com/services/apexrest/AttachPDF/a04O000000EHJN6IAP');
req.setMethod('GET');
req.setHeader('Authorization', 'OAuth ' + sessionId);
Http http = new Http();
HttpResponse response = http.send(req);
}
}
Schedule class from Developer Console in Anonymous Window:-
Datetime sysTime = System.now();
sysTime = sysTime.addSeconds(5);
String chron_exp =' '+sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();
System.schedule('Job1',chron_exp , new ScheduleFinacialNotification(UserInfo.getSessionId()));