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

This commit is contained in:
Hamza-Ayed
2026-05-03 14:50:24 +03:00
parent fe075e64d1
commit 3aeb3220f1
9 changed files with 362 additions and 127 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Modules\Invoices\Actions;
use App\Core\Database;
use Exception;
final class DownloadInvoiceFileAction {
public function execute(string $invoiceId, string $tenantId, $user): array {
$db = Database::getInstance();
$stmt = $db->prepare("SELECT original_file_path, company_id FROM invoices WHERE id = ? AND tenant_id = ? AND deleted_at IS NULL LIMIT 1");
$stmt->execute([$invoiceId, $tenantId]);
$invoice = $stmt->fetch();
if (!$invoice || !file_exists($invoice['original_file_path'])) {
throw new Exception('الملف غير موجود', 404);
}
$role = $user->role ?? 'viewer';
if ($role !== 'super_admin' && $invoice['company_id'] !== ($user->assigned_company_id ?? null)) {
throw new Exception('غير مصرح لك بمشاهدة هذا الملف', 403);
}
return [
'path' => $invoice['original_file_path'],
'mime' => mime_content_type($invoice['original_file_path']),
'name' => basename($invoice['original_file_path'])
];
}
}

View File

@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Invoices\Actions;
use App\Core\Database;
use Exception;
final class GetInvoiceDetailAction {
public function execute(string $invoiceId, string $tenantId, $user): array {
$db = 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) {
throw new Exception('الفاتورة غير موجودة أو تم حذفها', 404);
}
$role = $user->role ?? 'viewer';
if ($role !== 'super_admin' && $invoice['company_id'] !== ($user->assigned_company_id ?? null)) {
throw new Exception('غير مصرح لك بالوصول لهذه الفاتورة', 403);
}
$stmt = $db->prepare("SELECT * FROM invoice_lines WHERE invoice_id = ? ORDER BY line_number ASC");
$stmt->execute([$invoiceId]);
$invoice['lines'] = $stmt->fetchAll() ?: [];
return $invoice;
}
}

View File

@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Invoices\Actions;
use App\Core\Database;
final class ListInvoicesAction {
public function execute(string $tenantId, $user): array {
$db = Database::getInstance();
$role = $user->role ?? 'viewer';
$assignedCompanyId = $user->assigned_company_id ?? null;
if ($role === 'super_admin' || $role === 'admin') {
$stmt = $db->prepare("SELECT i.*, c.name as company_name
FROM invoices i
JOIN companies c ON i.company_id = c.id
WHERE i.tenant_id = ? AND i.deleted_at IS NULL
ORDER BY i.created_at DESC");
$stmt->execute([$tenantId]);
} else {
$stmt = $db->prepare("SELECT i.*, c.name as company_name
FROM invoices i
JOIN companies c ON i.company_id = c.id
WHERE i.tenant_id = ? AND i.company_id = ? AND i.deleted_at IS NULL
ORDER BY i.created_at DESC");
$stmt->execute([$tenantId, $assignedCompanyId]);
}
return $stmt->fetchAll() ?: [];
}
}

View File

@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Invoices\Actions;
use App\Services\QueueService;
use App\Core\Database;
use Exception;
final class SubmitInvoiceAction {
public function execute(string $invoiceId, string $tenantId): void {
$db = Database::getInstance();
$stmt = $db->prepare("SELECT id FROM invoices WHERE id = ? AND tenant_id = ? AND deleted_at IS NULL LIMIT 1");
$stmt->execute([$invoiceId, $tenantId]);
if (!$stmt->fetch()) {
throw new Exception('الفاتورة غير موجودة', 404);
}
QueueService::push('submit_jofotara', [
'invoice_id' => $invoiceId
]);
}
}

View File

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Modules\Invoices\Actions;
use App\Services\FileStorageService;
use App\Modules\Invoices\InvoiceModel;
use App\Services\QueueService;
use Exception;
use Ramsey\Uuid\Uuid;
final class UploadInvoiceAction {
public function __construct(
private readonly FileStorageService $storage,
private readonly InvoiceModel $invoiceModel
) {}
public function execute(array $files, string $companyId, string $tenantId, $user): string {
if (empty($files['invoice'])) {
throw new Exception('يرجى اختيار ملف الفاتورة', 422);
}
if (!$companyId) {
throw new Exception('يرجى تحديد الشركة', 422);
}
$filePath = $this->storage->store($files['invoice'], $tenantId, $companyId);
$fileHash = $this->storage->getHash($filePath);
$invoiceId = Uuid::uuid4()->toString();
$this->invoiceModel->create([
'id' => $invoiceId,
'tenant_id' => $tenantId,
'company_id' => $companyId,
'uploaded_by' => $user->user_id ?? null,
'status' => 'uploaded',
'original_file_path' => $filePath,
'original_file_hash' => $fileHash,
'idempotency_key' => bin2hex(random_bytes(16))
]);
QueueService::push('invoice_extraction', [
'invoice_id' => $invoiceId,
'file_path' => $filePath,
'mime_type' => mime_content_type($filePath)
]);
return $invoiceId;
}
}

View File

@@ -6,164 +6,90 @@ namespace App\Modules\Invoices;
use App\Core\{Request, Response}; use App\Core\{Request, Response};
use App\Services\FileStorageService; use App\Services\FileStorageService;
use App\Services\AiExtractionService;
use App\Modules\Invoices\InvoiceModel; use App\Modules\Invoices\InvoiceModel;
use App\Modules\Invoices\Actions\{
ListInvoicesAction,
UploadInvoiceAction,
GetInvoiceDetailAction,
SubmitInvoiceAction,
DownloadInvoiceFileAction
};
use Throwable; use Throwable;
final class InvoiceController final class InvoiceController
{ {
public function __construct( public function __construct(
private readonly InvoiceModel $invoiceModel, private readonly InvoiceModel $invoiceModel,
private readonly FileStorageService $storage, private readonly FileStorageService $storage
private readonly AiExtractionService $aiExtraction
) {} ) {}
public function list(Request $request): void public function list(Request $request): void
{ {
$tenantId = $request->tenantId; try {
$role = $request->user->role ?? 'viewer'; $action = new ListInvoicesAction();
$assignedCompanyId = $request->user->assigned_company_id ?? null; $invoices = $action->execute($request->tenantId, $request->user);
Response::json(['success' => true, 'data' => $invoices]);
$db = \App\Core\Database::getInstance(); } catch (Throwable $e) {
if ($role === 'super_admin' || $role === 'admin') { Response::error($e->getMessage(), 'LIST_ERROR', (int)($e->getCode() ?: 500));
$stmt = $db->prepare("SELECT i.*, c.name as company_name FROM invoices i JOIN companies c ON i.company_id = c.id WHERE i.tenant_id = ? AND i.deleted_at IS NULL ORDER BY i.created_at DESC");
$stmt->execute([$tenantId]);
$invoices = $stmt->fetchAll();
} else {
$stmt = $db->prepare("SELECT i.*, c.name as company_name FROM invoices i JOIN companies c ON i.company_id = c.id WHERE i.tenant_id = ? AND i.company_id = ? AND i.deleted_at IS NULL ORDER BY i.created_at DESC");
$stmt->execute([$tenantId, $assignedCompanyId]);
$invoices = $stmt->fetchAll();
} }
Response::json([
'success' => true,
'data' => $invoices
]);
} }
public function upload(Request $request): void public function upload(Request $request): void
{ {
$files = $request->getFiles();
if (empty($files['invoice'])) {
Response::error('يرجى اختيار ملف الفاتورة', 'MISSING_FILE', 422);
return;
}
$companyId = $request->input('company_id');
if (!$companyId) {
Response::error('يرجى تحديد الشركة', 'MISSING_COMPANY', 422);
return;
}
try { try {
$tenantId = $request->tenantId; $action = new UploadInvoiceAction($this->storage, $this->invoiceModel);
$filePath = $this->storage->store($files['invoice'], $tenantId, $companyId); $invoiceId = $action->execute(
$fileHash = $this->storage->getHash($filePath); $request->getFiles(),
(string)$request->input('company_id'),
// Create invoice record $request->tenantId,
$invoiceId = \Ramsey\Uuid\Uuid::uuid4()->toString(); $request->user
$this->invoiceModel->create([ );
'id' => $invoiceId,
'tenant_id' => $tenantId,
'company_id' => $companyId,
'uploaded_by' => $request->user->user_id,
'status' => 'uploaded', // Match schema ENUM
'original_file_path' => $filePath,
'original_file_hash' => $fileHash,
'idempotency_key' => bin2hex(random_bytes(16))
]);
// Push to Queue for AI Extraction
\App\Services\QueueService::push('invoice_extraction', [
'invoice_id' => $invoiceId,
'file_path' => $filePath,
'mime_type' => mime_content_type($filePath)
]);
Response::json([ Response::json([
'success' => true, 'success' => true,
'data' => ['invoice_id' => $invoiceId], 'data' => ['invoice_id' => $invoiceId],
'message' => 'تم رفع الفاتورة بنجاح وجاري استخراج البيانات بالذكاء الاصطناعي' 'message' => 'تم رفع الفاتورة بنجاح وجاري استخراج البيانات بالذكاء الاصطناعي'
], 202); ], 202);
} catch (Throwable $e) { } catch (Throwable $e) {
Response::error($e->getMessage(), 'UPLOAD_FAILED', 500); Response::error($e->getMessage(), 'UPLOAD_ERROR', (int)($e->getCode() ?: 500));
} }
} }
public function detail(Request $request, string $id): void public function detail(Request $request, string $id): void
{ {
$tenantId = $request->tenantId; try {
$invoiceId = $id; $action = new GetInvoiceDetailAction();
$invoice = $action->execute($id, $request->tenantId, $request->user);
$db = \App\Core\Database::getInstance(); Response::json(['success' => true, 'data' => $invoice]);
$stmt = $db->prepare("SELECT * FROM invoices WHERE id = ? AND tenant_id = ? AND deleted_at IS NULL LIMIT 1"); } catch (Throwable $e) {
$stmt->execute([$invoiceId, $tenantId]); Response::error($e->getMessage(), 'DETAIL_ERROR', (int)($e->getCode() ?: 500));
$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, string $id): void public function submit(Request $request, string $id): void
{ {
$tenantId = $request->tenantId; try {
$invoiceId = $id; $action = new SubmitInvoiceAction();
$action->execute($id, $request->tenantId);
Response::json(['success' => true, 'message' => 'Invoice submission queued.']);
} catch (Throwable $e) {
Response::error($e->getMessage(), 'SUBMIT_ERROR', (int)($e->getCode() ?: 500));
}
}
// Push to Queue for JoFotara Submission
\App\Services\QueueService::push('submit_jofotara', [
'invoice_id' => $invoiceId
]);
Response::json([
'success' => true,
'message' => 'Invoice submission queued.'
]);
public function downloadFile(Request $request, string $id): void public function downloadFile(Request $request, string $id): void
{ {
$tenantId = $request->tenantId; try {
$db = \App\Core\Database::getInstance(); $action = new DownloadInvoiceFileAction();
$stmt = $db->prepare("SELECT original_file_path, company_id FROM invoices WHERE id = ? AND tenant_id = ? AND deleted_at IS NULL LIMIT 1"); $file = $action->execute($id, $request->tenantId, $request->user);
$stmt->execute([$id, $tenantId]);
$invoice = $stmt->fetch();
if (!$invoice || !file_exists($invoice['original_file_path'])) { header("Content-Type: {$file['mime']}");
Response::error('الملف غير موجود', 'NOT_FOUND', 404); header("Content-Disposition: inline; filename=\"{$file['name']}\"");
return; header("Content-Length: " . filesize($file['path']));
readfile($file['path']);
exit;
} catch (Throwable $e) {
Response::error($e->getMessage(), 'DOWNLOAD_ERROR', (int)($e->getCode() ?: 500));
} }
$role = $request->user->role ?? 'viewer';
if ($role !== 'super_admin' && $invoice['company_id'] !== $request->user->assigned_company_id) {
Response::error('غير مصرح لك بمشاهدة هذا الملف', 'FORBIDDEN', 403);
return;
}
$path = $invoice['original_file_path'];
$mime = mime_content_type($path);
header("Content-Type: $mime");
header("Content-Disposition: inline; filename=\"" . basename($path) . "\"");
header("Content-Length: " . filesize($path));
readfile($path);
exit;
} }
} }

View File

@@ -80,6 +80,14 @@
<!-- Toast & Modals --> <!-- Toast & Modals -->
<div id="toast-container" class="fixed top-8 left-1/2 -translate-x-1/2 z-[200] space-y-4"></div> <div id="toast-container" class="fixed top-8 left-1/2 -translate-x-1/2 z-[200] space-y-4"></div>
<div id="modals" class="fixed inset-0 z-[150] hidden items-center justify-center p-6 bg-black/80 backdrop-blur-md"></div> <div id="modals" class="fixed inset-0 z-[150] hidden items-center justify-center p-6 bg-black/80 backdrop-blur-md"></div>
<!-- Global Loader -->
<div id="global-loader" class="fixed inset-0 z-[250] hidden items-center justify-center bg-black/40 backdrop-blur-sm">
<div class="flex flex-col items-center gap-4">
<div class="w-16 h-16 border-4 border-primary border-t-transparent rounded-full animate-spin shadow-[0_0_30px_var(--primary-glow)]"></div>
<p class="text-white font-bold animate-pulse">جاري المعالجة...</p>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script> <script>
@@ -87,13 +95,28 @@
baseUrl: 'index.php?route=/api/v1', baseUrl: 'index.php?route=/api/v1',
get token() { return localStorage.getItem('access_token'); }, get token() { return localStorage.getItem('access_token'); },
async req(method, path, body = null, files = false) { async req(method, path, body = null, files = false) {
const headers = { 'Accept': 'application/json' }; const loader = document.getElementById('global-loader');
if (this.token) headers['Authorization'] = `Bearer ${this.token}`; if (loader) loader.classList.replace('hidden', 'flex');
if (!files && body) { headers['Content-Type'] = 'application/json'; body = JSON.stringify(body); }
const res = await fetch(`${this.baseUrl}${path}`, { method, headers, body }); try {
const data = await res.json(); const headers = { 'Accept': 'application/json' };
if (!res.ok) { if (res.status === 401) logout(); throw data; } if (this.token) headers['Authorization'] = `Bearer ${this.token}`;
return data; if (!files && body) { headers['Content-Type'] = 'application/json'; body = JSON.stringify(body); }
const res = await fetch(`${this.baseUrl}${path}`, { method, headers, body });
const data = await res.json();
if (!res.ok) {
if (res.status === 401) logout();
throw data;
}
return data;
} catch (err) {
showToast(err.error?.message || 'حدث خطأ غير متوقع في النظام', 'error');
throw err;
} finally {
if (loader) loader.classList.replace('flex', 'hidden');
}
}, },
get(p) { return this.req('GET', p); }, get(p) { return this.req('GET', p); },
post(p, b) { return this.req('POST', p, b); }, post(p, b) { return this.req('POST', p, b); },

View File

@@ -0,0 +1,122 @@
# مُصادَق — ملخص كود المشروع الكامل
هذا الملف يحتوي على كافة ملفات المصدر للمشروع مجمعة لتسهيل المراجعة.
## الملف: `migrate.php`
```php
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../app/Core/helpers.php';
use App\Core\{Application, Database};
// Initialize app to load .env and configs
$app = new Application(dirname(__DIR__));
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "🗄️ Musadaq Migration Tool\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
try {
$db = Database::getInstance();
// Create migrations table if not exists
$db->exec("CREATE TABLE IF NOT EXISTS migrations (
id INT AUTO_INCREMENT PRIMARY KEY,
migration VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
$stmt = $db->query("SELECT migration FROM migrations");
$executed = $stmt->fetchAll(PDO::FETCH_COLUMN);
$migrationsDir = dirname(__DIR__) . '/database/migrations';
$files = glob($migrationsDir . '/*.sql');
sort($files); // Ensure order
$count = 0;
foreach ($files as $file) {
$name = basename($file);
if (!in_array($name, $executed)) {
echo "🚀 Running: $name... ";
$sql = file_get_contents($file);
// Execute the SQL. Since it might contain multiple statements,
// and PDO::exec doesn't always handle them well in one go
// depending on the driver, we'll try to run it.
$db->exec($sql);
$stmt = $db->prepare("INSERT INTO migrations (migration) VALUES (?)");
$stmt->execute([$name]);
echo "✅ Done\n";
$count++;
}
}
if ($count === 0) {
echo "✨ Nothing to migrate. Database is up to date.\n";
} else {
echo "🎉 Migrations completed successfully ($count ran).\n";
}
} catch (Exception $e) {
echo "❌ Error: " . $e->getMessage() . "\n";
exit(1);
}
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
```
---
## الملف: `seed.php`
```php
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
use App\Core\{Application, Database};
use Ramsey\Uuid\Uuid;
$app = new Application(dirname(__DIR__));
$db = Database::getInstance();
echo "🌱 Seeding initial data...\n";
try {
// 1. Create Tenant
$tenantId = Uuid::uuid4()->toString();
$db->prepare("INSERT INTO tenants (id, name, email, status) VALUES (?, ?, ?, 'active')")
->execute([$tenantId, 'شركة انطلاق للحلول الرقمية', 'admin@intaleqapp.com']);
// 2. Create Super Admin User
$userId = Uuid::uuid4()->toString();
$passwordHash = password_hash('Musadaq@2026', PASSWORD_ARGON2ID);
$db->prepare("INSERT INTO users (id, tenant_id, name, email, password_hash, role, is_active) VALUES (?, ?, ?, ?, ?, 'super_admin', 1)")
->execute([$userId, $tenantId, 'Hamza Admin', 'admin@musadaq.app', $passwordHash]);
// 3. Create initial subscription
$db->prepare("INSERT INTO subscriptions (tenant_id, plan, max_companies, max_invoices_per_month, max_users) VALUES (?, 'pro', 10, 500, 5)")
->execute([$tenantId]);
echo "✅ Success! You can now log in with:\n";
echo "📧 Email: admin@musadaq.app\n";
echo "🔑 Password: Musadaq@2026\n";
} catch (\Throwable $e) {
echo "❌ Error: " . $e->getMessage() . "\n";
}
```
---