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
+29 -5
View File
@@ -40,7 +40,12 @@ if (!$user || !password_verify($password, $user['password_hash'])) {
}
$deviceId = $data['device_id'] ?? null;
$isReviewer = (strtolower($email) === 'reviewer@musadaq.jo');
// App-store reviewer account skips the WhatsApp OTP step (reviewers have no
// access to the registered phone). Configured via .env so the exception is not
// baked into the source, and disabled entirely when the var is unset.
$reviewerEmail = strtolower(trim((string)env('REVIEWER_EMAIL', '')));
$isReviewer = $reviewerEmail !== '' && strtolower($email) === $reviewerEmail;
if ($deviceId && !$isReviewer) {
// Generate and send WhatsApp OTP
@@ -127,7 +132,9 @@ if ($deviceId) {
$deviceName,
$data['platform'] ?? 'web',
$data['app_version'] ?? '1.0.0',
password_hash($deviceSecret, PASSWORD_DEFAULT),
// Stored encrypted, NOT bcrypt-hashed: the server must be able to
// recompute the client's HMAC signature from this same secret.
\App\Core\Encryption::encrypt($deviceSecret),
]);
}
@@ -152,11 +159,28 @@ $payload = [
$token = JWT::encode($payload, $secret);
// 5. Update Refresh Token (Hashed before storage for security)
// 5. Issue Refresh Token (hashed before storage).
//
// Mobile tokens are stored PER DEVICE. users.refresh_token_hash is a single
// column, so writing there logged the user out of every other device silently.
$refreshToken = bin2hex(random_bytes(32));
$refreshTokenHash = hash('sha256', $refreshToken);
$stmt = $db->prepare("UPDATE users SET refresh_token_hash = ?, last_login_at = NOW() WHERE id = ?");
$stmt->execute([$refreshTokenHash, $user['id']]);
$refreshTtlDays = $deviceId ? 60 : 7;
$refreshExpiresAt = date('Y-m-d H:i:s', time() + ($refreshTtlDays * 24 * 3600));
if ($deviceId) {
$stmt = $db->prepare("
UPDATE user_devices
SET refresh_token_hash = ?, refresh_expires_at = ?, last_seen_at = NOW()
WHERE user_id = ? AND device_fingerprint = ?
");
$stmt->execute([$refreshTokenHash, $refreshExpiresAt, $user['id'], $deviceId]);
$db->prepare("UPDATE users SET last_login_at = NOW() WHERE id = ?")->execute([$user['id']]);
} else {
$stmt = $db->prepare("UPDATE users SET refresh_token_hash = ?, last_login_at = NOW() WHERE id = ?");
$stmt->execute([$refreshTokenHash, $user['id']]);
}
// 6. Secure Refresh Token delivery via HttpOnly Cookie (for web)
if (!$deviceId) {
+20 -3
View File
@@ -10,9 +10,26 @@ use App\Middleware\AuthMiddleware;
$decoded = AuthMiddleware::check();
$userId = $decoded['user_id'];
// 2. Invalidate Refresh Token
// 2. Invalidate the refresh token.
// A mobile logout must only sign THIS device out - clearing the shared user
// column would drop every other device the user owns.
$db = Database::getInstance();
$stmt = $db->prepare("UPDATE users SET refresh_token_hash = NULL WHERE id = ?");
$stmt->execute([$userId]);
$deviceId = $decoded['device_id'] ?? null;
if ($deviceId) {
$stmt = $db->prepare("
UPDATE user_devices
SET refresh_token_hash = NULL,
refresh_expires_at = NULL,
push_token = NULL,
live_activity_token = NULL,
is_trusted = 0
WHERE user_id = ? AND device_fingerprint = ?
");
$stmt->execute([$userId, $deviceId]);
} else {
$stmt = $db->prepare("UPDATE users SET refresh_token_hash = NULL WHERE id = ?");
$stmt->execute([$userId]);
}
json_success(null, 'تم تسجيل الخروج بنجاح');
+10 -5
View File
@@ -64,8 +64,12 @@ try {
exit;
}
// A disabled account must produce the SAME answer as an unknown number,
// otherwise this endpoint tells an attacker which phones are registered.
if (!$user['is_active']) {
json_error('الحساب معطّل. تواصل مع المسؤول.', 403);
error_log("OTP request for disabled account: user {$user['id']}");
json_success(null, 'إذا كان الرقم مسجلاً، سيتم إرسال رمز التحقق');
exit;
}
// 3. Generate OTP (6 digits)
@@ -102,16 +106,17 @@ try {
$result = $whatsappService->sendMessage($phone, $message);
if (!$result['success']) {
error_log("ERROR: Failed to send OTP WhatsApp to phone: {$phone}");
json_error('عذراً، فشل في إرسال رمز التحقق. الرجاء التأكد من صحة رقم الواتساب الخاص بك والمحاولة مرة أخرى.', 500, ['whatsapp_debug' => $result]);
// Internal provider details stay in the log, not in the HTTP response.
error_log("ERROR: Failed to send OTP WhatsApp to phone: {$phone} - " . json_encode($result));
json_error('عذراً، فشل في إرسال رمز التحقق. الرجاء التأكد من صحة رقم الواتساب الخاص بك والمحاولة مرة أخرى.', 500);
}
// Log for development (REMOVE IN PRODUCTION!)
// Development only - never reached when APP_DEBUG is false.
if (env('APP_DEBUG', 'false') === 'true') {
error_log("DEV OTP for {$phone}: {$otp}");
}
json_success(['whatsapp_debug' => $result], 'إذا كان الرقم مسجلاً، سيتم إرسال رمز التحقق عبر واتساب');
json_success(null, 'إذا كان الرقم مسجلاً، سيتم إرسال رمز التحقق عبر واتساب');
} catch (\Exception $e) {
safe_error($e, 'auth/mobile_request_otp');
+15 -4
View File
@@ -132,7 +132,9 @@ $stmt->execute([
$platform,
$appVersion,
$pushToken,
password_hash($deviceSecret, PASSWORD_DEFAULT), // Store hashed
// Stored encrypted (reversible), not bcrypt-hashed: HmacMiddleware has to
// recompute the same signature the client produced from this secret.
\App\Core\Encryption::encrypt($deviceSecret),
]);
// 6. Generate JWT (30 days for mobile)
@@ -153,11 +155,20 @@ $payload = [
$token = JWT::encode($payload, $secret);
// 7. Generate refresh token
// 7. Generate refresh token, stored against THIS device so signing in on a
// second phone does not silently invalidate the first one.
$refreshToken = bin2hex(random_bytes(32));
$refreshTokenHash = hash('sha256', $refreshToken);
$stmt = $db->prepare("UPDATE users SET refresh_token_hash = ?, last_login_at = NOW() WHERE id = ?");
$stmt->execute([$refreshTokenHash, $userId]);
$refreshExpiresAt = date('Y-m-d H:i:s', time() + (60 * 24 * 3600)); // 60 days
$stmt = $db->prepare("
UPDATE user_devices
SET refresh_token_hash = ?, refresh_expires_at = ?, last_seen_at = NOW()
WHERE user_id = ? AND device_fingerprint = ?
");
$stmt->execute([$refreshTokenHash, $refreshExpiresAt, $userId, $deviceId]);
$db->prepare("UPDATE users SET last_login_at = NOW() WHERE id = ?")->execute([$userId]);
// 8. Decrypt name for response
$userName = $user['name'];
+90 -16
View File
@@ -1,13 +1,30 @@
<?php
/**
* Refresh Token Endpoint (Secure Cookie Based)
* Refresh Token Endpoint
*
* Two callers, two transports:
* - Web: HttpOnly cookie, token stored on users.refresh_token_hash
* - Mobile: JSON body {refresh_token, device_id}, token stored per device on
* user_devices.refresh_token_hash
*
* The mobile path used to be missing entirely (cookies only), so the app had no
* way to refresh and simply started failing with 401s once the JWT aged out.
*/
use App\Core\Database;
use Firebase\JWT\JWT;
declare(strict_types=1);
// 1. Get Refresh Token from HttpOnly Cookie
$refreshToken = $_COOKIE['refresh_token'] ?? null;
use App\Core\Database;
use App\Core\JWT;
use App\Core\Security;
use App\Middleware\RateLimitMiddleware;
// Refresh is unauthenticated by design, so rate limit it.
RateLimitMiddleware::check(20, 60);
$data = Security::sanitize(input());
$refreshToken = $_COOKIE['refresh_token'] ?? ($data['refresh_token'] ?? null);
$deviceId = $data['device_id'] ?? null;
if (!$refreshToken) {
json_error('Refresh token is required', 401);
@@ -16,30 +33,87 @@ if (!$refreshToken) {
$db = Database::getInstance();
$refreshTokenHash = hash('sha256', $refreshToken);
// 2. Verify in DB
$stmt = $db->prepare("SELECT * FROM users WHERE refresh_token_hash = ? AND is_active = 1 LIMIT 1");
$stmt->execute([$refreshTokenHash]);
$user = $stmt->fetch();
$user = null;
$isMobile = false;
// 1. Mobile: per-device lookup.
if ($deviceId) {
$stmt = $db->prepare("
SELECT u.*, d.device_fingerprint, d.refresh_expires_at
FROM user_devices d
JOIN users u ON u.id = d.user_id
WHERE d.refresh_token_hash = ?
AND d.device_fingerprint = ?
AND d.is_trusted = 1
AND u.is_active = 1
LIMIT 1
");
$stmt->execute([$refreshTokenHash, $deviceId]);
$user = $stmt->fetch();
if ($user) {
$isMobile = true;
if (!empty($user['refresh_expires_at']) && strtotime($user['refresh_expires_at']) < time()) {
json_error('انتهت صلاحية الجلسة. يرجى تسجيل الدخول من جديد.', 401);
}
}
}
// 2. Web: single-column lookup.
if (!$user) {
$stmt = $db->prepare("SELECT * FROM users WHERE refresh_token_hash = ? AND is_active = 1 LIMIT 1");
$stmt->execute([$refreshTokenHash]);
$user = $stmt->fetch();
}
if (!$user) {
json_error('Invalid refresh token', 401);
}
// 3. Generate New Access Token
$secret = $_ENV['JWT_SECRET'] ?? null;
if (!$secret) {
// 3. Generate a new access token.
$secret = env('JWT_SECRET');
if (!$secret || strlen($secret) < 32) {
error_log('FATAL: JWT_SECRET is missing or too short in .env');
json_error('Server configuration error', 500);
}
$payload = [
'user_id' => $user['id'],
'tenant_id' => $user['tenant_id'], // Now including tenant_id
'tenant_id' => $user['tenant_id'],
'role' => $user['role'],
'exp' => time() + (15 * 60) // 15 minutes
'device_id' => $isMobile ? $deviceId : null,
'source' => $isMobile ? 'mobile' : 'web',
'exp' => time() + ($isMobile ? (30 * 24 * 3600) : (15 * 60)),
];
$token = JWT::encode($payload, $secret, 'HS256');
$token = JWT::encode($payload, $secret);
// 4. Rotate the refresh token so a leaked one cannot be replayed indefinitely.
$newRefreshToken = bin2hex(random_bytes(32));
$newHash = hash('sha256', $newRefreshToken);
if ($isMobile) {
$expiresAt = date('Y-m-d H:i:s', time() + (60 * 24 * 3600));
$db->prepare("
UPDATE user_devices
SET refresh_token_hash = ?, refresh_expires_at = ?, last_seen_at = NOW()
WHERE user_id = ? AND device_fingerprint = ?
")->execute([$newHash, $expiresAt, $user['id'], $deviceId]);
} else {
$db->prepare("UPDATE users SET refresh_token_hash = ? WHERE id = ?")
->execute([$newHash, $user['id']]);
setcookie('refresh_token', $newRefreshToken, [
'expires' => time() + (7 * 24 * 60 * 60),
'path' => '/api/v1/auth/refresh',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict',
]);
}
json_success([
'access_token' => $token
'access_token' => $token,
// Web keeps receiving it via the HttpOnly cookie only.
'refresh_token' => $isMobile ? $newRefreshToken : null,
]);
+8
View File
@@ -32,6 +32,14 @@ if (isset($data['push_token'])) {
$params[] = $data['push_token'];
}
// ActivityKit push token for the currently running Live Activity (iOS).
// This is a DIFFERENT token from the FCM registration token above: APNs
// liveactivity pushes must target this one specifically.
if (isset($data['live_activity_token'])) {
$updateFields[] = 'live_activity_token = ?';
$params[] = $data['live_activity_token'];
}
if (isset($data['app_version'])) {
$updateFields[] = 'app_version = ?';
$params[] = $data['app_version'];
+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;
+38 -5
View File
@@ -84,7 +84,31 @@ try {
}
}
$extension = pathinfo($_FILES['invoice']['name'], PATHINFO_EXTENSION);
// 4a. Validate the file BEFORE storing it. The client-supplied
// $_FILES['invoice']['type'] is attacker-controlled, so sniff the real type
// off the temp file and derive the extension from that, never from the name.
$allowedMimeTypes = [
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/webp' => 'webp',
'image/heic' => 'heic',
'image/heif' => 'heif',
'application/pdf' => 'pdf',
];
$maxSize = 10 * 1024 * 1024; // 10MB
if ($_FILES['invoice']['size'] > $maxSize) {
json_error('حجم الملف أكبر من 10 ميغابايت', 422);
exit;
}
$detectedMime = @mime_content_type($_FILES['invoice']['tmp_name']) ?: '';
if (!isset($allowedMimeTypes[$detectedMime])) {
json_error('نوع الملف غير مدعوم. المسموح: صور (JPG, PNG, WEBP, HEIC) و PDF', 422);
exit;
}
$extension = $allowedMimeTypes[$detectedMime];
$fileName = bin2hex(random_bytes(8)) . '_' . time() . '.' . $extension;
$targetFile = $uploadDir . $fileName;
@@ -94,13 +118,17 @@ try {
}
// 5. Run AI Extraction
$mimeType = $_FILES['invoice']['type'];
$mimeType = $detectedMime;
$fileContent = file_get_contents($targetFile);
$base64Data = base64_encode($fileContent);
$extracted = AI::extractInvoiceData($base64Data, $mimeType);
// extractInvoices() returns EVERY invoice in the image. extractInvoiceData()
// silently kept only the first, so a photo holding two receipts lost one.
AI::setTenantContext($tenantId);
$extractedInvoices = AI::extractInvoices($base64Data, $mimeType);
AI::setTenantContext(null);
if (!$extracted) {
if (empty($extractedInvoices)) {
$invoiceId = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex(random_bytes(16)), 4));
$stmt = $db->prepare("
INSERT INTO invoices (
@@ -115,9 +143,14 @@ try {
}
// 6. Save Extracted Data
// Multiple invoices in one image each consume a credit, so make sure the
// tenant can actually cover the whole set before writing any of them.
if ($decoded['role'] !== 'super_admin' && count($extractedInvoices) > 1) {
QuotaMiddleware::checkInvoiceQuota($tenantId, count($extractedInvoices));
}
$db->beginTransaction();
$extractedInvoices = $extracted['invoices'] ?? [$extracted];
$savedIds = [];
foreach ($extractedInvoices as $inv) {
+12 -3
View File
@@ -88,16 +88,25 @@ try {
date('Y-m-d H:i:s')
]);
json_success(null, 'تم إضافة المستخدم بنجاح');
// Audit BEFORE responding: json_success() calls exit(), so anything after it
// never ran and user creation was never recorded in the audit log.
AuditLogger::log('user.created', 'user', null, null, [
'name' => $data['name'],
'email' => $data['email'],
'role' => $data['role'],
], $decoded);
json_success(null, 'تم إضافة المستخدم بنجاح');
} catch (\Exception $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
$msg = $e->getMessage();
if (str_contains($msg, 'Duplicate entry')) {
// Say which field actually collided - reporting "email" for a duplicate
// phone sent admins hunting for the wrong problem.
if (str_contains($msg, 'phone')) {
json_error('رقم الهاتف مسجل مسبقاً لمستخدم آخر', 409);
}
json_error('البريد الإلكتروني مسجل مسبقاً', 409);
}
error_log('[users/create] ' . $msg);
json_error('حدث خطأ أثناء حفظ البيانات', 500);
}