Skip to content

Instantly share code, notes, and snippets.

@citrus
Last active June 12, 2022 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save citrus/19ce62aded1e6d9ff8ffa25db00bad71 to your computer and use it in GitHub Desktop.
Save citrus/19ce62aded1e6d9ff8ffa25db00bad71 to your computer and use it in GitHub Desktop.
Generate Quote PDF via Salesforce REST API
global class QuotePDFGenerator {
@future(callout=true)
public static void AttachPDFToQuote(String Id) {
try {
CreateQuoteDocumentFromPDF(Id);
} catch(exception ex) {
System.debug('Error: ' + ex);
}
}
public static String CreateQuoteDocumentFromPDF(String Id) {
String quoteURL = '/quote/quoteTemplateDataViewer.apexp?headerHeight=156&footerHeight=94&summlid=0EH800000000fkT&id=' + Id;
Blob renderedPDF;
if (Test.isRunningTest()) {
renderedPDF = Blob.valueOf('Unit.Test');
} else {
renderedPDF = new PageReference(quoteURL).getContentAsPDF();
}
QuoteDocument doc = new QuoteDocument(QuoteId = Id, Document = renderedPDF);
INSERT doc;
String Name = [select Name from QuoteDocument where QuoteId =: Id].Name;
RETURN Name;
}
}
@RestResource(urlMapping='/Quote/PDFGenerator/*')
global with sharing class QuotePDFGeneratorResource {
@HttpPost
global static String doPost(String Id) {
QuotePDFGenerator.AttachPDFToQuote(Id);
return 'SUCCESS';
}
}
@isTest
private class Test_QuotePDFGenerator {
static Account account;
static Opportunity opportunity;
static Quote quote;
static {
account = new Account(
Name = 'Test Account'
);
insert account;
opportunity = new Opportunity(
AccountId = account.Id,
Name = account.Name,
StageName = 'Prospecting',
CloseDate = System.today()
);
insert opportunity;
quote = new Quote(
Name = '12345',
OpportunityId = opportunity.Id
);
insert quote;
}
static testMethod void test_AttachPDFToQuote() {
Test.startTest();
QuotePDFGenerator.AttachPDFToQuote(quote.Id);
Test.stopTest();
Integer count = [select count() from QuoteDocument where QuoteId =: quote.Id];
System.assertEquals(1, count);
}
static testMethod void test_CreateQuoteDocumentFromPDF() {
Test.startTest();
Integer beforeCount = [select count() from QuoteDocument where QuoteId =: quote.Id];
System.debug('BeforeCount: ' + beforeCount);
System.assertEquals(0, beforeCount);
String Name = QuotePDFGenerator.CreateQuoteDocumentFromPDF(quote.Id);
String ExpectedName = [select Name from QuoteDocument where QuoteId =: quote.Id].Name;
System.assertEquals(ExpectedName, Name);
Test.stopTest();
}
}
@isTest
private class Test_QuotePDFGeneratorResource {
static testMethod void testQuotePdfGeneratorResource() {
Test.startTest();
String result = QuotePDFGeneratorResource.doPost('abc123');
System.assertEquals('SUCCESS', result);
Test.stopTest();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment