| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239 |
- <?php
- /**
- * API Calculs - encours par client, encours total, échéances (FR6, FR7, FR8).
- * GET ?client_id= pour un client, sinon agrégé global.
- */
- require_once __DIR__ . '/config.php';
- header('Access-Control-Allow-Origin: *');
- header('Access-Control-Allow-Methods: GET');
- $method = $_SERVER['REQUEST_METHOD'] ?? '';
- if ($method !== 'GET') {
- sendError('Méthode non autorisée', 405);
- exit;
- }
- $clientId = isset($_GET['client_id']) ? (int) $_GET['client_id'] : null;
- if (isMockMode()) {
- $clients = loadMock('clients');
- $factures = loadMock('factures');
- $paiements = loadMock('paiements');
- $encoursByClient = [];
- foreach ($clients as $c) {
- $cid = (int) $c['id'];
- $totalFactures = 0;
- $totalPaye = 0;
- foreach ($factures as $f) {
- if ((int) $f['client_id'] === $cid) {
- $totalFactures += (float) $f['montant_ht'];
- foreach ($paiements as $p) {
- if ((int) $p['facture_id'] === (int) $f['id']) {
- $totalPaye += (float) $p['montant'];
- }
- }
- }
- }
- $encours = max(0, $totalFactures - $totalPaye);
- $encoursByClient[$cid] = ['client_id' => $cid, 'nom' => $c['nom'], 'encours' => $encours];
- }
- if ($clientId !== null && $clientId > 0) {
- if (!isset($encoursByClient[$clientId])) {
- sendError('Client non trouvé', 404);
- exit;
- }
- sendJson($encoursByClient[$clientId]);
- exit;
- }
- $parClient = array_values(array_filter($encoursByClient, fn($r) => $r['encours'] > 0));
- usort($parClient, fn($a, $b) => $b['encours'] <=> $a['encours']);
- $encoursTotal = array_sum(array_column($parClient, 'encours'));
-
- // Charger les écheanciers pour calculer les dates d'échéances réelles
- $echeanciers = loadMock('echeanciers');
- $echeancierByFacture = [];
- foreach ($echeanciers as $ech) {
- $echeancierByFacture[(int) $ech['facture_id']] = $ech;
- }
-
- $echeances = [];
- foreach ($factures as $f) {
- $totalPaye = 0;
- foreach ($paiements as $p) {
- if ((int) $p['facture_id'] === (int) $f['id']) $totalPaye += (float) $p['montant'];
- }
- $encoursF = max(0, (float) $f['montant_ht'] - $totalPaye);
- if ($encoursF > 0) {
- $nom = '';
- foreach ($clients as $c) {
- if ((int) $c['id'] === (int) $f['client_id']) { $nom = $c['nom']; break; }
- }
- $factureId = (int) $f['id'];
-
- // Si la facture a un écheancier, calculer les dates d'échéances réelles
- if (isset($echeancierByFacture[$factureId])) {
- $ech = $echeancierByFacture[$factureId];
- $dateDebut = new DateTime($ech['date_debut_echeancier']);
- $nbEcheances = (int) $ech['nb_echeances'];
- $montantParEch = isset($ech['montant_par_echeance']) ? (float) $ech['montant_par_echeance'] : ($nbEcheances > 0 ? $encoursF / $nbEcheances : 0);
-
- // Créer une échéance pour chaque date prévue
- for ($i = 0; $i < $nbEcheances; $i++) {
- $dateEcheance = clone $dateDebut;
- $dateEcheance->modify("+{$i} months");
- $echeances[] = [
- 'facture_id' => $factureId,
- 'client_id' => (int) $f['client_id'],
- 'nom' => $nom,
- 'n_facture' => $f['n_facture'],
- 'date_echeance' => $dateEcheance->format('Y-m-d'),
- 'montant_echeance' => $montantParEch,
- 'encours_facture' => $encoursF,
- 'echeance_num' => $i + 1,
- 'echeance_total' => $nbEcheances,
- ];
- }
- } else {
- // Pas d'écheancier : utiliser la date de facture
- $echeances[] = [
- 'facture_id' => $factureId,
- 'client_id' => (int) $f['client_id'],
- 'nom' => $nom,
- 'n_facture' => $f['n_facture'],
- 'date_echeance' => $f['date_facture'],
- 'montant_echeance' => $encoursF,
- 'encours_facture' => $encoursF,
- 'echeance_num' => null,
- 'echeance_total' => null,
- ];
- }
- }
- }
- usort($echeances, fn($a, $b) => strcmp($a['date_echeance'], $b['date_echeance']));
-
- // Filtrer pour ne garder que les échéances à venir (date >= aujourd'hui)
- $aujourdhui = date('Y-m-d');
- $echeances = array_filter($echeances, fn($e) => $e['date_echeance'] >= $aujourdhui);
- $echeances = array_values($echeances);
-
- sendJson([
- 'encours_total' => $encoursTotal,
- 'encours_par_client' => $parClient,
- 'echeances_a_venir' => $echeances,
- ]);
- exit;
- }
- $pdo = getPdo();
- if ($clientId !== null && $clientId > 0) {
- $stmt = $pdo->prepare("
- SELECT c.id AS client_id, c.nom,
- GREATEST(0, COALESCE(SUM(f.montant_ht), 0) - COALESCE(SUM(p.montant), 0)) AS encours
- FROM clients c
- LEFT JOIN factures f ON f.client_id = c.id
- LEFT JOIN paiements p ON p.facture_id = f.id
- WHERE c.id = ?
- GROUP BY c.id, c.nom
- ");
- $stmt->execute([$clientId]);
- $row = $stmt->fetch();
- if (!$row) {
- sendError('Client non trouvé', 404);
- exit;
- }
- sendJson([
- 'client_id' => (int) $row['client_id'],
- 'nom' => $row['nom'],
- 'encours' => (float) $row['encours'],
- ]);
- exit;
- }
- $stmt = $pdo->query("
- SELECT c.id AS client_id, c.nom,
- GREATEST(0, COALESCE(SUM(f.montant_ht), 0) - COALESCE(SUM(p.montant), 0)) AS encours
- FROM clients c
- LEFT JOIN factures f ON f.client_id = c.id
- LEFT JOIN paiements p ON p.facture_id = f.id
- GROUP BY c.id, c.nom
- HAVING encours > 0
- ORDER BY encours ASC
- ");
- $parClient = $stmt->fetchAll();
- $encoursTotal = 0;
- foreach ($parClient as &$r) {
- $r['encours'] = (float) $r['encours'];
- $encoursTotal += $r['encours'];
- }
- // Récupérer les factures avec encours et leurs écheanciers
- $stmt = $pdo->query("
- SELECT f.id AS facture_id, f.client_id, c.nom, f.n_facture, f.date_facture, f.montant_ht,
- COALESCE(SUM(p.montant), 0) AS total_paye,
- GREATEST(0, f.montant_ht - COALESCE(SUM(p.montant), 0)) AS encours_facture,
- e.id AS echeancier_id, e.nb_echeances, e.date_debut_echeancier, e.montant_par_echeance
- FROM factures f
- JOIN clients c ON c.id = f.client_id
- LEFT JOIN paiements p ON p.facture_id = f.id
- LEFT JOIN echeanciers e ON e.facture_id = f.id
- GROUP BY f.id, f.client_id, c.nom, f.n_facture, f.date_facture, f.montant_ht, e.id, e.nb_echeances, e.date_debut_echeancier, e.montant_par_echeance
- HAVING encours_facture > 0
- ORDER BY f.date_facture ASC
- ");
- $facturesAvecEncours = $stmt->fetchAll();
- $echeances = [];
- foreach ($facturesAvecEncours as $f) {
- $encoursF = (float) $f['encours_facture'];
- $factureId = (int) $f['facture_id'];
-
- // Si la facture a un écheancier, calculer les dates d'échéances réelles
- if ($f['echeancier_id'] !== null && $f['date_debut_echeancier'] !== null) {
- $dateDebut = new DateTime($f['date_debut_echeancier']);
- $nbEcheances = (int) $f['nb_echeances'];
- $montantParEch = $f['montant_par_echeance'] !== null ? (float) $f['montant_par_echeance'] : ($nbEcheances > 0 ? $encoursF / $nbEcheances : 0);
-
- // Créer une échéance pour chaque date prévue
- for ($i = 0; $i < $nbEcheances; $i++) {
- $dateEcheance = clone $dateDebut;
- $dateEcheance->modify("+{$i} months");
- $echeances[] = [
- 'facture_id' => $factureId,
- 'client_id' => (int) $f['client_id'],
- 'nom' => $f['nom'],
- 'n_facture' => $f['n_facture'],
- 'date_echeance' => $dateEcheance->format('Y-m-d'),
- 'montant_echeance' => $montantParEch,
- 'encours_facture' => $encoursF,
- 'echeance_num' => $i + 1,
- 'echeance_total' => $nbEcheances,
- ];
- }
- } else {
- // Pas d'écheancier : utiliser la date de facture
- $echeances[] = [
- 'facture_id' => $factureId,
- 'client_id' => (int) $f['client_id'],
- 'nom' => $f['nom'],
- 'n_facture' => $f['n_facture'],
- 'date_echeance' => $f['date_facture'],
- 'montant_echeance' => $encoursF,
- 'encours_facture' => $encoursF,
- 'echeance_num' => null,
- 'echeance_total' => null,
- ];
- }
- }
- usort($echeances, fn($a, $b) => strcmp($a['date_echeance'], $b['date_echeance']));
- // Filtrer pour ne garder que les échéances à venir (date >= aujourd'hui)
- $aujourdhui = date('Y-m-d');
- $echeances = array_filter($echeances, fn($e) => $e['date_echeance'] >= $aujourdhui);
- $echeances = array_values($echeances);
- sendJson([
- 'encours_total' => $encoursTotal,
- 'encours_par_client' => $parClient,
- 'echeances_a_venir' => $echeances,
- ]);
|