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

This commit is contained in:
Hamza-Ayed
2026-05-03 13:39:05 +03:00
parent 2de6a0adfd
commit ea415e3a11
19 changed files with 972 additions and 7 deletions

View File

@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Modules\Admin;
use App\Core\{Request, Response, Database};
final class AdminController
{
public function getSystemStats(Request $request): void
{
// Must be super_admin
if (($request->user->role ?? '') !== 'super_admin') {
Response::error('غير مصرح', 'FORBIDDEN', 403);
return;
}
$db = Database::getInstance();
$stmt = $db->prepare("SELECT COUNT(*) as count FROM tenants");
$stmt->execute();
$totalTenants = $stmt->fetch()['count'];
$stmt = $db->prepare("SELECT COUNT(*) as count FROM invoices");
$stmt->execute();
$totalInvoices = $stmt->fetch()['count'];
// Simple Health Check
$redisHealth = 'ok';
try {
$redis = \App\Core\Redis::getInstance();
$redis->ping();
} catch (\Throwable $e) {
$redisHealth = 'failed';
}
Response::json([
'success' => true,
'data' => [
'total_tenants' => $totalTenants,
'total_invoices' => $totalInvoices,
'system_health' => [
'database' => 'ok',
'redis' => $redisHealth
]
]
]);
}
}

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace App\Modules\ApiKeys;
use App\Core\{Request, Response};
use App\Modules\ApiKeys\ApiKeyModel;
final class ApiKeyController
{
public function __construct(private readonly ApiKeyModel $apiKeyModel) {}
public function list(Request $request): void
{
$tenantId = $request->tenantId;
$keys = $this->apiKeyModel->findAllByTenant($tenantId);
Response::json([
'success' => true,
'data' => $keys
]);
}
public function create(Request $request): void
{
$tenantId = $request->tenantId;
$data = $request->getBody();
if (empty($data['name'])) {
Response::error('اسم المفتاح مطلوب', 'VALIDATION_ERROR', 422);
return;
}
$id = \Ramsey\Uuid\Uuid::uuid4()->toString();
// Generate a random key
$rawKey = bin2hex(random_bytes(32));
$prefix = substr($rawKey, 0, 8);
$hashedKey = hash('sha256', $rawKey);
$this->apiKeyModel->create([
'id' => $id,
'tenant_id' => $tenantId,
'name' => $data['name'],
'key_hash' => $hashedKey,
'prefix' => $prefix,
'is_active' => 1
]);
Response::json([
'success' => true,
'message' => 'تم إنشاء مفتاح API بنجاح',
'data' => [
'id' => $id,
'name' => $data['name'],
'key' => $rawKey // Only shown once!
]
], 201);
}
}

View File

@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\ApiKeys;
use App\Models\BaseModel;
final class ApiKeyModel extends BaseModel
{
protected string $table = 'api_keys';
public function findAllByTenant(string $tenantId): array
{
$stmt = $this->db()->prepare("SELECT id, name, prefix, expires_at, last_used_at, is_active, created_at FROM {$this->table} WHERE tenant_id = ? AND deleted_at IS NULL");
$stmt->execute([$tenantId]);
return $stmt->fetchAll();
}
}

View File

@@ -25,6 +25,16 @@ final class AuthController
try {
$result = $this->authService->login($email, $password);
// 2FA Check
if ($result['user']->totp_enabled) {
Response::json([
'success' => true,
'requires_2fa' => true,
'temp_token' => $result['access_token']
]);
return;
}
// Set refresh token in HttpOnly cookie
setcookie('refresh_token', $result['refresh_token'], [
'expires' => time() + (60 * 60 * 24 * 7),
@@ -128,4 +138,47 @@ final class AuthController
Response::error($e->getMessage(), 'REGISTRATION_FAILED', 400);
}
}
public function enable2FA(Request $request): void
{
$user = $request->user;
$totpService = new \App\Services\TotpService();
$secret = $totpService->generateSecret();
$qrUrl = $totpService->getQrCodeUrl($user->email, $secret);
Response::json([
'success' => true,
'data' => [
'secret' => $secret,
'qr_url' => $qrUrl
]
]);
}
public function verify2FA(Request $request): void
{
$data = $request->getBody();
$code = $data['code'] ?? '';
$secret = $data['secret'] ?? '';
$totpService = new \App\Services\TotpService();
if ($totpService->verify($secret, $code)) {
$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]);
Response::json(['success' => true, 'message' => 'تم تفعيل التحقق الثنائي بنجاح']);
} else {
Response::error('رمز التحقق غير صحيح', 'INVALID_CODE', 400);
}
}
public function disable2FA(Request $request): void
{
$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]);
Response::json(['success' => true, 'message' => 'تم تعطيل التحقق الثنائي']);
}
}

View File

@@ -89,4 +89,53 @@ final class InvoiceController
Response::error($e->getMessage(), 'UPLOAD_FAILED', 500);
}
}
public function detail(Request $request, array $vars): void
{
$tenantId = $request->tenantId;
$invoiceId = $vars['id'] ?? null;
$db = \App\Core\Database::getInstance();
$stmt = $db->prepare("SELECT * FROM invoices WHERE id = ? AND tenant_id = ? AND deleted_at IS NULL LIMIT 1");
$stmt->execute([$invoiceId, $tenantId]);
$invoice = $stmt->fetch();
if (!$invoice) {
Response::error('الفاتورة غير موجودة', 'NOT_FOUND', 404);
return;
}
// Additional authorization check based on assigned company if needed
$role = $request->user->role ?? 'viewer';
if ($role !== 'super_admin' && $invoice['company_id'] !== $request->user->assigned_company_id) {
Response::error('غير مصرح لك بمشاهدة هذه الفاتورة', 'FORBIDDEN', 403);
return;
}
// Fetch lines
$stmt = $db->prepare("SELECT * FROM invoice_lines WHERE invoice_id = ? ORDER BY id ASC");
$stmt->execute([$invoiceId]);
$invoice['lines'] = $stmt->fetchAll();
Response::json([
'success' => true,
'data' => $invoice
]);
}
public function submit(Request $request, array $vars): void
{
$tenantId = $request->tenantId;
$invoiceId = $vars['id'];
// Push to Queue for JoFotara Submission
\App\Services\QueueService::push('submit_jofotara', [
'invoice_id' => $invoiceId
]);
Response::json([
'success' => true,
'message' => 'Invoice submission queued.'
]);
}
}

View File

@@ -38,5 +38,38 @@ final class UserController
'success' => true,
'data' => $user
]);
public function create(Request $request): void
{
$tenantId = $request->tenantId;
$data = $request->getBody();
if (empty($data['email']) || empty($data['password']) || empty($data['name']) || empty($data['role'])) {
Response::error('جميع الحقول مطلوبة', 'VALIDATION_ERROR', 422);
return;
}
if ($this->userModel->findByEmail($data['email'])) {
Response::error('البريد الإلكتروني مستخدم مسبقاً', 'DUPLICATE_EMAIL', 409);
return;
}
$userId = \Ramsey\Uuid\Uuid::uuid4()->toString();
$this->userModel->create([
'id' => $userId,
'tenant_id' => $tenantId,
'name' => $data['name'],
'email' => $data['email'],
'password_hash' => password_hash($data['password'], PASSWORD_ARGON2ID),
'role' => $data['role'],
'assigned_company_id' => $data['assigned_company_id'] ?? null,
'is_active' => 1
]);
Response::json([
'success' => true,
'message' => 'تم إضافة المستخدم بنجاح',
'data' => ['id' => $userId]
], 201);
}
}

View File

@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace App\Services\AI;
use App\Services\AI\Contracts\AIProviderInterface;
use Exception;
final class OpenAIProvider implements AIProviderInterface
{
private string $apiKey;
private string $model;
public function __construct()
{
$this->apiKey = $_ENV['OPENAI_API_KEY'] ?? '';
$this->model = $_ENV['OPENAI_MODEL'] ?? 'gpt-4o-mini';
}
public function isConfigured(): bool
{
return !empty($this->apiKey);
}
public function extractInvoiceData(string $fileContent, string $mimeType, string $prompt): array
{
if (!$this->isConfigured()) {
throw new Exception("OpenAI API Key is missing. Please configure it in .env");
}
$base64Data = base64_encode($fileContent);
$payload = [
'model' => $this->model,
'messages' => [
[
'role' => 'user',
'content' => [
[
'type' => 'text',
'text' => $prompt
],
[
'type' => 'image_url',
'image_url' => [
'url' => "data:{$mimeType};base64,{$base64Data}"
]
]
]
]
],
'response_format' => ['type' => 'json_object'],
'temperature' => 0.1
];
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"Authorization: Bearer {$this->apiKey}"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("OpenAI Extraction failed. HTTP Code: {$httpCode}. Response: {$response}");
}
$result = json_decode($response, true);
$text = $result['choices'][0]['message']['content'] ?? '{}';
$data = json_decode($text, true);
if (!is_array($data)) {
throw new Exception("Failed to parse OpenAI output as JSON: {$text}");
}
return $data;
}
}

View File

@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Core\Database;
final class RiskAnalysisService
{
public function calculateCompanyRiskScore(string $companyId): array
{
$db = Database::getInstance();
$score = 100;
$factors = [];
// 1. Rejection Rate
$stmt = $db->prepare("SELECT status, COUNT(*) as count FROM invoices WHERE company_id = ? GROUP BY status");
$stmt->execute([$companyId]);
$stats = $stmt->fetchAll();
$total = 0;
$rejected = 0;
foreach ($stats as $stat) {
$total += $stat['count'];
if ($stat['status'] === 'rejected' || $stat['status'] === 'validation_failed') {
$rejected += $stat['count'];
}
}
if ($total > 0) {
$rejectionRate = $rejected / $total;
if ($rejectionRate > 0.10) { // More than 10% rejections
$penalty = min(30, (int)(($rejectionRate - 0.10) * 100));
$score -= $penalty;
$factors[] = "نسبة رفض عالية: " . round($rejectionRate * 100, 1) . "% (خصم {$penalty} نقطة)";
}
}
// 2. High Value Cash Invoices
$stmt = $db->prepare("SELECT COUNT(*) as count FROM invoices WHERE company_id = ? AND invoice_type = 'cash' AND grand_total > 5000");
$stmt->execute([$companyId]);
$highValueCash = $stmt->fetch()['count'];
if ($highValueCash > 0) {
$penalty = min(20, $highValueCash * 2);
$score -= $penalty;
$factors[] = "وجود فواتير نقدية بقيم عالية: {$highValueCash} فاتورة (خصم {$penalty} نقطة)";
}
// 3. Late submissions (invoice_date is much older than created_at)
$stmt = $db->prepare("SELECT COUNT(*) as count FROM invoices WHERE company_id = ? AND DATEDIFF(created_at, invoice_date) > 7");
$stmt->execute([$companyId]);
$lateInvoices = $stmt->fetch()['count'];
if ($lateInvoices > 0) {
$penalty = min(15, $lateInvoices * 1);
$score -= $penalty;
$factors[] = "تأخير في رفع الفواتير: {$lateInvoices} فاتورة متأخرة بأكثر من 7 أيام (خصم {$penalty} نقطة)";
}
// Determine Risk Level
$riskLevel = 'low';
if ($score < 50) {
$riskLevel = 'high';
} elseif ($score < 80) {
$riskLevel = 'medium';
}
return [
'score' => max(0, $score),
'level' => $riskLevel,
'factors' => $factors,
'calculated_at' => date('Y-m-d H:i:s')
];
}
}

View File

@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace App\Services;
final class TotpService
{
private const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
public function generateSecret(): string
{
$secret = '';
for ($i = 0; $i < 16; $i++) {
$secret .= self::ALPHABET[random_int(0, 31)];
}
return $secret;
}
public function verify(string $secret, string $code): bool
{
$currentTime = floor(time() / 30);
// Check current, previous and next window (allow 30s clock drift)
for ($i = -1; $i <= 1; $i++) {
if ($this->calculateCode($secret, (int)($currentTime + $i)) === $code) {
return true;
}
}
return false;
}
private function calculateCode(string $secret, int $time): string
{
$key = $this->base32Decode($secret);
$timeHex = str_pad(dechex($time), 16, '0', STR_PAD_LEFT);
$timeBin = pack('H*', $timeHex);
$hash = hash_hmac('sha1', $timeBin, $key, true);
$offset = ord($hash[19]) & 0xf;
$otp = (
((ord($hash[$offset]) & 0x7f) << 24) |
((ord($hash[$offset + 1]) & 0xff) << 16) |
((ord($hash[$offset + 2]) & 0xff) << 8) |
(ord($hash[$offset + 3]) & 0xff)
) % 1000000;
return str_pad((string)$otp, 6, '0', STR_PAD_LEFT);
}
private function base32Decode(string $base32): string
{
$base32 = strtoupper($base32);
$buffer = 0;
$bufferSize = 0;
$decoded = '';
for ($i = 0; $i < strlen($base32); $i++) {
$char = $base32[$i];
$pos = strpos(self::ALPHABET, $char);
if ($pos === false) continue;
$buffer = ($buffer << 5) | $pos;
$bufferSize += 5;
if ($bufferSize >= 8) {
$bufferSize -= 8;
$decoded .= chr(($buffer >> $bufferSize) & 0xff);
}
}
return $decoded;
}
public function getQrCodeUrl(string $userEmail, string $secret, string $issuer = 'Musadaq'): string
{
$label = urlencode($issuer . ':' . $userEmail);
$otpauth = "otpauth://totp/{$label}?secret={$secret}&issuer=" . urlencode($issuer);
return "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" . urlencode($otpauth);
}
}