Update: 2026-05-04 14:40:41
This commit is contained in:
@@ -20,68 +20,91 @@ if (!$id) {
|
||||
try {
|
||||
$db->beginTransaction();
|
||||
|
||||
// 1. Fetch Invoice
|
||||
$stmt = $db->prepare("SELECT * FROM invoices WHERE id = ? FOR UPDATE");
|
||||
// 1. Fetch Invoice & Company
|
||||
$stmt = $db->prepare("
|
||||
SELECT i.*, c.name as company_name, c.tax_identification_number as company_tin,
|
||||
c.address as company_address, c.jofotara_client_id_encrypted, c.jofotara_secret_key_encrypted
|
||||
FROM invoices i
|
||||
JOIN companies c ON i.company_id = c.id
|
||||
WHERE i.id = ? FOR UPDATE
|
||||
");
|
||||
$stmt->execute([$id]);
|
||||
$invoice = $stmt->fetch();
|
||||
|
||||
if (!$invoice) {
|
||||
json_error('Invoice not found', 404);
|
||||
}
|
||||
|
||||
if ($invoice['status'] === 'approved') {
|
||||
json_error('Invoice is already approved', 400);
|
||||
}
|
||||
|
||||
// Authorization
|
||||
if ($decoded['role'] !== 'super_admin' && $invoice['tenant_id'] !== $decoded['tenant_id']) {
|
||||
json_error('Unauthorized', 403);
|
||||
}
|
||||
if (!$invoice) json_error('Invoice not found', 404);
|
||||
if ($invoice['status'] === 'approved') json_error('Already approved', 400);
|
||||
|
||||
// 2. Fetch Line Items
|
||||
$stmtLines = $db->prepare("SELECT * FROM invoice_lines WHERE invoice_id = ?");
|
||||
$stmtLines->execute([$id]);
|
||||
$invoice['items'] = $stmtLines->fetchAll();
|
||||
|
||||
// 3. Decrypt Sensitive Data for XML Generation
|
||||
$invoice['supplier_name'] = \App\Core\Encryption::decrypt($invoice['supplier_name']) ?: '';
|
||||
$invoice['supplier_tin'] = \App\Core\Encryption::decrypt($invoice['supplier_tin']) ?: '';
|
||||
$invoice['buyer_name'] = \App\Core\Encryption::decrypt($invoice['buyer_name']) ?: '';
|
||||
$invoice['buyer_tin'] = \App\Core\Encryption::decrypt($invoice['buyer_tin']) ?: '';
|
||||
// 3. Decrypt Company Keys for JoFotara
|
||||
$clientId = \App\Core\Encryption::decrypt($invoice['jofotara_client_id_encrypted']);
|
||||
$secretKey = \App\Core\Encryption::decrypt($invoice['jofotara_secret_key_encrypted']);
|
||||
|
||||
// 4. Initialize JoFotara Core
|
||||
if (!$clientId || !$secretKey) {
|
||||
throw new \Exception("JoFotara credentials missing for company: " . $invoice['company_name']);
|
||||
}
|
||||
|
||||
// Decrypt Buyer Info
|
||||
$invoice['buyer_name'] = \App\Core\Encryption::decrypt($invoice['buyer_name']) ?: '';
|
||||
$invoice['buyer_tin'] = \App\Core\Encryption::decrypt($invoice['buyer_tin']) ?: '';
|
||||
|
||||
// 4. Initialize JoFotara Service
|
||||
$jofotara = new JoFotara();
|
||||
|
||||
// 5. Generate TLV QR Code Base64
|
||||
$qrBase64 = $jofotara->generateQRCode($invoice);
|
||||
// 5. Generate UBL 2.1 XML
|
||||
$companyData = [
|
||||
'name' => $invoice['company_name'],
|
||||
'tax_identification_number' => $invoice['company_tin'],
|
||||
'address' => $invoice['company_address']
|
||||
];
|
||||
$xmlContent = $jofotara->generateXML($invoice, $companyData);
|
||||
|
||||
// 6. Generate UBL 2.1 XML
|
||||
$xmlContent = $jofotara->generateXML($invoice);
|
||||
// 6. Submit to JoFotara API
|
||||
$apiResponse = $jofotara->submitInvoice($xmlContent, $clientId, $secretKey);
|
||||
|
||||
// 7. Submit to JoFotara API (Simulation for now)
|
||||
$apiResponse = $jofotara->submitInvoice($xmlContent);
|
||||
// 7. Record Submission (Audit Log)
|
||||
$submissionId = \App\Core\Database::generateUuid();
|
||||
$stmtSub = $db->prepare("
|
||||
INSERT INTO jofotara_submissions
|
||||
(id, invoice_id, company_id, tenant_id, xml_payload, xml_hash,
|
||||
jofotara_uuid, qr_code_raw, response_code, response_body, status, submitted_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
|
||||
");
|
||||
|
||||
$status = $apiResponse['success'] ? 'accepted' : 'rejected';
|
||||
$stmtSub->execute([
|
||||
$submissionId,
|
||||
$id,
|
||||
$invoice['company_id'],
|
||||
$invoice['tenant_id'],
|
||||
$xmlContent,
|
||||
hash('sha256', $xmlContent),
|
||||
$apiResponse['uuid'] ?? null,
|
||||
$apiResponse['qrCode'] ?? null,
|
||||
$apiResponse['_http_code'] ?? '0',
|
||||
json_encode($apiResponse['raw'] ?? []),
|
||||
$status
|
||||
]);
|
||||
|
||||
if (!$apiResponse['success']) {
|
||||
throw new \Exception("JoFotara Rejection: " . ($apiResponse['error'] ?? 'Unknown Error'));
|
||||
}
|
||||
|
||||
// 8. Update Invoice Status & Save JoFotara UUID/QR
|
||||
// 8. Update Invoice
|
||||
$updateStmt = $db->prepare("
|
||||
UPDATE invoices
|
||||
SET status = 'approved',
|
||||
jofotara_uuid = ?,
|
||||
qr_code = ?,
|
||||
updated_at = NOW()
|
||||
WHERE id = ?
|
||||
UPDATE invoices SET status = 'approved', jofotara_uuid = ?, qr_code = ?, updated_at = NOW() WHERE id = ?
|
||||
");
|
||||
$updateStmt->execute([$apiResponse['uuid'] ?? 'mock-uuid', $qrBase64, $id]);
|
||||
$updateStmt->execute([$apiResponse['uuid'], $apiResponse['qrCode'], $id]);
|
||||
|
||||
$db->commit();
|
||||
|
||||
json_success([
|
||||
'message' => 'Invoice approved and submitted to JoFotara successfully.',
|
||||
'jofotara_uuid' => $apiResponse['uuid'] ?? 'mock-uuid',
|
||||
'qr_code' => $qrBase64
|
||||
'message' => 'Approved and submitted to JoFotara.',
|
||||
'uuid' => $apiResponse['uuid'],
|
||||
'qr_code' => $apiResponse['qrCode']
|
||||
]);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
|
||||
@@ -108,41 +108,34 @@ if (move_uploaded_file($_FILES['invoice']['tmp_name'], $targetFile)) {
|
||||
'date' => $extracted['invoice_date'] ?? null,
|
||||
'type' => $extracted['invoice_type'] ?? 'cash',
|
||||
'cat' => $extracted['invoice_category'] ?? 'simplified',
|
||||
's_tin' => \App\Core\Encryption::encrypt($extracted['supplier_tin'] ?? ''),
|
||||
's_name' => \App\Core\Encryption::encrypt($extracted['supplier_name'] ?? ''),
|
||||
's_addr' => \App\Core\Encryption::encrypt($extracted['supplier_address'] ?? ''),
|
||||
'b_tin' => \App\Core\Encryption::encrypt($extracted['buyer_tin'] ?? ''),
|
||||
'b_name' => \App\Core\Encryption::encrypt($extracted['buyer_name'] ?? ''),
|
||||
'b_nid' => \App\Core\Encryption::encrypt($extracted['buyer_national_id'] ?? ''),
|
||||
's_tin' => \App\Core\Encryption::encrypt($extracted['supplier']['tin'] ?? ''),
|
||||
's_name' => \App\Core\Encryption::encrypt($extracted['supplier']['name'] ?? ''),
|
||||
's_addr' => \App\Core\Encryption::encrypt($extracted['supplier']['address'] ?? ''),
|
||||
'b_tin' => \App\Core\Encryption::encrypt($extracted['buyer']['tin'] ?? ''),
|
||||
'b_name' => \App\Core\Encryption::encrypt($extracted['buyer']['name'] ?? ''),
|
||||
'b_nid' => \App\Core\Encryption::encrypt($extracted['buyer']['national_id'] ?? ''),
|
||||
'sub' => $extracted['subtotal'] ?? 0,
|
||||
'tax' => $extracted['tax_amount'] ?? 0,
|
||||
'disc' => $extracted['discount_total'] ?? 0,
|
||||
'total' => $extracted['grand_total'] ?? 0,
|
||||
'cur' => $extracted['currency'] ?? 'JOD'
|
||||
'cur' => $extracted['currency_code'] ?? 'JOD'
|
||||
]);
|
||||
|
||||
// Save Line Items
|
||||
if (!empty($extracted['items'])) {
|
||||
if (!empty($extracted['lines'])) {
|
||||
$lineStmt = $db->prepare("
|
||||
INSERT INTO invoice_lines (invoice_id, line_number, description, quantity, unit_price, tax_rate, line_total)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
");
|
||||
$lineNo = 1;
|
||||
foreach ($extracted['items'] as $item) {
|
||||
// Calculate tax rate if not provided (fallback to 0.16 for Jordan)
|
||||
$taxRate = 0.16;
|
||||
if (!empty($item['unit_price']) && !empty($item['tax_amount'])) {
|
||||
$taxRate = round($item['tax_amount'] / ($item['unit_price'] * ($item['quantity'] ?: 1)), 4);
|
||||
}
|
||||
|
||||
foreach ($extracted['lines'] as $item) {
|
||||
$lineStmt->execute([
|
||||
$invoiceId,
|
||||
$lineNo++,
|
||||
$item['line_number'] ?? 1,
|
||||
$item['description'] ?? 'N/A',
|
||||
$item['quantity'] ?? 1,
|
||||
$item['unit_price'] ?? 0,
|
||||
$taxRate,
|
||||
$item['total'] ?? 0
|
||||
$item['tax_rate'] ?? 0.16,
|
||||
$item['line_total'] ?? 0
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user