calculs.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. /**
  3. * API Calculs - encours par client, encours total, échéances (FR6, FR7, FR8).
  4. * GET ?client_id= pour un client, sinon agrégé global.
  5. */
  6. require_once __DIR__ . '/config.php';
  7. header('Access-Control-Allow-Origin: *');
  8. header('Access-Control-Allow-Methods: GET');
  9. $method = $_SERVER['REQUEST_METHOD'] ?? '';
  10. if ($method !== 'GET') {
  11. sendError('Méthode non autorisée', 405);
  12. exit;
  13. }
  14. $clientId = isset($_GET['client_id']) ? (int) $_GET['client_id'] : null;
  15. if (isMockMode()) {
  16. $clients = loadMock('clients');
  17. $factures = loadMock('factures');
  18. $paiements = loadMock('paiements');
  19. $encoursByClient = [];
  20. foreach ($clients as $c) {
  21. $cid = (int) $c['id'];
  22. $totalFactures = 0;
  23. $totalPaye = 0;
  24. foreach ($factures as $f) {
  25. if ((int) $f['client_id'] === $cid) {
  26. $totalFactures += (float) $f['montant_ht'];
  27. foreach ($paiements as $p) {
  28. if ((int) $p['facture_id'] === (int) $f['id']) {
  29. $totalPaye += (float) $p['montant'];
  30. }
  31. }
  32. }
  33. }
  34. $encours = max(0, $totalFactures - $totalPaye);
  35. $encoursByClient[$cid] = ['client_id' => $cid, 'nom' => $c['nom'], 'encours' => $encours];
  36. }
  37. if ($clientId !== null && $clientId > 0) {
  38. if (!isset($encoursByClient[$clientId])) {
  39. sendError('Client non trouvé', 404);
  40. exit;
  41. }
  42. sendJson($encoursByClient[$clientId]);
  43. exit;
  44. }
  45. $parClient = array_values(array_filter($encoursByClient, fn($r) => $r['encours'] > 0));
  46. usort($parClient, fn($a, $b) => $b['encours'] <=> $a['encours']);
  47. $encoursTotal = array_sum(array_column($parClient, 'encours'));
  48. // Charger les écheanciers pour calculer les dates d'échéances réelles
  49. $echeanciers = loadMock('echeanciers');
  50. $echeancierByFacture = [];
  51. foreach ($echeanciers as $ech) {
  52. $echeancierByFacture[(int) $ech['facture_id']] = $ech;
  53. }
  54. $echeances = [];
  55. foreach ($factures as $f) {
  56. $totalPaye = 0;
  57. foreach ($paiements as $p) {
  58. if ((int) $p['facture_id'] === (int) $f['id']) $totalPaye += (float) $p['montant'];
  59. }
  60. $encoursF = max(0, (float) $f['montant_ht'] - $totalPaye);
  61. if ($encoursF > 0) {
  62. $nom = '';
  63. foreach ($clients as $c) {
  64. if ((int) $c['id'] === (int) $f['client_id']) { $nom = $c['nom']; break; }
  65. }
  66. $factureId = (int) $f['id'];
  67. // Si la facture a un écheancier, calculer les dates d'échéances réelles
  68. if (isset($echeancierByFacture[$factureId])) {
  69. $ech = $echeancierByFacture[$factureId];
  70. $dateDebut = new DateTime($ech['date_debut_echeancier']);
  71. $nbEcheances = (int) $ech['nb_echeances'];
  72. $montantParEch = isset($ech['montant_par_echeance']) ? (float) $ech['montant_par_echeance'] : ($nbEcheances > 0 ? $encoursF / $nbEcheances : 0);
  73. // Créer une échéance pour chaque date prévue
  74. for ($i = 0; $i < $nbEcheances; $i++) {
  75. $dateEcheance = clone $dateDebut;
  76. $dateEcheance->modify("+{$i} months");
  77. $echeances[] = [
  78. 'facture_id' => $factureId,
  79. 'client_id' => (int) $f['client_id'],
  80. 'nom' => $nom,
  81. 'n_facture' => $f['n_facture'],
  82. 'date_echeance' => $dateEcheance->format('Y-m-d'),
  83. 'montant_echeance' => $montantParEch,
  84. 'encours_facture' => $encoursF,
  85. 'echeance_num' => $i + 1,
  86. 'echeance_total' => $nbEcheances,
  87. ];
  88. }
  89. } else {
  90. // Pas d'écheancier : utiliser la date de facture
  91. $echeances[] = [
  92. 'facture_id' => $factureId,
  93. 'client_id' => (int) $f['client_id'],
  94. 'nom' => $nom,
  95. 'n_facture' => $f['n_facture'],
  96. 'date_echeance' => $f['date_facture'],
  97. 'montant_echeance' => $encoursF,
  98. 'encours_facture' => $encoursF,
  99. 'echeance_num' => null,
  100. 'echeance_total' => null,
  101. ];
  102. }
  103. }
  104. }
  105. usort($echeances, fn($a, $b) => strcmp($a['date_echeance'], $b['date_echeance']));
  106. // Filtrer pour ne garder que les échéances à venir (date >= aujourd'hui)
  107. $aujourdhui = date('Y-m-d');
  108. $echeances = array_filter($echeances, fn($e) => $e['date_echeance'] >= $aujourdhui);
  109. $echeances = array_values($echeances);
  110. sendJson([
  111. 'encours_total' => $encoursTotal,
  112. 'encours_par_client' => $parClient,
  113. 'echeances_a_venir' => $echeances,
  114. ]);
  115. exit;
  116. }
  117. $pdo = getPdo();
  118. if ($clientId !== null && $clientId > 0) {
  119. $stmt = $pdo->prepare("
  120. SELECT c.id AS client_id, c.nom,
  121. GREATEST(0, COALESCE(SUM(f.montant_ht), 0) - COALESCE(SUM(p.montant), 0)) AS encours
  122. FROM clients c
  123. LEFT JOIN factures f ON f.client_id = c.id
  124. LEFT JOIN paiements p ON p.facture_id = f.id
  125. WHERE c.id = ?
  126. GROUP BY c.id, c.nom
  127. ");
  128. $stmt->execute([$clientId]);
  129. $row = $stmt->fetch();
  130. if (!$row) {
  131. sendError('Client non trouvé', 404);
  132. exit;
  133. }
  134. sendJson([
  135. 'client_id' => (int) $row['client_id'],
  136. 'nom' => $row['nom'],
  137. 'encours' => (float) $row['encours'],
  138. ]);
  139. exit;
  140. }
  141. $stmt = $pdo->query("
  142. SELECT c.id AS client_id, c.nom,
  143. GREATEST(0, COALESCE(SUM(f.montant_ht), 0) - COALESCE(SUM(p.montant), 0)) AS encours
  144. FROM clients c
  145. LEFT JOIN factures f ON f.client_id = c.id
  146. LEFT JOIN paiements p ON p.facture_id = f.id
  147. GROUP BY c.id, c.nom
  148. HAVING encours > 0
  149. ORDER BY encours ASC
  150. ");
  151. $parClient = $stmt->fetchAll();
  152. $encoursTotal = 0;
  153. foreach ($parClient as &$r) {
  154. $r['encours'] = (float) $r['encours'];
  155. $encoursTotal += $r['encours'];
  156. }
  157. // Récupérer les factures avec encours et leurs écheanciers
  158. $stmt = $pdo->query("
  159. SELECT f.id AS facture_id, f.client_id, c.nom, f.n_facture, f.date_facture, f.montant_ht,
  160. COALESCE(SUM(p.montant), 0) AS total_paye,
  161. GREATEST(0, f.montant_ht - COALESCE(SUM(p.montant), 0)) AS encours_facture,
  162. e.id AS echeancier_id, e.nb_echeances, e.date_debut_echeancier, e.montant_par_echeance
  163. FROM factures f
  164. JOIN clients c ON c.id = f.client_id
  165. LEFT JOIN paiements p ON p.facture_id = f.id
  166. LEFT JOIN echeanciers e ON e.facture_id = f.id
  167. 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
  168. HAVING encours_facture > 0
  169. ORDER BY f.date_facture ASC
  170. ");
  171. $facturesAvecEncours = $stmt->fetchAll();
  172. $echeances = [];
  173. foreach ($facturesAvecEncours as $f) {
  174. $encoursF = (float) $f['encours_facture'];
  175. $factureId = (int) $f['facture_id'];
  176. // Si la facture a un écheancier, calculer les dates d'échéances réelles
  177. if ($f['echeancier_id'] !== null && $f['date_debut_echeancier'] !== null) {
  178. $dateDebut = new DateTime($f['date_debut_echeancier']);
  179. $nbEcheances = (int) $f['nb_echeances'];
  180. $montantParEch = $f['montant_par_echeance'] !== null ? (float) $f['montant_par_echeance'] : ($nbEcheances > 0 ? $encoursF / $nbEcheances : 0);
  181. // Créer une échéance pour chaque date prévue
  182. for ($i = 0; $i < $nbEcheances; $i++) {
  183. $dateEcheance = clone $dateDebut;
  184. $dateEcheance->modify("+{$i} months");
  185. $echeances[] = [
  186. 'facture_id' => $factureId,
  187. 'client_id' => (int) $f['client_id'],
  188. 'nom' => $f['nom'],
  189. 'n_facture' => $f['n_facture'],
  190. 'date_echeance' => $dateEcheance->format('Y-m-d'),
  191. 'montant_echeance' => $montantParEch,
  192. 'encours_facture' => $encoursF,
  193. 'echeance_num' => $i + 1,
  194. 'echeance_total' => $nbEcheances,
  195. ];
  196. }
  197. } else {
  198. // Pas d'écheancier : utiliser la date de facture
  199. $echeances[] = [
  200. 'facture_id' => $factureId,
  201. 'client_id' => (int) $f['client_id'],
  202. 'nom' => $f['nom'],
  203. 'n_facture' => $f['n_facture'],
  204. 'date_echeance' => $f['date_facture'],
  205. 'montant_echeance' => $encoursF,
  206. 'encours_facture' => $encoursF,
  207. 'echeance_num' => null,
  208. 'echeance_total' => null,
  209. ];
  210. }
  211. }
  212. usort($echeances, fn($a, $b) => strcmp($a['date_echeance'], $b['date_echeance']));
  213. // Filtrer pour ne garder que les échéances à venir (date >= aujourd'hui)
  214. $aujourdhui = date('Y-m-d');
  215. $echeances = array_filter($echeances, fn($e) => $e['date_echeance'] >= $aujourdhui);
  216. $echeances = array_values($echeances);
  217. sendJson([
  218. 'encours_total' => $encoursTotal,
  219. 'encours_par_client' => $parClient,
  220. 'echeances_a_venir' => $echeances,
  221. ]);