quantites-clients.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * API Quantités vendues par client (FR10c) : qte facturée, qte livrée, par type si demandé.
  4. * GET ?type=alevins|larves (optionnel)
  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. $type = isset($_GET['type']) ? strtolower(trim($_GET['type'])) : null;
  15. if (isMockMode()) {
  16. $clients = loadMock('clients');
  17. $factures = loadMock('factures');
  18. $byClient = [];
  19. foreach ($factures as $f) {
  20. if ($type !== null && $type !== '' && strtolower(trim($f['type_produit'] ?? '')) !== $type) continue;
  21. $cid = (int) $f['client_id'];
  22. if (!isset($byClient[$cid])) {
  23. $byClient[$cid] = ['client_id' => $cid, 'nom' => '', 'qte_facturee' => 0, 'qte_livree' => 0];
  24. foreach ($clients as $c) {
  25. if ((int) $c['id'] === $cid) { $byClient[$cid]['nom'] = $c['nom']; break; }
  26. }
  27. }
  28. $byClient[$cid]['qte_facturee'] += (float) ($f['quantites'] ?? 0);
  29. $byClient[$cid]['qte_livree'] += (float) ($f['qte_livree'] ?? 0);
  30. }
  31. $rows = array_values($byClient);
  32. usort($rows, fn($a, $b) => $b['qte_facturee'] <=> $a['qte_facturee']);
  33. sendJson([
  34. 'type_filter' => $type,
  35. 'quantites_par_client' => $rows,
  36. ]);
  37. exit;
  38. }
  39. $pdo = getPdo();
  40. $params = [];
  41. if ($type !== null && $type !== '') {
  42. $sql = "
  43. SELECT c.id AS client_id, c.nom,
  44. SUM(COALESCE(f.quantites, 0)) AS qte_facturee,
  45. SUM(COALESCE(f.qte_livree, 0)) AS qte_livree
  46. FROM clients c
  47. INNER JOIN factures f ON f.client_id = c.id AND LOWER(TRIM(f.type_produit)) = ?
  48. GROUP BY c.id, c.nom
  49. HAVING qte_facturee > 0
  50. ORDER BY qte_facturee DESC
  51. ";
  52. $params = [$type];
  53. } else {
  54. $sql = "
  55. SELECT c.id AS client_id, c.nom,
  56. SUM(COALESCE(f.quantites, 0)) AS qte_facturee,
  57. SUM(COALESCE(f.qte_livree, 0)) AS qte_livree
  58. FROM clients c
  59. LEFT JOIN factures f ON f.client_id = c.id
  60. GROUP BY c.id, c.nom
  61. HAVING qte_facturee > 0
  62. ORDER BY qte_facturee DESC
  63. ";
  64. $params = [];
  65. }
  66. $stmt = $pdo->prepare($sql);
  67. $stmt->execute($params);
  68. $rows = $stmt->fetchAll();
  69. foreach ($rows as &$r) {
  70. $r['qte_facturee'] = (float) $r['qte_facturee'];
  71. $r['qte_livree'] = (float) $r['qte_livree'];
  72. }
  73. sendJson([
  74. 'type_filter' => $type,
  75. 'quantites_par_client' => $rows,
  76. ]);