cmc-sales/php/app/views/documents/pdf_invoice.ctp

184 lines
8.1 KiB
Plaintext
Raw Normal View History

2011-08-15 17:36:48 -07:00
<?php
2026-01-12 03:00:48 -08:00
// Generate the Invoice PDF by calling the Go service instead of TCPDF.
2026-01-18 22:52:57 -08:00
error_log("=== pdf_invoice.ctp: Starting invoice PDF generation ===");
error_log("=== pdf_invoice.ctp: Document ID: " . (isset($document['Document']['id']) ? $document['Document']['id'] : 'UNDEFINED') . " ===");
if (!isset($document) || !isset($document['Document'])) {
error_log("=== pdf_invoice.ctp: ERROR - Document not set in view! ===");
echo "ERROR: Document data not available in view";
exit;
}
2026-01-12 03:00:48 -08:00
$goBaseUrl = AppController::getGoBaseUrlOrFail();
$goEndpoint = $goBaseUrl . '/go/document/generate/invoice';
2026-01-18 22:52:57 -08:00
error_log("=== pdf_invoice.ctp: Go endpoint: " . $goEndpoint . " ===");
2026-01-12 03:00:48 -08:00
$outputDir = Configure::read('pdf_directory');
$lineItems = array();
foreach ($document['LineItem'] as $li) {
$lineItems[] = array(
'item_number' => $li['item_number'],
'quantity' => $li['quantity'],
'title' => $li['title'],
'description' => isset($li['description']) ? $li['description'] : '',
2026-01-16 04:26:56 -08:00
'is_html' => true, // Description is always HTML
2026-01-12 03:00:48 -08:00
'unit_price' => floatval($li['gross_unit_price']),
'total_price' => floatval($li['gross_price']),
'net_unit_price' => floatval($li['net_unit_price']),
'net_price' => floatval($li['net_price']),
'discount_percent' => floatval($li['discount_percent']),
'discount_amount_unit' => floatval($li['discount_amount_unit']),
'discount_amount_total' => floatval($li['discount_amount_total']),
'option' => intval($li['option']),
'has_text_prices' => isset($li['has_text_prices']) ? (bool)$li['has_text_prices'] : false,
'unit_price_string' => isset($li['unit_price_string']) ? $li['unit_price_string'] : '',
'gross_price_string' => isset($li['gross_price_string']) ? $li['gross_price_string'] : ''
2026-01-12 03:00:48 -08:00
);
}
2026-01-16 04:26:56 -08:00
$invoiceNumber = '';
if (!empty($document['Document']['cmc_reference'])) {
$invoiceNumber = $document['Document']['cmc_reference'];
} elseif (!empty($document['Invoice']['title'])) {
// Fallback so the Go service always receives a number-like value
$invoiceNumber = $document['Invoice']['title'];
}
2026-01-18 00:53:46 -08:00
// Add fallback logic for missing fields
$invoiceTitle = isset($document['Invoice']['title']) && !empty($document['Invoice']['title'])
? $document['Invoice']['title']
: 'Invoice-' . $document['Document']['id'];
$customerName = 'Customer';
if (isset($enquiry['Customer']['name']) && !empty($enquiry['Customer']['name'])) {
$customerName = $enquiry['Customer']['name'];
} elseif (isset($document['Document']['cmc_reference']) && !empty($document['Document']['cmc_reference'])) {
$customerName = $document['Document']['cmc_reference'];
}
// Add fallback logic for all enquiry-dependent fields
$contactEmail = isset($enquiry['Contact']['email']) ? $enquiry['Contact']['email'] : '';
$contactName = '';
if (isset($enquiry['Contact']['first_name']) && isset($enquiry['Contact']['last_name'])) {
$contactName = $enquiry['Contact']['first_name'] . ' ' . $enquiry['Contact']['last_name'];
}
$userFirstName = isset($enquiry['User']['first_name']) ? $enquiry['User']['first_name'] : '';
$userLastName = isset($enquiry['User']['last_name']) ? $enquiry['User']['last_name'] : '';
$userEmail = isset($enquiry['User']['email']) ? $enquiry['User']['email'] : '';
$yourReference = '';
if (isset($enquiry['Enquiry']['customer_reference']) && !empty($enquiry['Enquiry']['customer_reference'])) {
$yourReference = $enquiry['Enquiry']['customer_reference'];
} else if (isset($enquiry['Enquiry']['created'])) {
$yourReference = 'Enquiry on ' . date('j M Y', strtotime($enquiry['Enquiry']['created']));
} else {
$yourReference = 'Enquiry on ' . date('j M Y');
}
2026-01-12 03:00:48 -08:00
$payload = array(
'document_id' => intval($document['Document']['id']),
2026-01-16 04:26:56 -08:00
'invoice_number' => $invoiceNumber,
2026-01-18 00:53:46 -08:00
'invoice_title' => $invoiceTitle,
'customer_name' => $customerName,
'contact_email' => $contactEmail,
'contact_name' => $contactName,
'user_first_name' => $userFirstName,
'user_last_name' => $userLastName,
'user_email' => $userEmail,
'your_reference' => $yourReference,
2026-01-12 03:00:48 -08:00
'ship_via' => $document['Invoice']['ship_via'],
'fob' => $fob,
2026-01-12 03:00:48 -08:00
'issue_date' => $document['Invoice']['issue_date'], // expects YYYY-MM-DD
'issue_date_string' => $issue_date_string,
2026-01-12 03:00:48 -08:00
'currency_symbol' => $currencySymbol,
'currency_code' => $currencyCode,
2026-01-12 03:00:48 -08:00
'show_gst' => (bool)$gst,
'bill_to' => isset($document['Document']['bill_to']) ? $document['Document']['bill_to'] : '',
'ship_to' => isset($document['Document']['ship_to']) ? $document['Document']['ship_to'] : '',
'shipping_details' => isset($document['Document']['shipping_details']) ? $document['Document']['shipping_details'] : '',
'customer_order_number' => isset($job['Job']['customer_order_number']) ? $job['Job']['customer_order_number'] : '',
'job_title' => isset($job['Job']['title']) ? $job['Job']['title'] : '',
'payment_terms' => isset($job['Customer']['payment_terms']) ? $job['Customer']['payment_terms'] : '',
'customer_abn' => isset($job['Customer']['abn']) ? $job['Customer']['abn'] : '',
'subtotal' => $totals['subtotal'],
'gst_amount' => $totals['gst'],
'total' => $totals['total'],
2026-01-12 03:00:48 -08:00
'line_items' => $lineItems,
'output_dir' => $outputDir
);
$ch = curl_init($goEndpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
2026-01-18 22:52:57 -08:00
error_log("=== pdf_invoice.ctp: Making curl request to Go service ===");
2026-01-12 03:00:48 -08:00
$response = curl_exec($ch);
2026-01-18 22:52:57 -08:00
error_log("=== pdf_invoice.ctp: Curl response received: " . substr($response, 0, 200) . " ===");
2026-01-12 03:00:48 -08:00
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr = curl_error($ch);
2026-01-18 22:52:57 -08:00
error_log("=== pdf_invoice.ctp: HTTP Code: " . $httpCode . ", Curl Error: " . $curlErr . " ===");
2026-01-12 03:00:48 -08:00
curl_close($ch);
if ($httpCode < 200 || $httpCode >= 300) {
2026-01-13 03:56:08 -08:00
echo "<p>Failed to generate PDF via Go service (HTTP $httpCode).<br>";
echo "Endpoint: " . htmlspecialchars($goEndpoint) . "<br>";
2026-01-12 03:00:48 -08:00
if ($curlErr) {
2026-01-13 03:56:08 -08:00
echo "Error: " . htmlspecialchars($curlErr) . "<br>";
}
if (!empty($response)) {
echo "Response: " . htmlspecialchars($response) . "<br>";
2026-01-12 03:00:48 -08:00
}
echo "</p>";
exit;
}
2011-08-15 17:36:48 -07:00
2026-01-18 22:52:57 -08:00
// PDF generated successfully - capture the filename from Go and save to database
$result = json_decode($response, true);
if (isset($result['filename'])) {
$Document = ClassRegistry::init('Document');
$Document->id = $document['Document']['id'];
$Document->saveField('pdf_filename', $result['filename']);
$Document->saveField('pdf_created_at', date('Y-m-d H:i:s'));
// Get user ID safely
$userId = null;
if (isset($this->Session)) {
$userId = $this->Session->read('Auth.User.id');
}
if ($userId) {
$Document->saveField('pdf_created_by_user_id', $userId);
}
// Count pages using the Go service
App::import('Vendor','pagecounter');
$pageCounter = new PageCounter();
$pdfPath = $outputDir . '/' . $result['filename'];
error_log("=== pdf_invoice.ctp: Counting pages for PDF: " . $pdfPath . " ===");
$pageCount = $pageCounter->count($pdfPath);
error_log("=== pdf_invoice.ctp: Page count result: " . var_export($pageCount, true) . " ===");
if ($pageCount !== null && $pageCount > 0) {
$Document->saveField('doc_page_count', $pageCount);
error_log("=== pdf_invoice.ctp: Saved page count: " . $pageCount . " ===");
} else {
error_log("=== pdf_invoice.ctp: Page count was null or 0, not saving ===");
}
}
error_log("=== pdf_invoice.ctp: About to redirect to /documents/view/" . $document['Document']['id'] . " ===");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0;url=/documents/view/<?=$document['Document']['id']?>">
</head>
<body>
<p>PDF generated successfully. <a href="/documents/view/<?=$document['Document']['id']?>">Click here if you are not redirected</a>.</p>
2011-08-15 17:36:48 -07:00
<script type="text/javascript">
window.location.replace("/documents/view/<?=$document['Document']['id']?>");
2011-08-15 17:36:48 -07:00
</script>
2026-01-18 22:52:57 -08:00
</body>
</html>