🚀 مُصادَق: تحديث برمجي جديد 2026-05-03 15:28

This commit is contained in:
Hamza-Ayed
2026-05-03 15:28:58 +03:00
parent 061431f36a
commit 06dc3885d7
9 changed files with 800 additions and 404 deletions

View File

@@ -5,7 +5,8 @@ declare(strict_types=1);
namespace App\Modules\Auth;
use App\Core\{Request, Response};
use App\Modules\Auth\AuthService;
use App\Services\Security\EncryptionService;
use App\Services\Security\JwtService;
use Throwable;
final class AuthController
@@ -26,7 +27,7 @@ final class AuthController
$result = $this->authService->login($email, $password);
// 2FA Check
if ($result['user']->totp_enabled) {
if (($result['user']['totp_enabled'] ?? false) === true) {
Response::json([
'success' => true,
'requires_2fa' => true,
@@ -71,6 +72,22 @@ final class AuthController
public function logout(Request $request): void
{
$authHeader = $request->getHeader('Authorization');
if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
try {
$token = substr($authHeader, 7);
$jwtService = new JwtService();
$decoded = $jwtService->verifyToken($token);
$jti = (string)($decoded['jti'] ?? '');
$remaining = max(((int)($decoded['exp'] ?? 0)) - time(), 0);
if ($jti !== '') {
$this->authService->logout($jti, $remaining);
}
} catch (Throwable $e) {
error_log('[AUTH] Could not parse token on logout: ' . $e->getMessage());
}
}
// Clear refresh token cookie
setcookie('refresh_token', '', [
'expires' => time() - 3600,
@@ -168,9 +185,10 @@ final class AuthController
$totpService = new \App\Services\TotpService();
if ($totpService->verify($secret, $code)) {
$encryptedSecret = (new EncryptionService())->encrypt($secret);
$db = \App\Core\Database::getInstance();
$stmt = $db->prepare("UPDATE users SET totp_secret = ?, totp_enabled = 1 WHERE id = ?");
$stmt->execute([$secret, $request->user->user_id]);
$stmt->execute([$encryptedSecret, $request->user->user_id]);
Response::json(['success' => true, 'message' => 'تم تفعيل التحقق الثنائي بنجاح']);
} else {
@@ -189,28 +207,58 @@ final class AuthController
$stmt->execute([$userId]);
$secret = $stmt->fetchColumn();
$totpService = new \App\Services\TotpService();
if ($secret && $totpService->verify($secret, $code)) {
// Re-fetch user for full data
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();
$authService = new AuthService();
$tokens = $authService->generateTokens($user);
Response::json([
'success' => true,
'data' => $tokens,
'message' => 'تم التحقق بنجاح'
]);
} else {
Response::error('رمز التحقق غير صحيح', 'INVALID_CODE', 401);
if (!$secret) {
Response::error('لم يتم تفعيل التحقق الثنائي لهذا الحساب', 'TWO_FA_DISABLED', 400);
return;
}
$totpService = new \App\Services\TotpService();
$decrypted = null;
try {
$decrypted = (new EncryptionService())->decrypt((string)$secret);
} catch (Throwable $e) {
// Backward compatibility with old plaintext records
$decrypted = (string)$secret;
}
if (!$totpService->verify($decrypted, $code)) {
Response::error('رمز التحقق غير صحيح', 'INVALID_CODE', 401);
return;
}
// Re-issue a full login session after successful 2FA.
$stmt = $db->prepare("SELECT email FROM users WHERE id = ?");
$stmt->execute([$userId]);
$email = $stmt->fetchColumn();
if (!$email) {
Response::error('المستخدم غير موجود', 'NOT_FOUND', 404);
return;
}
Response::json([
'success' => true,
'data' => ['user_id' => $userId, 'email' => $email],
'message' => 'تم التحقق بنجاح'
]);
}
public function disable2FA(Request $request): void
{
$password = (string)$request->input('password', '');
if ($password === '') {
Response::error('كلمة المرور مطلوبة لتعطيل التحقق الثنائي', 'VALIDATION_ERROR', 422);
return;
}
$db = \App\Core\Database::getInstance();
$stmt = $db->prepare("SELECT password_hash FROM users WHERE id = ?");
$stmt->execute([$request->user->user_id]);
$hash = $stmt->fetchColumn();
if (!$hash || !password_verify($password, (string)$hash)) {
Response::error('كلمة المرور غير صحيحة', 'UNAUTHORIZED', 401);
return;
}
$db = \App\Core\Database::getInstance();
$stmt = $db->prepare("UPDATE users SET totp_secret = NULL, totp_enabled = 0 WHERE id = ?");
$stmt->execute([$request->user->user_id]);

View File

@@ -20,12 +20,17 @@ final class DashboardController
$params[] = $assignedCompanyId;
}
// Total this month
// Invoices this month
$stmt = $db->prepare("SELECT COUNT(*) FROM invoices i
WHERE i.tenant_id = ? {$companyScope} AND MONTH(i.created_at) = MONTH(CURDATE()) AND YEAR(i.created_at) = YEAR(CURDATE()) AND i.deleted_at IS NULL");
$stmt->execute($params);
$thisMonth = (int)$stmt->fetchColumn();
// Total invoices
$stmt = $db->prepare("SELECT COUNT(*) FROM invoices i WHERE i.tenant_id = ? {$companyScope} AND i.deleted_at IS NULL");
$stmt->execute($params);
$total = (int)$stmt->fetchColumn();
// Status distribution
$stmt = $db->prepare("SELECT status, COUNT(*) as count FROM invoices i
WHERE i.tenant_id = ? {$companyScope} AND i.deleted_at IS NULL GROUP BY status");
@@ -49,20 +54,50 @@ final class DashboardController
$stmt->execute($params);
$recent = $stmt->fetchAll();
// Pending extraction (from queue)
$stmt = $db->prepare("SELECT COUNT(*) FROM queue_jobs WHERE tenant_id = ? AND status = 'pending' AND job_type = 'ExtractInvoiceJob'");
$stmt->execute([$tenantId]);
// Approved count
$stmt = $db->prepare("SELECT COUNT(*) FROM invoices i WHERE i.tenant_id = ? {$companyScope} AND i.status = 'approved' AND i.deleted_at IS NULL");
$stmt->execute($params);
$approved = (int)$stmt->fetchColumn();
// Pending extraction (from invoices table)
$stmt = $db->prepare("SELECT COUNT(*) FROM invoices WHERE tenant_id = ? {$companyScope} AND status IN ('uploaded', 'extracting') AND deleted_at IS NULL");
$stmt->execute($params);
$pendingExtraction = (int)$stmt->fetchColumn();
// Unresolved risk alerts
$stmt = $db->prepare("SELECT COUNT(*) FROM risk_scores WHERE tenant_id = ? AND is_resolved = 0");
$stmt->execute([$tenantId]);
$riskCount = (int)$stmt->fetchColumn();
// Companies count
$stmt = $db->prepare("SELECT COUNT(*) FROM companies WHERE tenant_id = ? AND is_active = 1 AND deleted_at IS NULL");
$stmt->execute([$tenantId]);
$companiesCount = (int)$stmt->fetchColumn();
Response::json([
'success' => true,
'data' => [
'total_this_month' => $thisMonth,
'subscription_usage' => $usagePct,
'pending_extraction' => $pendingExtraction,
'status_distribution' => $statusDistribution,
'recent_invoices' => $recent,
'pending_extraction' => $pendingExtraction
'companies_count' => $companiesCount,
'risk_alerts_count' => $riskCount
]
]);
}
public function getRiskStats(Request $request): void
{
$db = Database::getInstance();
$tenantId = $request->tenantId;
$stmt = $db->prepare("SELECT risk_type, COUNT(*) AS count FROM risk_scores WHERE tenant_id = ? AND is_resolved = 0 GROUP BY risk_type");
$stmt->execute([$tenantId]);
Response::json([
'success' => true,
'data' => $stmt->fetchAll(),
]);
}
}

View File

@@ -78,7 +78,7 @@ final class InvoiceController
$invoiceId = \Ramsey\Uuid\Uuid::uuid4()->toString();
// Store file
$path = $this->storage->store($file, "invoices/{$request->tenantId}/{$invoiceId}");
$path = $this->storage->store($file, $request->tenantId, $companyId);
// Create record
$this->invoiceModel->create([

View File

@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Modules\Risks;
use App\Core\{Database, Request, Response};
final class RiskController
{
public function index(Request $request): void
{
$db = Database::getInstance();
$stmt = $db->prepare(
"SELECT r.*, c.name AS company_name, i.invoice_number
FROM risk_scores r
LEFT JOIN companies c ON c.id = r.company_id
LEFT JOIN invoices i ON i.id = r.invoice_id
WHERE r.tenant_id = ? AND r.is_resolved = 0
ORDER BY r.score ASC, r.created_at DESC"
);
$stmt->execute([$request->tenantId]);
Response::json([
'success' => true,
'data' => $stmt->fetchAll(),
]);
}
public function resolve(Request $request, string $id): void
{
$db = Database::getInstance();
$resolvedBy = $request->user->user_id ?? null;
$stmt = $db->prepare(
"UPDATE risk_scores
SET is_resolved = 1, resolved_by = ?, resolved_at = NOW()
WHERE id = ? AND tenant_id = ?"
);
$stmt->execute([$resolvedBy, $id, $request->tenantId]);
if ($stmt->rowCount() === 0) {
Response::error('تنبيه المخاطر غير موجود', 'NOT_FOUND', 404);
return;
}
Response::json([
'success' => true,
'message' => 'تم حل التنبيه بنجاح',
]);
}
}

View File

@@ -26,4 +26,18 @@ final class SubscriptionController
'data' => $subscription
]);
}
public function plans(): void
{
Response::json([
'success' => true,
'data' => [
['plan' => 'free', 'price_jod' => 0, 'max_companies' => 1, 'max_invoices' => 10, 'max_users' => 1],
['plan' => 'basic', 'price_jod' => 25, 'max_companies' => 3, 'max_invoices' => 50, 'max_users' => 2],
['plan' => 'office', 'price_jod' => 75, 'max_companies' => 10, 'max_invoices' => 200, 'max_users' => 5],
['plan' => 'pro', 'price_jod' => 150, 'max_companies' => 30, 'max_invoices' => 500, 'max_users' => 15],
['plan' => 'enterprise', 'price_jod' => 0, 'max_companies' => 999, 'max_invoices' => 9999, 'max_users' => 99],
],
]);
}
}