Update: 2026-05-03 22:51:59
This commit is contained in:
72
app/modules_app/invoices/upload.php
Normal file
72
app/modules_app/invoices/upload.php
Normal file
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
/**
|
||||
* Invoice Upload Endpoint (Multi-Tenant & Role-Aware)
|
||||
*/
|
||||
|
||||
use App\Core\Database;
|
||||
use App\Middleware\AuthMiddleware;
|
||||
|
||||
// 1. Auth Check
|
||||
$decoded = AuthMiddleware::check();
|
||||
$db = Database::getInstance();
|
||||
|
||||
$allowedRoles = ['admin', 'accountant', 'employee'];
|
||||
if (!in_array($decoded['role'], $allowedRoles)) {
|
||||
json_error('Unauthorized to upload invoices', 403);
|
||||
}
|
||||
|
||||
// 2. Validate Request
|
||||
$companyId = $_POST['company_id'] ?? null;
|
||||
if (!$companyId || !isset($_FILES['invoice'])) {
|
||||
json_error('Company ID and invoice file are required', 422);
|
||||
}
|
||||
|
||||
// 3. Permission Check (Can this user upload to this company?)
|
||||
$tenantId = $decoded['tenant_id'];
|
||||
$userId = $decoded['user_id'];
|
||||
|
||||
if ($decoded['role'] === 'admin') {
|
||||
$stmt = $db->prepare("SELECT id FROM companies WHERE id = ? AND tenant_id = ? AND deleted_at IS NULL");
|
||||
$stmt->execute([$companyId, $tenantId]);
|
||||
} elseif ($decoded['role'] === 'accountant') {
|
||||
$stmt = $db->prepare("
|
||||
SELECT c.id FROM companies c
|
||||
JOIN user_company_assignments uca ON c.id = uca.company_id
|
||||
WHERE c.id = ? AND uca.user_id = ? AND uca.is_active = 1
|
||||
");
|
||||
$stmt->execute([$companyId, $userId]);
|
||||
} else { // employee
|
||||
// In our schema, employee is linked via users.company_id
|
||||
$stmt = $db->prepare("SELECT id FROM users WHERE id = ? AND company_id = ?");
|
||||
$stmt->execute([$userId, $companyId]);
|
||||
}
|
||||
|
||||
if (!$stmt->fetch()) {
|
||||
json_error('Access denied to this company', 403);
|
||||
}
|
||||
|
||||
// 4. Handle File Upload (Mock logic for now, using storage/invoices)
|
||||
$uploadDir = __DIR__ . '/../../../storage/invoices/' . $tenantId . '/' . $companyId . '/';
|
||||
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
|
||||
|
||||
$fileName = time() . '_' . basename($_FILES['invoice']['name']);
|
||||
$targetFile = $uploadDir . $fileName;
|
||||
|
||||
if (move_uploaded_file($_FILES['invoice']['tmp_name'], $targetFile)) {
|
||||
// 5. Save to DB
|
||||
$stmt = $db->prepare("
|
||||
INSERT INTO invoices (
|
||||
tenant_id, company_id, status, uploaded_by, original_file_path, created_at
|
||||
) VALUES (?, ?, 'uploaded', ?, ?, NOW())
|
||||
");
|
||||
$stmt->execute([
|
||||
$tenantId,
|
||||
$companyId,
|
||||
$userId,
|
||||
$targetFile
|
||||
]);
|
||||
|
||||
json_success(['id' => $db->lastInsertId()], 'تم رفع الفاتورة بنجاح وبدأت عملية المعالجة');
|
||||
} else {
|
||||
json_error('Failed to save uploaded file', 500);
|
||||
}
|
||||
Reference in New Issue
Block a user