Update: 2026-05-08 14:47:40

This commit is contained in:
Hamza-Ayed
2026-05-08 14:47:40 +03:00
parent 30974da55b
commit 0d8ff9a7b1
2 changed files with 51 additions and 17 deletions

View File

@@ -58,26 +58,22 @@ $stmt = $db->prepare("
");
$stmt->execute([$batchId]);
// 3. If it's a single invoice, try processing it SYNCHRONOUSLY right now!
if ($batch['total_images'] == 1) {
// We need the queue ID for this batch
$queueStmt = $db->prepare("SELECT id FROM invoice_processing_queue WHERE batch_id = ? AND status = 'pending' LIMIT 1");
$queueStmt->execute([$batchId]);
$queueId = $queueStmt->fetchColumn();
// 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]);
if ($queueId) {
InvoiceProcessor::processQueueItem((int)$queueId);
}
} else {
// For multiple invoices, try triggering the worker in the background
$workerPath = ROOT_PATH . '/app/cron/process_batches.php';
$logPath = STORAGE_PATH . '/logs/cron.log';
// Mute exec since it might fail depending on server config
@exec("php " . escapeshellarg($workerPath) . " >> " . escapeshellarg($logPath) . " 2>&1 &");
}
$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);
json_success([
'batch_id' => $batchId,
'status' => 'processing',
'total_images' => $batch['total_images']
], 'تم إنهاء الدفعة بنجاح وإرسالها للمعالجة');
], 'تم إنهاء الدفعة بنجاح وبدء المعالجة الفورية');

View File

@@ -0,0 +1,38 @@
<?php
/**
* Background Worker Trigger (HTTP)
* POST /api/v1/batches/process-worker
*
* This endpoint is triggered by finalize.php to start processing in the background.
*/
declare(strict_types=1);
require_once __DIR__ . '/../../../bootstrap/init.php';
use App\Services\InvoiceProcessor;
use App\Core\Database;
// 1. Ignore user abort and set no time limit
ignore_user_abort(true);
set_time_limit(0);
// 2. Get batch ID
$data = json_decode(file_get_contents('php://input'), true);
$batchId = $data['batch_id'] ?? null;
if (!$batchId) {
exit('No batch ID');
}
// 3. Process all pending items for this batch
$db = Database::getInstance();
$stmt = $db->prepare("SELECT id FROM invoice_processing_queue WHERE batch_id = ? AND status = 'pending'");
$stmt->execute([$batchId]);
$items = $stmt->fetchAll();
foreach ($items as $item) {
InvoiceProcessor::processQueueItem((int)$item['id']);
}
echo "Done";