Update: 2026-07-30 02:27:45

This commit is contained in:
Hamza-Ayed
2026-07-30 02:27:45 +03:00
parent 5f62455113
commit ca4a7c2e70
56 changed files with 3391 additions and 709 deletions
+13 -10
View File
@@ -32,7 +32,9 @@ if ($errors) {
$companyId = $data['company_id'];
$source = $data['source'] ?? 'mobile_scan';
$expectedImages = (int)($data['expected_images'] ?? 0);
// The mobile client sends 'total_images'; older/web callers send 'expected_images'.
// Accept both so the expected count is never silently zero.
$expectedImages = (int)($data['expected_images'] ?? $data['total_images'] ?? 0);
// 2. Permission check
$db = Database::getInstance();
@@ -52,24 +54,25 @@ if ($decoded['role'] !== 'super_admin' && $company['tenant_id'] !== $tenantId) {
// Use the actual tenant of the company
$targetTenantId = $company['tenant_id'];
// 3. Check quota (preview — don't increment yet)
// 3. Reserve quota for the WHOLE batch up front, not just one invoice.
// checkInvoiceQuota() responds and exits by itself when there is no room, so the
// old try/catch wrapper never actually caught anything.
if ($decoded['role'] !== 'super_admin') {
try {
QuotaMiddleware::checkInvoiceQuota($targetTenantId);
} catch (\Exception $e) {
json_error('تم استنفاد رصيد الفواتير لهذا الشهر. قم بترقية باقتك.', 429);
}
QuotaMiddleware::checkInvoiceQuota($targetTenantId, max(1, $expectedImages));
}
// 4. Generate batch ID
$batchId = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4));
// 5. Create batch record
// 5. Create batch record.
// total_images starts at 0 and is incremented by upload-image for each file that
// actually lands. Seeding it with the client's expected count here would double
// count and break the (processed + failed) >= total completion check.
$stmt = $db->prepare("
INSERT INTO invoice_batches (id, tenant_id, company_id, uploaded_by, total_images, source, status)
VALUES (?, ?, ?, ?, ?, ?, 'uploading')
VALUES (?, ?, ?, ?, 0, ?, 'uploading')
");
$stmt->execute([$batchId, $targetTenantId, $companyId, $userId, $expectedImages, $source]);
$stmt->execute([$batchId, $targetTenantId, $companyId, $userId, $source]);
// 6. Create upload directory
$uploadDir = STORAGE_PATH . '/invoices/' . $targetTenantId . '/' . $companyId . '/batches/' . $batchId;
+24 -6
View File
@@ -48,14 +48,19 @@ if ($batch['total_images'] == 0) {
json_error('لا يمكن إنهاء دفعة فارغة', 400);
}
// 2. Mark as processing
// 2. Mark as processing - atomically, so two concurrent finalize calls cannot
// both start a background worker for the same batch.
$stmt = $db->prepare("
UPDATE invoice_batches
SET status = 'processing', updated_at = NOW()
WHERE id = ?
UPDATE invoice_batches
SET status = 'processing', updated_at = NOW()
WHERE id = ? AND status = 'uploading'
");
$stmt->execute([$batchId]);
if ($stmt->rowCount() !== 1) {
json_error('تم إنهاء هذه الدفعة مسبقاً', 400);
}
// 3. Send response IMMEDIATELY to mobile app
// We manually build the response instead of using json_success() because it calls exit()
$responsePayload = json_encode([
@@ -117,7 +122,16 @@ $bgLog = function(string $msg) {
$bgLog("Background processing started for batch: $batchId");
try {
$queueStmt = $db->prepare("SELECT id FROM invoice_processing_queue WHERE batch_id = ? AND status = 'pending' ORDER BY created_at ASC");
// processQueueItem() claims each row atomically, so it is safe for the cron
// worker to be walking the same batch at the same time - whoever claims a row
// first owns it and the other simply skips it.
$queueStmt = $db->prepare("
SELECT id FROM invoice_processing_queue
WHERE batch_id = ?
AND status = 'pending'
AND attempts < COALESCE(max_attempts, 3)
ORDER BY image_order ASC, created_at ASC
");
$queueStmt->execute([$batchId]);
$items = $queueStmt->fetchAll(\PDO::FETCH_COLUMN);
@@ -127,12 +141,16 @@ try {
$bgLog("Processing queue item: $queueId");
try {
$success = InvoiceProcessor::processQueueItem((int)$queueId);
$bgLog("Queue item $queueId: " . ($success ? "SUCCESS" : "FAILED"));
$bgLog("Queue item $queueId: " . ($success ? "SUCCESS" : "FAILED/SKIPPED"));
} catch (\Throwable $e) {
$bgLog("Queue item $queueId EXCEPTION: " . $e->getMessage());
}
}
// Final sweep: if every item ended up terminal, close the batch here rather
// than waiting up to a minute for the cron to notice.
InvoiceProcessor::checkBatchCompletion($batchId);
$bgLog("Background processing finished for batch: $batchId");
} catch (\Throwable $e) {
@@ -1,38 +0,0 @@
<?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";
+10 -4
View File
@@ -40,15 +40,21 @@ if (!$batch || ($decoded['role'] !== 'super_admin' && $batch['tenant_id'] !== $t
// 2. Get items
$stmt = $db->prepare("
SELECT id, invoice_id, image_order, status, error_message, created_at, processed_at
SELECT id, invoice_id, image_order, status, attempts, max_attempts, error_message, created_at, processed_at
FROM invoice_processing_queue
WHERE batch_id = ?
ORDER BY image_order ASC
ORDER BY image_order ASC, id ASC
");
$stmt->execute([$batchId]);
$items = $stmt->fetchAll();
// 3. Tell the client explicitly whether it should keep polling. Without this the
// app polled forever whenever a batch ended in anything other than 'done'.
$isTerminal = in_array($batch['status'], ['done', 'partial_fail', 'failed'], true);
json_success([
'batch' => $batch,
'items' => $items
'batch' => $batch,
'items' => $items,
'is_terminal' => $isTerminal,
'should_poll' => !$isTerminal,
], 'تم جلب حالة الدفعة');
+28 -7
View File
@@ -18,7 +18,9 @@ $userId = $decoded['user_id'];
// 1. Validate request
$batchId = $_POST['batch_id'] ?? null;
$imageOrder = (int)($_POST['image_order'] ?? 0);
// The mobile client sends 'order_index'; accept both spellings so every image
// does not end up with order 0 (which also made every saved file img_000_*).
$imageOrder = (int)($_POST['image_order'] ?? $_POST['order_index'] ?? 0);
if (!$batchId || !isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
$uploadError = $_FILES['image']['error'] ?? 'No file';
@@ -46,11 +48,20 @@ if ($batch['status'] !== 'uploading') {
json_error('لا يمكن إضافة صور لدفعة تمت معالجتها', 400);
}
// 3. Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/heic', 'image/heif', 'application/pdf'];
$mimeType = $_FILES['image']['type'];
if (!in_array($mimeType, $allowedTypes)) {
json_error('نوع الملف غير مدعوم. المسموح: صور و PDF', 422);
// 3. Validate file type.
// Sniff the real type off the temp file - $_FILES[...]['type'] is supplied by the
// client and can claim anything.
$allowedTypes = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/webp' => 'webp',
'image/heic' => 'heic',
'image/heif' => 'heif',
'application/pdf' => 'pdf',
];
$mimeType = @mime_content_type($_FILES['image']['tmp_name']) ?: '';
if (!isset($allowedTypes[$mimeType])) {
json_error('نوع الملف غير مدعوم. المسموح: صور (JPG, PNG, WEBP, HEIC) و PDF', 422);
}
// 4. Validate file size (max 10MB)
@@ -59,6 +70,16 @@ if ($_FILES['image']['size'] > $maxSize) {
json_error('حجم الصورة أكبر من 10 ميغابايت', 422);
}
// 4b. Enforce quota per image, not just once per batch. Checking only at
// batches/create let a 50-image batch through on a single remaining credit.
$queuedStmt = $db->prepare("SELECT COUNT(*) FROM invoice_processing_queue WHERE batch_id = ?");
$queuedStmt->execute([$batchId]);
$alreadyQueued = (int)$queuedStmt->fetchColumn();
if ($decoded['role'] !== 'super_admin') {
\App\Middleware\QuotaMiddleware::checkInvoiceQuota($tenantId, $alreadyQueued + 1);
}
// 5. Save file
$companyId = $batch['company_id'];
$uploadDir = STORAGE_PATH . '/invoices/' . $tenantId . '/' . $companyId . '/batches/' . $batchId;
@@ -66,7 +87,7 @@ if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION) ?: 'jpg';
$extension = $allowedTypes[$mimeType];
$fileName = sprintf('img_%03d_%s.%s', $imageOrder, bin2hex(random_bytes(4)), $extension);
$targetPath = $uploadDir . '/' . $fileName;