From 80949e584c94395cccb287e3de3a2ba3ad0e9239 Mon Sep 17 00:00:00 2001 From: Hamza-Ayed Date: Fri, 8 May 2026 14:52:14 +0300 Subject: [PATCH] Update: 2026-05-08 14:52:14 --- app/modules_app/batches/finalize.php | 49 ++++++++++++++++++---------- 1 file changed, 32 insertions(+), 17 deletions(-) diff --git a/app/modules_app/batches/finalize.php b/app/modules_app/batches/finalize.php index 188712f..b320ad6 100644 --- a/app/modules_app/batches/finalize.php +++ b/app/modules_app/batches/finalize.php @@ -58,22 +58,37 @@ $stmt = $db->prepare(" "); $stmt->execute([$batchId]); -// 3. Trigger the worker via a "Fire and Forget" HTTP request -// This ensures processing starts immediately but the mobile app doesn't timeout. -$workerUrl = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . '/api/v1/batches/process-worker'; -$postData = json_encode(['batch_id' => $batchId]); +// 3. Post-Response Processing (Background) +// Manually send response instead of json_success() because it calls exit; +header('Content-Type: application/json; charset=utf-8'); +http_response_code(200); +echo json_encode([ + 'success' => true, + 'data' => [ + 'batch_id' => $batchId, + 'status' => 'processing', + 'total_images' => $batch['total_images'] + ], + 'message' => 'تم إنهاء الدفعة بنجاح وبدء المعالجة الفورية', + 'timestamp' => date('c') +], JSON_UNESCAPED_UNICODE); -$ch = curl_init($workerUrl); -curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); -curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); -curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); -curl_setopt($ch, CURLOPT_TIMEOUT, 1); // Only wait 1 second -curl_setopt($ch, CURLOPT_NOSIGNAL, 1); -@curl_exec($ch); -curl_close($ch); +// This allows the mobile app to get an instant success message, +// while the server continues processing the AI extraction in the background. +if (function_exists('fastcgi_finish_request')) { + fastcgi_finish_request(); +} -json_success([ - 'batch_id' => $batchId, - 'status' => 'processing', - 'total_images' => $batch['total_images'] -], 'تم إنهاء الدفعة بنجاح وبدء المعالجة الفورية'); +// Ensure the script keeps running +ignore_user_abort(true); +set_time_limit(300); // Give it 5 minutes + +$queueStmt = $db->prepare("SELECT id FROM invoice_processing_queue WHERE batch_id = ? AND status = 'pending'"); +$queueStmt->execute([$batchId]); +$items = $queueStmt->fetchAll(); + +foreach ($items as $item) { + InvoiceProcessor::processQueueItem((int)$item['id']); +} + +exit; // End here