| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <?php
- /**
- * API Quantités vendues par client (FR10c) : qte facturée, qte livrée, par type si demandé.
- * GET ?type=alevins|larves (optionnel)
- */
- 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;
- }
- $type = isset($_GET['type']) ? strtolower(trim($_GET['type'])) : null;
- if (isMockMode()) {
- $clients = loadMock('clients');
- $factures = loadMock('factures');
- $byClient = [];
- foreach ($factures as $f) {
- if ($type !== null && $type !== '' && strtolower(trim($f['type_produit'] ?? '')) !== $type) continue;
- $cid = (int) $f['client_id'];
- if (!isset($byClient[$cid])) {
- $byClient[$cid] = ['client_id' => $cid, 'nom' => '', 'qte_facturee' => 0, 'qte_livree' => 0];
- foreach ($clients as $c) {
- if ((int) $c['id'] === $cid) { $byClient[$cid]['nom'] = $c['nom']; break; }
- }
- }
- $byClient[$cid]['qte_facturee'] += (float) ($f['quantites'] ?? 0);
- $byClient[$cid]['qte_livree'] += (float) ($f['qte_livree'] ?? 0);
- }
- $rows = array_values($byClient);
- usort($rows, fn($a, $b) => $b['qte_facturee'] <=> $a['qte_facturee']);
- sendJson([
- 'type_filter' => $type,
- 'quantites_par_client' => $rows,
- ]);
- exit;
- }
- $pdo = getPdo();
- $params = [];
- if ($type !== null && $type !== '') {
- $sql = "
- SELECT c.id AS client_id, c.nom,
- SUM(COALESCE(f.quantites, 0)) AS qte_facturee,
- SUM(COALESCE(f.qte_livree, 0)) AS qte_livree
- FROM clients c
- INNER JOIN factures f ON f.client_id = c.id AND LOWER(TRIM(f.type_produit)) = ?
- GROUP BY c.id, c.nom
- HAVING qte_facturee > 0
- ORDER BY qte_facturee DESC
- ";
- $params = [$type];
- } else {
- $sql = "
- SELECT c.id AS client_id, c.nom,
- SUM(COALESCE(f.quantites, 0)) AS qte_facturee,
- SUM(COALESCE(f.qte_livree, 0)) AS qte_livree
- FROM clients c
- LEFT JOIN factures f ON f.client_id = c.id
- GROUP BY c.id, c.nom
- HAVING qte_facturee > 0
- ORDER BY qte_facturee DESC
- ";
- $params = [];
- }
- $stmt = $pdo->prepare($sql);
- $stmt->execute($params);
- $rows = $stmt->fetchAll();
- foreach ($rows as &$r) {
- $r['qte_facturee'] = (float) $r['qte_facturee'];
- $r['qte_livree'] = (float) $r['qte_livree'];
- }
- sendJson([
- 'type_filter' => $type,
- 'quantites_par_client' => $rows,
- ]);
|