78 lines
2.7 KiB
PHP
78 lines
2.7 KiB
PHP
<?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')
|
|
];
|
|
}
|
|
}
|