PDF_Generation_and_Automation/force-app/main/default/classes/PdfApiController.cls
2025-08-25 21:52:12 +05:30

365 lines
18 KiB
OpenEdge ABL

public with sharing class PdfApiController {
@AuraEnabled
public static Map<String, Object> generatePreview(String template, String propertyName, String propertyType,
String location, String price, String bedrooms, String bathrooms,
String area, String description) {
try {
// Prepare data for Python API with all required fields
Map<String, Object> previewData = new Map<String, Object>{
'template' => template,
'propertyName' => propertyName,
'propertyType' => propertyType,
'location' => location,
'price' => price,
'bedrooms' => bedrooms,
'bathrooms' => bathrooms,
'area' => area,
'description' => description
};
String jsonBody = JSON.serialize(previewData);
// Call Python API for preview
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://salesforce.tech4biz.io/api/preview');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setBody(jsonBody);
request.setTimeout(120000); // 2 minutes timeout
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
if (result.containsKey('success') && (Boolean) result.get('success')) {
// Extract the preview data from the nested structure
Map<String, Object> preview = (Map<String, Object>) result.get('preview');
return new Map<String, Object>{
'success' => true,
'preview_html' => preview.get('preview_html'),
'template_info' => preview.get('template_info'),
'property_data' => preview.get('property_data'),
'message' => 'Preview generated successfully'
};
} else {
String errorMessage = result.get('message') != null ? (String) result.get('message') : 'Preview generation failed';
return new Map<String, Object>{
'success' => false,
'error' => errorMessage
};
}
} else {
return new Map<String, Object>{
'success' => false,
'error' => 'HTTP ' + response.getStatusCode() + ': ' + response.getBody()
};
}
} catch (Exception e) {
return new Map<String, Object>{
'success' => false,
'error' => 'Exception: ' + e.getMessage()
};
}
}
@AuraEnabled
public static Map<String, Object> generatePdf(String templateName, String propertyName, String propertyType,
String location, String price, String bedrooms, String bathrooms,
String area, String description) {
try {
Map<String, Object> propertyData = new Map<String, Object>{
'template' => templateName,
'propertyName' => propertyName,
'propertyType' => propertyType,
'location' => location,
'price' => price,
'bedrooms' => bedrooms,
'bathrooms' => bathrooms,
'area' => area,
'description' => description
};
Map<String, Object> requestData = new Map<String, Object>{
'template_name' => templateName,
'property_data' => propertyData
};
String jsonBody = JSON.serialize(requestData);
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://salesforce.tech4biz.io/api/generate-pdf');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setBody(jsonBody);
request.setTimeout(120000);
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
if (result.containsKey('success') && (Boolean) result.get('success')) {
// Try to fetch the actual PDF content
if (result.containsKey('pdf_url')) {
String pdfUrl = (String) result.get('pdf_url');
System.debug('PDF URL received: ' + pdfUrl);
System.debug('Full API response: ' + JSON.serialize(result));
// Make a GET request to fetch the actual PDF content
HttpRequest pdfRequest = new HttpRequest();
pdfRequest.setEndpoint('https://salesforce.tech4biz.io' + pdfUrl);
pdfRequest.setMethod('GET');
pdfRequest.setTimeout(120000);
HttpResponse pdfResponse = http.send(pdfRequest);
System.debug('PDF fetch response status: ' + pdfResponse.getStatusCode());
System.debug('PDF fetch response headers: ' + pdfResponse.getHeaderKeys());
System.debug('PDF fetch response body length: ' + pdfResponse.getBody().length());
if (pdfResponse.getStatusCode() == 200) {
// Successfully got PDF content
Blob pdfBlob = pdfResponse.getBodyAsBlob();
String base64Pdf = EncodingUtil.base64Encode(pdfBlob);
System.debug('PDF blob size: ' + pdfBlob.size());
System.debug('Base64 PDF length: ' + base64Pdf.length());
// Extract filename from URL or create one
String filename = 'property_report_' + propertyName + '_' + templateName + '.pdf';
if (pdfUrl.contains('/')) {
String[] urlParts = pdfUrl.split('/');
if (urlParts.size() > 0) {
String lastPart = urlParts[urlParts.size() - 1];
if (lastPart.endsWith('.pdf')) {
filename = lastPart;
}
}
}
System.debug('Final filename: ' + filename);
return new Map<String, Object>{
'success' => true,
'message' => 'PDF generated successfully',
'pdf_data' => base64Pdf,
'filename' => filename,
'content_type' => 'application/pdf'
};
} else {
System.debug('Failed to fetch PDF content: HTTP ' + pdfResponse.getStatusCode());
System.debug('PDF fetch error response: ' + pdfResponse.getBody());
// If PDF fetch fails, try to get preview content as fallback
return getPreviewContentAsFallback(templateName, propertyName, propertyType,
location, price, bedrooms, bathrooms, area, description);
}
} else {
System.debug('No pdf_url in response, falling back to preview');
System.debug('Available keys in result: ' + result.keySet());
return getPreviewContentAsFallback(templateName, propertyName, propertyType,
location, price, bedrooms, bathrooms, area, description);
}
} else {
String errorMessage = result.get('message') != null ? (String) result.get('message') : 'PDF generation failed';
return new Map<String, Object>{
'success' => false,
'error' => errorMessage
};
}
} else {
return new Map<String, Object>{
'success' => false,
'error' => 'HTTP ' + response.getStatusCode() + ': ' + response.getBody()
};
}
} catch (Exception e) {
return new Map<String, Object>{
'success' => false,
'error' => 'Exception: ' + e.getMessage()
};
}
}
@AuraEnabled
public static Map<String, Object> generatePdfDirect(String templateName, String propertyData, String htmlContent) {
Map<String, Object> result = new Map<String, Object>();
try {
System.debug('=== PDF GENERATION STARTED ===');
System.debug('Template Name: ' + templateName);
System.debug('Property Data: ' + propertyData);
System.debug('HTML Content Length: ' + (htmlContent != null ? htmlContent.length() : 0));
// Parse property data
Map<String, Object> propertyMap = (Map<String, Object>) JSON.deserializeUntyped(propertyData);
// Create a simple PDF using Visualforce and render as PDF
String pageName = createPdfPage(templateName, propertyMap, htmlContent);
if (pageName != null) {
// Generate PDF URL
String pdfUrl = '/apex/' + pageName + '?id=' + EncodingUtil.urlEncode(htmlContent, 'UTF-8');
result.put('success', true);
result.put('pdfUrl', pdfUrl);
result.put('message', 'PDF generated successfully');
System.debug('PDF generated successfully: ' + pdfUrl);
} else {
result.put('success', false);
result.put('error', 'Failed to create PDF page');
System.debug('Failed to create PDF page');
}
} catch (Exception e) {
System.debug('Error in generatePdfDirect: ' + e.getMessage());
System.debug('Stack trace: ' + e.getStackTraceString());
result.put('success', false);
result.put('error', 'PDF generation failed: ' + e.getMessage());
}
return result;
}
private static String createPdfPage(String templateName, Map<String, Object> propertyData, String htmlContent) {
try {
// Create a unique page name
String pageName = 'PropertyPdf_' + DateTime.now().getTime() + '_' + Math.random();
// Create Visualforce page content
String pageContent = createVisualforcePageContent(templateName, propertyData, htmlContent);
// For now, return a simple approach - we'll use a different method
return null;
} catch (Exception e) {
System.debug('Error creating PDF page: ' + e.getMessage());
return null;
}
}
private static String createVisualforcePageContent(String templateName, Map<String, Object> propertyData, String htmlContent) {
// This would create a Visualforce page, but for now we'll use a simpler approach
return '';
}
// Helper method to get preview content as fallback
private static Map<String, Object> getPreviewContentAsFallback(String templateName, String propertyName,
String propertyType, String location, String price,
String bedrooms, String bathrooms, String area, String description) {
try {
Map<String, Object> previewData = new Map<String, Object>{
'template' => templateName,
'propertyName' => propertyName,
'propertyType' => propertyType,
'location' => location,
'price' => price,
'bedrooms' => bedrooms,
'bathrooms' => bathrooms,
'area' => area,
'description' => description
};
String previewJsonBody = JSON.serialize(previewData);
Http http = new Http();
HttpRequest previewRequest = new HttpRequest();
previewRequest.setEndpoint('https://salesforce.tech4biz.io/api/preview-simple');
previewRequest.setMethod('POST');
previewRequest.setHeader('Content-Type', 'application/json');
previewRequest.setBody(previewJsonBody);
previewRequest.setTimeout(120000);
HttpResponse previewResponse = http.send(previewRequest);
if (previewResponse.getStatusCode() == 200) {
Map<String, Object> previewResult = (Map<String, Object>) JSON.deserializeUntyped(previewResponse.getBody());
Map<String, Object> preview = (Map<String, Object>) previewResult.get('preview');
return new Map<String, Object>{
'success' => true,
'message' => 'PDF generation failed, but preview content is available. Use this to create your PDF manually.',
'preview_html' => preview.get('preview_html'),
'template_info' => preview.get('template_info'),
'property_data' => preview.get('property_data'),
'note' => 'The PDF download endpoint is currently unavailable. Use the preview content to create your PDF manually or contact support.',
'fallback' => true
};
} else {
return new Map<String, Object>{
'success' => false,
'error' => 'Failed to get preview content: HTTP ' + previewResponse.getStatusCode()
};
}
} catch (Exception e) {
return new Map<String, Object>{
'success' => false,
'error' => 'Exception getting preview content: ' + e.getMessage()
};
}
}
@AuraEnabled
public static Map<String, Object> generatePdfServerSide(String templateName, String propertyData, String htmlContent) {
Map<String, Object> result = new Map<String, Object>();
try {
System.debug('=== SERVER-SIDE PDF GENERATION STARTED ===');
System.debug('Template Name: ' + templateName);
System.debug('Property Data: ' + propertyData);
System.debug('HTML Content Length: ' + (htmlContent != null ? htmlContent.length() : 0));
// Parse property data
Map<String, Object> propertyMap = (Map<String, Object>) JSON.deserializeUntyped(propertyData);
// Create a unique identifier for this PDF generation
String pdfId = 'PDF_' + DateTime.now().getTime() + '_' + Math.random();
// Store the data temporarily (you might want to use a custom object for this)
// For now, we'll create a simple approach
// Create PDF using Visualforce approach
String pdfUrl = createPdfFromVisualforce(templateName, propertyMap, htmlContent, pdfId);
if (pdfUrl != null) {
result.put('success', true);
result.put('pdfUrl', pdfUrl);
result.put('message', 'PDF generated successfully on server side');
result.put('pdfId', pdfId);
System.debug('Server-side PDF generated successfully: ' + pdfUrl);
} else {
result.put('success', false);
result.put('error', 'Failed to create PDF from Visualforce');
System.debug('Failed to create PDF from Visualforce');
}
} catch (Exception e) {
System.debug('Error in generatePdfServerSide: ' + e.getMessage());
System.debug('Stack trace: ' + e.getStackTraceString());
result.put('success', false);
result.put('error', 'Server-side PDF generation failed: ' + e.getMessage());
}
return result;
}
private static String createPdfFromVisualforce(String templateName, Map<String, Object> propertyData, String htmlContent, String pdfId) {
try {
// Create a Visualforce page name
String pageName = 'PropertyPdf_' + pdfId.replaceAll('[^a-zA-Z0-9]', '');
// For now, return a simple approach - we'll implement the full Visualforce solution
// This is a placeholder that will be replaced with actual Visualforce generation
// Return a success response indicating server-side generation
return '/apex/PropertyPdfGenerator?template=' + EncodingUtil.urlEncode(templateName, 'UTF-8') +
'&propertyData=' + EncodingUtil.urlEncode(JSON.serialize(propertyData), 'UTF-8') +
'&htmlContent=' + EncodingUtil.urlEncode(htmlContent, 'UTF-8') +
'&pdfId=' + pdfId;
} catch (Exception e) {
System.debug('Error creating PDF from Visualforce: ' + e.getMessage());
return null;
}
}
}