57 lines
1.3 KiB
PHP
57 lines
1.3 KiB
PHP
<?php
|
|
/**
|
|
* Background Worker for AI Invoice Extraction
|
|
* Processes images in the invoice_processing_queue.
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/../bootstrap/init.php';
|
|
|
|
use App\Services\InvoiceProcessor;
|
|
|
|
// Prevent multiple instances (Lock file)
|
|
$lockFile = STORAGE_PATH . '/logs/process_batches.lock';
|
|
$fp = fopen($lockFile, 'c+');
|
|
if (!flock($fp, LOCK_EX | LOCK_NB)) {
|
|
exit("Worker already running.\n");
|
|
}
|
|
|
|
echo "Starting Musadaq AI Worker [" . date('Y-m-d H:i:s') . "]\n";
|
|
|
|
try {
|
|
$db = Database::getInstance();
|
|
|
|
while (true) {
|
|
$stmt = $db->prepare("
|
|
SELECT id FROM invoice_processing_queue
|
|
WHERE status = 'pending'
|
|
ORDER BY created_at ASC
|
|
LIMIT 1
|
|
");
|
|
$stmt->execute();
|
|
$queueId = $stmt->fetchColumn();
|
|
|
|
if (!$queueId) {
|
|
echo "Queue empty. Waiting...\n";
|
|
sleep(5);
|
|
continue;
|
|
}
|
|
|
|
echo "Processing Queue ID: $queueId\n";
|
|
$success = InvoiceProcessor::processQueueItem((int)$queueId);
|
|
|
|
if ($success) {
|
|
echo "Success for Queue ID $queueId\n";
|
|
} else {
|
|
echo "Failed for Queue ID $queueId\n";
|
|
}
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
echo "Fatal Worker Error: " . $e->getMessage() . "\n";
|
|
} finally {
|
|
flock($fp, LOCK_UN);
|
|
fclose($fp);
|
|
}
|