瀏覽代碼

Initial: PDF planning, maquettes (doc projet), app

Co-authored-by: Cursor <cursoragent@cursor.com>
augustin.podvin 9 月之前
當前提交
617d63da8e
共有 63 個文件被更改,包括 3408 次插入 和 0 次删除
  1. 21 0
      .gitignore
  2. 二進制
      _bmad-output/planning-artifacts/pdf/README-PDF.pdf
  3. 二進制
      _bmad-output/planning-artifacts/pdf/architecture-generale-fonctionnelle-et-interfaces.pdf
  4. 二進制
      _bmad-output/planning-artifacts/pdf/architecture.pdf
  5. 二進制
      _bmad-output/planning-artifacts/pdf/cahier-recettes-livraison.pdf
  6. 二進制
      _bmad-output/planning-artifacts/pdf/decisions-client-chiffrage.pdf
  7. 二進制
      _bmad-output/planning-artifacts/pdf/ecart-excel-captures-vs-appli.pdf
  8. 二進制
      _bmad-output/planning-artifacts/pdf/ecart-methodologie-intersel-vs-projet.pdf
  9. 二進制
      _bmad-output/planning-artifacts/pdf/gaps-et-guides-chiffrage-client-stagiaire.pdf
  10. 二進制
      _bmad-output/planning-artifacts/pdf/grille-complexite-chiffrage.pdf
  11. 二進制
      _bmad-output/planning-artifacts/pdf/implementation-readiness-report-2026-02-09.pdf
  12. 二進制
      _bmad-output/planning-artifacts/pdf/listing-complet-ecrans-pages.pdf
  13. 二進制
      _bmad-output/planning-artifacts/pdf/logique-paiements-echeanciers.pdf
  14. 二進制
      _bmad-output/planning-artifacts/pdf/options-reduction-perimetre-chiffrage.pdf
  15. 二進制
      _bmad-output/planning-artifacts/pdf/prd.pdf
  16. 二進制
      _bmad-output/planning-artifacts/pdf/product-brief-bmad-2026-02-09.pdf
  17. 二進制
      _bmad-output/planning-artifacts/pdf/questions-en-suspens.pdf
  18. 二進制
      _bmad-output/planning-artifacts/pdf/schema-chiffrage-projet.pdf
  19. 二進制
      _bmad-output/planning-artifacts/pdf/schema-relationnel-et-tables-donnees.pdf
  20. 二進制
      _bmad-output/planning-artifacts/pdf/schema-workflows.pdf
  21. 二進制
      _bmad-output/planning-artifacts/pdf/synthèse-projet-lecture-client.pdf
  22. 6 0
      app/.env.example
  23. 4 0
      app/.gitignore
  24. 133 0
      app/INSTALL.md
  25. 120 0
      app/ONBOARDING-STAGIAIRE.md
  26. 60 0
      app/README.md
  27. 239 0
      app/api/calculs.php
  28. 152 0
      app/api/clients.php
  29. 84 0
      app/api/config.php
  30. 198 0
      app/api/echeanciers.php
  31. 243 0
      app/api/factures.php
  32. 160 0
      app/api/paiements.php
  33. 82 0
      app/api/quantites-clients.php
  34. 386 0
      app/api/reporting.php
  35. 93 0
      app/api/top-clients.php
  36. 102 0
      app/client.html
  37. 43 0
      app/dashboard.html
  38. 128 0
      app/index.html
  39. 269 0
      app/js/client-detail.js
  40. 114 0
      app/js/dashboard.js
  41. 82 0
      app/js/echeancier-form.js
  42. 68 0
      app/js/facture-form.js
  43. 30 0
      app/js/paiements.js
  44. 52 0
      app/js/quantites-clients.js
  45. 67 0
      app/js/top-clients.js
  46. 85 0
      app/js/utils.js
  47. 22 0
      app/mock/clients.json
  48. 34 0
      app/mock/echeanciers.json
  49. 67 0
      app/mock/factures.json
  50. 58 0
      app/mock/paiements.json
  51. 43 0
      app/quantites-clients.html
  52. 35 0
      app/sql/migration-echeanciers-montant.sql
  53. 13 0
      app/sql/migration-echeanciers.sql
  54. 7 0
      app/sql/migration-type-produit-cycle.sql
  55. 56 0
      app/sql/schema.sql
  56. 52 0
      app/top-clients.html
  57. 二進制
      doc projet/new captures/2026-01-13_10-33-26.jpg
  58. 二進制
      doc projet/new captures/2026-01-13_10-34-49.jpg
  59. 二進制
      doc projet/new captures/2026-01-13_10-37-15.jpg
  60. 二進制
      doc projet/new captures/2026-01-13_10-37-45.jpg
  61. 二進制
      doc projet/new captures/2026-01-13_10-59-25.jpg
  62. 二進制
      doc projet/new captures/en plus previsionnel/2026-01-13_11-18-02.jpg
  63. 二進制
      doc projet/new captures/listing facturation.jpg

+ 21 - 0
.gitignore

@@ -0,0 +1,21 @@
+# ===== BMAD : tout ignorer sauf les PDF générés =====
+_bmad/
+_bmad-output/*
+!_bmad-output/planning-artifacts/
+_bmad-output/planning-artifacts/*
+!_bmad-output/planning-artifacts/pdf/
+
+# ===== Fichiers / dossiers à ne pas versionner =====
+.cursor/
+node_modules/
+*.log
+.DS_Store
+.env
+vendor/
+~$*
+*.tmp
+*.docx
+Thumbs.db
+
+# ===== Optionnel : décommenter pour ignorer aussi l'app (si vous ne versionnez que PDF + maquettes) =====
+# app/

二進制
_bmad-output/planning-artifacts/pdf/README-PDF.pdf


二進制
_bmad-output/planning-artifacts/pdf/architecture-generale-fonctionnelle-et-interfaces.pdf


二進制
_bmad-output/planning-artifacts/pdf/architecture.pdf


二進制
_bmad-output/planning-artifacts/pdf/cahier-recettes-livraison.pdf


二進制
_bmad-output/planning-artifacts/pdf/decisions-client-chiffrage.pdf


二進制
_bmad-output/planning-artifacts/pdf/ecart-excel-captures-vs-appli.pdf


二進制
_bmad-output/planning-artifacts/pdf/ecart-methodologie-intersel-vs-projet.pdf


二進制
_bmad-output/planning-artifacts/pdf/gaps-et-guides-chiffrage-client-stagiaire.pdf


二進制
_bmad-output/planning-artifacts/pdf/grille-complexite-chiffrage.pdf


二進制
_bmad-output/planning-artifacts/pdf/implementation-readiness-report-2026-02-09.pdf


二進制
_bmad-output/planning-artifacts/pdf/listing-complet-ecrans-pages.pdf


二進制
_bmad-output/planning-artifacts/pdf/logique-paiements-echeanciers.pdf


二進制
_bmad-output/planning-artifacts/pdf/options-reduction-perimetre-chiffrage.pdf


二進制
_bmad-output/planning-artifacts/pdf/prd.pdf


二進制
_bmad-output/planning-artifacts/pdf/product-brief-bmad-2026-02-09.pdf


二進制
_bmad-output/planning-artifacts/pdf/questions-en-suspens.pdf


二進制
_bmad-output/planning-artifacts/pdf/schema-chiffrage-projet.pdf


二進制
_bmad-output/planning-artifacts/pdf/schema-relationnel-et-tables-donnees.pdf


二進制
_bmad-output/planning-artifacts/pdf/schema-workflows.pdf


二進制
_bmad-output/planning-artifacts/pdf/synthèse-projet-lecture-client.pdf


+ 6 - 0
app/.env.example

@@ -0,0 +1,6 @@
+DB_HOST=localhost
+DB_NAME=bmad
+DB_USER=root
+DB_PASS=
+DB_CHARSET=utf8mb4
+MOCK_MODE=1

+ 4 - 0
app/.gitignore

@@ -0,0 +1,4 @@
+.env
+vendor/
+*.log
+.DS_Store

+ 133 - 0
app/INSTALL.md

@@ -0,0 +1,133 @@
+# Création de la base et lancement
+
+## 0. Si « mysql » n’est pas reconnu
+
+La commande `mysql` doit être exécutable. Soit tu l’ajoutes au PATH, soit tu utilises le **chemin complet** vers `mysql.exe`.
+
+**Où se trouve mysql.exe ?**
+
+- **XAMPP** : `C:\xampp\mysql\bin\mysql.exe`
+- **WAMP** : `C:\wamp64\bin\mysql\mysql8.x.x\bin\mysql.exe` (adapte la version)
+- **MySQL installé seul** : souvent `C:\Program Files\MySQL\MySQL Server 8.x\bin\mysql.exe`
+- **Laragon** : `C:\laragon\bin\mysql\mysql-8.x.x-w64\bin\mysql.exe`
+
+Dans les commandes ci‑dessous, remplace `mysql` par le chemin complet, par exemple :
+```powershell
+& "C:\xampp\mysql\bin\mysql.exe" -u root -p -e "CREATE DATABASE IF NOT EXISTS bmad CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
+```
+(Le `&` en PowerShell permet d’exécuter un chemin entre guillemets.)
+
+**Si tu n’as ni XAMPP ni MySQL** : installe [XAMPP](https://www.apachefriends.org/) (avec MySQL) ou [MariaDB](https://mariadb.org/download/), puis utilise le chemin vers `mysql.exe` comme ci‑dessus.
+
+---
+
+## 1. Créer la base de données
+
+Ouvre un terminal (PowerShell ou CMD) et lance MySQL/MariaDB.
+
+**Si MySQL/MariaDB est dans le PATH :**
+```bash
+mysql -u root -p -e "CREATE DATABASE IF NOT EXISTS bmad CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
+```
+(Entre le mot de passe root quand il est demandé. Si pas de mot de passe, utilise `mysql -u root` sans `-p`.)
+
+**Avec XAMPP** (MySQL dans `C:\xampp\mysql\bin`) :
+```bash
+C:\xampp\mysql\bin\mysql.exe -u root -p -e "CREATE DATABASE IF NOT EXISTS bmad CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
+```
+
+**Avec WAMP** (chemin type `C:\wamp64\bin\mysql\mysql8.x.x\bin\mysql.exe`) :
+```bash
+C:\wamp64\bin\mysql\mysql8.2.0\bin\mysql.exe -u root -p -e "CREATE DATABASE IF NOT EXISTS bmad CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
+```
+(Adapte la version MySQL dans le chemin.)
+
+---
+
+## 2. Importer le schéma (créer les tables)
+
+Depuis la racine du projet **bmad** (le dossier qui contient `app`).
+
+**MySQL dans le PATH :**
+```bash
+mysql -u root -p bmad < app/sql/schema.sql
+```
+
+**Avec XAMPP :**
+```bash
+C:\xampp\mysql\bin\mysql.exe -u root -p bmad < app/sql/schema.sql
+```
+
+**Si tu es déjà dans le dossier `app` :**
+```bash
+mysql -u root -p bmad < sql/schema.sql
+```
+
+---
+
+## 3. Fichier de configuration .env
+
+Dans le dossier **app**, copie le fichier d’exemple puis édite-le :
+
+**PowerShell (depuis la racine du projet) :**
+```powershell
+cd app
+Copy-Item .env.example .env
+notepad .env
+```
+
+**CMD :**
+```cmd
+cd app
+copy .env.example .env
+notepad .env
+```
+
+Dans `.env`, vérifie ou modifie :
+- `DB_HOST=localhost`
+- `DB_NAME=bmad`
+- `DB_USER=root`
+- `DB_PASS=` (ton mot de passe MySQL, ou vide si pas de mot de passe)
+
+Sauvegarde et ferme.
+
+---
+
+## 4. Lancer l’application
+
+Toujours depuis le dossier **app** :
+
+```bash
+php -S localhost:8080
+```
+
+Ouvre le navigateur : **http://localhost:8080**
+
+---
+
+## 5. (Optionnel) Données de test
+
+Pour avoir des clients et des factures tout de suite, exécute ce SQL après l’import du schéma :
+
+```bash
+mysql -u root -p bmad -e "
+INSERT INTO clients (nom) VALUES ('Client A'), ('Client B');
+INSERT INTO factures (client_id, n_facture, n_vente, date_facture, montant_ht) VALUES (1, 'FA-001', 'V1', '2026-01-15', 1000), (1, 'FA-002', 'V2', '2026-02-01', 500);
+INSERT INTO paiements (facture_id, montant, date_paiement) VALUES (1, 500, '2026-02-01');
+"
+```
+
+**Avec XAMPP :**
+```bash
+C:\xampp\mysql\bin\mysql.exe -u root -p bmad -e "INSERT INTO clients (nom) VALUES ('Client A'), ('Client B'); INSERT INTO factures (client_id, n_facture, n_vente, date_facture, montant_ht) VALUES (1, 'FA-001', 'V1', '2026-01-15', 1000), (1, 'FA-002', 'V2', '2026-02-01', 500); INSERT INTO paiements (facture_id, montant, date_paiement) VALUES (1, 500, '2026-02-01');"
+```
+
+---
+
+## Récap ordre des commandes
+
+1. Créer la base : `mysql -u root -p -e "CREATE DATABASE ..."`
+2. Importer le schéma : `mysql -u root -p bmad < app/sql/schema.sql`
+3. Copier et éditer `app/.env`
+4. Lancer : `cd app` puis `php -S localhost:8080`
+5. (Optionnel) Insérer les données de test

+ 120 - 0
app/ONBOARDING-STAGIAIRE.md

@@ -0,0 +1,120 @@
+# Guide stagiaire – Onboarding projet bmad
+
+**Projet :** Suivi facturation / échéancier / paiement (EMGI).  
+**Objectif :** Comprendre le projet, lancer l’appli et savoir où modifier le code.
+
+---
+
+## 1. En deux phrases
+
+L’appli remplace Excel pour le suivi des factures, paiements et échéanciers. Les factures sont émises dans Pennylane ; ici on les saisit pour le suivi (encours, paiements, tableaux de bord, exports).
+
+---
+
+## 2. Où sont les docs ?
+
+| Doc | Contenu |
+|-----|--------|
+| **Ce fichier** (`app/ONBOARDING-STAGIAIRE.md`) | Démarrage, structure, où modifier quoi. |
+| **`app/README.md`** | Installation (mock + base), structure dossiers, export. |
+| **`_bmad-output/planning-artifacts/prd.md`** | Périmètre, fonctionnalités (FR), user journeys. |
+| **`_bmad-output/planning-artifacts/architecture.md`** | Stack, API, conventions, limites techniques. |
+| **`_bmad-output/planning-artifacts/schema-chiffrage-projet.md`** | Modules, endpoints, données, points complexes. |
+| **`_bmad-output/planning-artifacts/cahier-recettes-livraison.md`** | Critères de recette (pour vérifier que ça marche). |
+| **`_bmad-output/planning-artifacts/questions-en-suspens.md`** | Questions pas encore tranchées (auth, Pennylane, etc.). |
+
+Ordre conseillé : README app → PRD (pour le métier) → ce guide → architecture si tu creuses le technique.
+
+---
+
+## 3. Lancer l’application
+
+**Sans base de données (démo mock) :**
+```bash
+cd app
+php -S localhost:8080
+```
+Puis ouvrir http://localhost:8080. Les données viennent de `mock/*.json`.
+
+**Avec base de données :**
+1. Créer la base : `mysql -u root -p -e "CREATE DATABASE IF NOT EXISTS bmad CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"`
+2. Importer le schéma : `mysql -u root -p bmad < sql/schema.sql`
+3. Copier `.env.example` en `.env`, mettre `MOCK_MODE=0` et renseigner DB_HOST, DB_NAME, DB_USER, DB_PASS
+4. Depuis `app/` : `php -S localhost:8080`
+5. Ouvrir http://localhost:8080
+
+Prérequis : PHP 7.4+ avec extensions `pdo`, `pdo_mysql`, `json`. MariaDB ou MySQL pour le mode base.
+
+---
+
+## 4. Structure du code (où modifier quoi)
+
+| Besoin | Fichiers à toucher |
+|--------|--------------------|
+| **Liste des clients, recherche** | `index.html`, `js/` (script liste clients si dédié), `api/clients.php` |
+| **Fiche client (en-tête, encours)** | `client.html`, `js/client-detail.js`, `api/clients.php`, `api/calculs.php` |
+| **Liste des factures d’un client** | `js/client-detail.js` (affichage), `api/factures.php` (données) |
+| **Ajouter une facture** | `client.html` (formulaire), `js/facture-form.js`, `api/factures.php` (POST) |
+| **Liste des paiements, enregistrer un paiement** | `client.html`, `js/paiements.js`, `api/paiements.php` |
+| **Écheanciers (liste + ajout)** | `client.html`, `js/client-detail.js`, `js/echeancier-form.js`, `api/echeanciers.php` |
+| **Calculs (encours, échéances à venir)** | `api/calculs.php` (et logique mock dans `api/factures.php`, `api/reporting.php`) |
+| **Tableau de bord** | `dashboard.html`, `js/dashboard.js`, `api/calculs.php`, `api/reporting.php` |
+| **Top clients** | `top-clients.html`, `js/top-clients.js`, `api/top-clients.php` |
+| **Quantités par client** | `quantites-clients.html`, `js/quantites-clients.js`, `api/quantites-clients.php` |
+| **Export CSV** | `api/reporting.php` (?format=csv) |
+| **Schéma de données** | `sql/schema.sql` ; migrations dans `sql/migration-*.sql` |
+
+Convention : **un fichier API par ressource** (clients, factures, paiements, echeanciers, calculs, reporting, top-clients, quantites-clients). Pas d’appels API-to-API. Front en **JavaScript vanilla** (pas de framework) et **Tailwind** en CDN.
+
+---
+
+## 5. Conventions (résumé)
+
+- **Base de données / API :** noms en `snake_case` (ex. `client_id`, `date_facture`). Réponses JSON sans wrapper `{ data: ... }` ; erreurs en `{ error: "message" }`.
+- **PHP :** variables `$camelCase`, fonctions en camelCase.
+- **JS :** variables et fonctions en camelCase. Fichiers en minuscules avec tirets (ex. `client-detail.js`).
+- **Endpoints :** pluriel (`/api/clients.php`, `/api/factures.php`). Paramètres en query ou body selon besoin.
+
+Détails complets dans `_bmad-output/planning-artifacts/architecture.md`.
+
+---
+
+## 6. Comment vérifier que ça marche
+
+- **À la main :** naviguer dans l’appli (liste clients, fiche client, ajout facture/paiement/écheancier, dashboard, Top clients, Quantités, export CSV).
+- **Recette :** le fichier `cahier-recettes-livraison.md` liste 32 critères (O/N) pour la livraison.
+- **API sans le front :** avec Postman ou curl, par ex. `GET http://localhost:8080/api/clients.php`, `GET http://localhost:8080/api/factures.php?client_id=1`, `POST http://localhost:8080/api/paiements.php` avec body JSON.
+
+Il n’y a pas de tests automatisés pour le POC.
+
+---
+
+## 7. FAQ (questions que tu vas te poser)
+
+- **Pourquoi saisir les factures à la main alors qu’il y a Pennylane ?**  
+  L’appli fait le **suivi** (encours, paiements, écheanciers). La facturation « document » (PDF) reste dans Pennylane. Pas d’import automatique prévu en MVP.
+
+- **Où est la logique d’encours ?**  
+  Dans `api/calculs.php`. La même logique est reproduite en mode mock dans `api/factures.php` et `api/reporting.php` pour afficher encours et état par facture.
+
+- **Pourquoi mock et DB ?**  
+  Le mode mock permet de démo sans installer MySQL. En prod on utilise la base (MOCK_MODE=0 dans `.env`).
+
+- **Je peux utiliser Vue / React ?**  
+  Non pour ce POC : on reste en JavaScript vanilla (décision architecture).
+
+- **Paiement supérieur au montant de la facture ?**  
+  Règle à clarifier (autoriser ou bloquer) ; pour l’instant à vérifier dans le code et le cahier recettes.
+
+- **Modifier / supprimer une facture ou un paiement ?**  
+  Pas prévu dans le MVP ; à confirmer avec le responsable projet (voir questions-en-suspens.md).
+
+---
+
+## 8. Contact
+
+En cas de doute technique ou métier : [à compléter — responsable technique / tuteur stagiaire].
+
+---
+
+*À mettre à jour au fil des retours (nouvelles questions, changements de structure).*

+ 60 - 0
app/README.md

@@ -0,0 +1,60 @@
+# Suivi facturation / échéancier (POC EMGI)
+
+Application de suivi facturation et échéancier de paiement — remplacement Excel pour l’équipe commerciale. La facturation (émission des factures, PDF) provient de **Pennylane** ; l’appli sert au suivi (saisie manuelle des factures pour encours, paiements, écheanciers).
+
+## Démo sans base (mode mock)
+
+Aucune config, pas de MySQL. Depuis le dossier `app` :
+
+```bash
+cd app
+php -S localhost:8080
+```
+
+Ouvre http://localhost:8080 — les données viennent de `mock/*.json`. Pour utiliser la vraie base, crée `.env` (copie de `.env.example`), mets `MOCK_MODE=0` et configure DB_*.
+
+## Prérequis (mode base)
+
+- PHP 7.4+ (avec extensions `pdo`, `pdo_mysql`, `json`)
+- MariaDB ou MySQL
+
+## Installation (mode base)
+
+1. Créer la base et importer le schéma :
+   ```bash
+   mysql -u root -p -e "CREATE DATABASE IF NOT EXISTS bmad CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
+   mysql -u root -p bmad < sql/schema.sql
+   ```
+
+2. Configurer l’accès DB :
+   ```bash
+   cp .env.example .env
+   # Éditer .env : DB_HOST, DB_NAME, DB_USER, DB_PASS
+   ```
+
+3. Démarrer le serveur PHP (depuis le dossier `app/`) :
+   ```bash
+   php -S localhost:8080
+   ```
+
+4. Ouvrir dans le navigateur : [http://localhost:8080](http://localhost:8080)
+
+## Structure
+
+- `api/` — API REST PHP (clients, factures GET/POST, paiements, calculs, reporting, top-clients, quantites-clients)
+- `js/` — Scripts front (liste clients, détail client, formulaire ajout facture, paiements, tableau de bord, top clients, quantités par client)
+- `sql/schema.sql` — Schéma : `clients`, `factures` (type_produit, cycle, qte_livree), `paiements`
+- Pages : index (clients), client (détail + ajout facture + paiement), dashboard, top-clients, quantites-clients
+
+## Données de test (optionnel)
+
+```sql
+INSERT INTO clients (nom) VALUES ('Client A'), ('Client B');
+INSERT INTO factures (client_id, n_facture, n_vente, date_facture, montant_ht) VALUES (1, 'FA-001', 'V1', '2026-01-15', 1000), (1, 'FA-002', 'V2', '2026-02-01', 500);
+INSERT INTO paiements (facture_id, montant, date_paiement) VALUES (1, 500, '2026-02-01');
+```
+
+## Export
+
+- Tableau de bord : lien « Exporter CSV » pour télécharger l’encours par client.
+- API : `GET /api/reporting.php?format=csv` pour le même export.

+ 239 - 0
app/api/calculs.php

@@ -0,0 +1,239 @@
+<?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,
+]);

+ 152 - 0
app/api/clients.php

@@ -0,0 +1,152 @@
+<?php
+/**
+ * API Clients - liste et détail (FR1, FR2).
+ * GET ?q=nom pour recherche, GET ?id= pour un client.
+ */
+require_once __DIR__ . '/config.php';
+
+header('Access-Control-Allow-Origin: *');
+header('Access-Control-Allow-Methods: GET, POST, DELETE');
+header('Access-Control-Allow-Headers: Content-Type');
+
+$method = $_SERVER['REQUEST_METHOD'] ?? '';
+
+if ($method === 'POST') {
+    $input = json_decode(file_get_contents('php://input'), true) ?? [];
+    $nom = isset($input['nom']) ? trim($input['nom']) : '';
+
+    if ($nom === '') {
+        sendError('nom requis', 400);
+        exit;
+    }
+
+    if (isMockMode()) {
+        $clients = loadMock('clients');
+        $newId = 1;
+        foreach ($clients as $c) {
+            if ((int) $c['id'] >= $newId) $newId = (int) $c['id'] + 1;
+        }
+        $row = [
+            'id' => $newId,
+            'nom' => $nom,
+            'created_at' => (new DateTime())->format(DateTime::ATOM),
+        ];
+        $clients[] = $row;
+        saveMock('clients', $clients);
+        sendJson($row);
+        exit;
+    }
+
+    $pdo = getPdo();
+    $stmt = $pdo->prepare('INSERT INTO clients (nom) VALUES (?)');
+    $stmt->execute([$nom]);
+    $id = (int) $pdo->lastInsertId();
+    $stmt = $pdo->prepare('SELECT id, nom, created_at FROM clients WHERE id = ?');
+    $stmt->execute([$id]);
+    $row = $stmt->fetch();
+    $row['created_at'] = $row['created_at'] ? (new DateTime($row['created_at']))->format(DateTime::ATOM) : null;
+    sendJson($row);
+    exit;
+}
+
+if ($method === 'DELETE') {
+    $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
+    if ($id <= 0) {
+        sendError('id requis', 400);
+        exit;
+    }
+
+    if (isMockMode()) {
+        $clients = loadMock('clients');
+        $found = false;
+        foreach ($clients as $i => $c) {
+            if ((int) $c['id'] === $id) {
+                unset($clients[$i]);
+                $clients = array_values($clients);
+                saveMock('clients', $clients);
+                sendJson(['success' => true, 'id' => $id]);
+                exit;
+            }
+        }
+        sendError('Client non trouvé', 404);
+        exit;
+    }
+
+    $pdo = getPdo();
+    // Vérifier que le client n'a pas de factures (cascade gérée par la DB mais on peut vérifier)
+    $stmt = $pdo->prepare('SELECT COUNT(*) AS nb FROM factures WHERE client_id = ?');
+    $stmt->execute([$id]);
+    $row = $stmt->fetch();
+    if ($row && (int) $row['nb'] > 0) {
+        sendError('Impossible de supprimer : ce client a des factures associées', 400);
+        exit;
+    }
+    $stmt = $pdo->prepare('DELETE FROM clients WHERE id = ?');
+    $stmt->execute([$id]);
+    if ($stmt->rowCount() === 0) {
+        sendError('Client non trouvé', 404);
+        exit;
+    }
+    sendJson(['success' => true, 'id' => $id]);
+    exit;
+}
+
+if ($method !== 'GET') {
+    sendError('Méthode non autorisée', 405);
+    exit;
+}
+
+$id = isset($_GET['id']) ? (int) $_GET['id'] : null;
+$q = isset($_GET['q']) ? trim($_GET['q']) : '';
+
+if (isMockMode()) {
+    $clients = loadMock('clients');
+    if ($id !== null && $id > 0) {
+        foreach ($clients as $c) {
+            if ((int) $c['id'] === $id) {
+                sendJson($c);
+                exit;
+            }
+        }
+        sendError('Client non trouvé', 404);
+        exit;
+    }
+    if ($q !== '') {
+        $clients = array_values(array_filter($clients, function ($c) use ($q) {
+            return stripos($c['nom'], $q) !== false;
+        }));
+    }
+    usort($clients, fn($a, $b) => strcasecmp($a['nom'], $b['nom']));
+    sendJson($clients);
+    exit;
+}
+
+$pdo = getPdo();
+if ($id !== null && $id > 0) {
+    $stmt = $pdo->prepare('SELECT id, nom, created_at FROM clients WHERE id = ?');
+    $stmt->execute([$id]);
+    $row = $stmt->fetch();
+    if (!$row) {
+        sendError('Client non trouvé', 404);
+        exit;
+    }
+    $row['created_at'] = $row['created_at'] ? (new DateTime($row['created_at']))->format(DateTime::ATOM) : null;
+    sendJson($row);
+    exit;
+}
+
+$sql = 'SELECT id, nom, created_at FROM clients';
+$params = [];
+if ($q !== '') {
+    $sql .= ' WHERE nom LIKE ?';
+    $params[] = '%' . $q . '%';
+}
+$sql .= ' ORDER BY nom';
+
+$stmt = $pdo->prepare($sql);
+$stmt->execute($params);
+$rows = $stmt->fetchAll();
+foreach ($rows as &$r) {
+    $r['created_at'] = $r['created_at'] ? (new DateTime($r['created_at']))->format(DateTime::ATOM) : null;
+}
+sendJson($rows);

+ 84 - 0
app/api/config.php

@@ -0,0 +1,84 @@
+<?php
+/**
+ * Configuration DB pour l'API POC.
+ * Lit les variables d'environnement ou des constantes (fallback).
+ */
+
+$envFile = dirname(__DIR__) . '/.env';
+if (is_readable($envFile)) {
+    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
+    foreach ($lines as $line) {
+        if (strpos(trim($line), '#') === 0) continue;
+        if (strpos($line, '=') !== false) {
+            list($key, $value) = explode('=', $line, 2);
+            $_ENV[trim($key)] = trim($value, " \t\"'");
+        }
+    }
+}
+
+$dbHost = $_ENV['DB_HOST'] ?? 'localhost';
+$dbName = $_ENV['DB_NAME'] ?? 'bmad';
+$dbUser = $_ENV['DB_USER'] ?? 'root';
+$dbPass = $_ENV['DB_PASS'] ?? '';
+$dbCharset = $_ENV['DB_CHARSET'] ?? 'utf8mb4';
+$mockMode = isset($_ENV['MOCK_MODE']) ? ($_ENV['MOCK_MODE'] === '1') : !is_readable($envFile);
+
+$dsn = "mysql:host=$dbHost;dbname=$dbName;charset=$dbCharset";
+
+function isMockMode(): bool
+{
+    global $mockMode;
+    return (bool) $mockMode;
+}
+
+function getPdo(): PDO
+{
+    if (isMockMode()) {
+        throw new RuntimeException('MOCK_MODE activé : pas de connexion DB');
+    }
+    global $dsn, $dbUser, $dbPass;
+    static $pdo = null;
+    if ($pdo === null) {
+        $pdo = new PDO($dsn, $dbUser, $dbPass, [
+            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
+            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
+        ]);
+    }
+    return $pdo;
+}
+
+function mockPath(string $name): string
+{
+    return dirname(__DIR__) . '/mock/' . $name . '.json';
+}
+
+function loadMock(string $name): array
+{
+    $path = mockPath($name);
+    if (!is_readable($path)) return [];
+    $raw = file_get_contents($path);
+    $data = json_decode($raw ?: '[]', true);
+    return is_array($data) ? $data : [];
+}
+
+function saveMock(string $name, array $data): void
+{
+    $path = mockPath($name);
+    if (!is_dir(dirname($path))) {
+        mkdir(dirname($path), 0777, true);
+    }
+    file_put_contents($path, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
+}
+
+function sendJson($data): void
+{
+    header('Content-Type: application/json; charset=utf-8');
+    echo json_encode($data, JSON_UNESCAPED_UNICODE);
+}
+
+function sendError(string $message, int $code = 400): void
+{
+    http_response_code($code);
+    header('Content-Type: application/json; charset=utf-8');
+    echo json_encode(['error' => $message], JSON_UNESCAPED_UNICODE);
+}

+ 198 - 0
app/api/echeanciers.php

@@ -0,0 +1,198 @@
+<?php
+/**
+ * API Écheanciers - FR4b, FR5b.
+ * GET ?client_id= ou ?facture_id= | POST pour ajouter un écheancier (facture_id, nb_echeances, date_debut_echeancier).
+ */
+require_once __DIR__ . '/config.php';
+
+header('Access-Control-Allow-Origin: *');
+header('Access-Control-Allow-Methods: GET, POST, DELETE');
+header('Access-Control-Allow-Headers: Content-Type');
+
+$method = $_SERVER['REQUEST_METHOD'] ?? '';
+
+if ($method === 'POST') {
+    $input = json_decode(file_get_contents('php://input'), true) ?? [];
+    $factureId = isset($input['facture_id']) ? (int) $input['facture_id'] : 0;
+    $nbEcheances = isset($input['nb_echeances']) ? (int) $input['nb_echeances'] : 0;
+    $dateDebut = isset($input['date_debut_echeancier']) ? trim($input['date_debut_echeancier']) : '';
+
+    if ($factureId <= 0 || $nbEcheances <= 0 || $dateDebut === '') {
+        sendError('facture_id, nb_echeances (positif) et date_debut_echeancier (YYYY-MM-DD) requis', 400);
+        exit;
+    }
+    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateDebut)) {
+        sendError('date_debut_echeancier invalide (YYYY-MM-DD)', 400);
+        exit;
+    }
+
+    if (isMockMode()) {
+        $echeanciers = loadMock('echeanciers');
+        foreach ($echeanciers as $e) {
+            if ((int) $e['facture_id'] === $factureId) {
+                sendError('Cette facture a déjà un écheancier', 400);
+                exit;
+            }
+        }
+        $factures = loadMock('factures');
+        $paiements = loadMock('paiements');
+        $facture = null;
+        foreach ($factures as $f) {
+            if ((int) $f['id'] === $factureId) { $facture = $f; break; }
+        }
+        if (!$facture) {
+            sendError('Facture introuvable', 404);
+            exit;
+        }
+        // Calculer l'encours actuel
+        $totalPaye = 0;
+        foreach ($paiements as $p) {
+            if ((int) $p['facture_id'] === $factureId) {
+                $totalPaye += (float) $p['montant'];
+            }
+        }
+        $encours = max(0, (float) $facture['montant_ht'] - $totalPaye);
+        if ($encours <= 0.01) {
+            sendError('La facture est déjà soldée (encours = 0)', 400);
+            exit;
+        }
+        $montantParEcheance = round($encours / $nbEcheances, 2);
+        $newId = 1;
+        foreach ($echeanciers as $e) {
+            if ((int) $e['id'] >= $newId) $newId = (int) $e['id'] + 1;
+        }
+        $row = [
+            'id' => $newId,
+            'facture_id' => $factureId,
+            'nb_echeances' => $nbEcheances,
+            'date_debut_echeancier' => $dateDebut,
+            'montant_par_echeance' => $montantParEcheance,
+            'created_at' => (new DateTime())->format(DateTime::ATOM),
+        ];
+        $echeanciers[] = $row;
+        saveMock('echeanciers', $echeanciers);
+        sendJson($row);
+        exit;
+    }
+
+    $pdo = getPdo();
+    // Vérifier que la facture n'a pas déjà un écheancier
+    $stmt = $pdo->prepare('SELECT id FROM echeanciers WHERE facture_id = ?');
+    $stmt->execute([$factureId]);
+    if ($stmt->fetch()) {
+        sendError('Cette facture a déjà un écheancier', 400);
+        exit;
+    }
+    // Vérifier que la facture existe et calculer l'encours
+    $stmt = $pdo->prepare('
+        SELECT f.id, f.montant_ht,
+               COALESCE(SUM(p.montant), 0) AS total_paye
+        FROM factures f
+        LEFT JOIN paiements p ON p.facture_id = f.id
+        WHERE f.id = ?
+        GROUP BY f.id, f.montant_ht
+    ');
+    $stmt->execute([$factureId]);
+    $facture = $stmt->fetch();
+    if (!$facture) {
+        sendError('Facture introuvable', 404);
+        exit;
+    }
+    $encours = max(0, (float) $facture['montant_ht'] - (float) $facture['total_paye']);
+    if ($encours <= 0.01) {
+        sendError('La facture est déjà soldée (encours = 0)', 400);
+        exit;
+    }
+    $montantParEcheance = round($encours / $nbEcheances, 2);
+    // Insérer l'écheancier avec le montant calculé
+    $stmt = $pdo->prepare('INSERT INTO echeanciers (facture_id, nb_echeances, date_debut_echeancier, montant_par_echeance) VALUES (?, ?, ?, ?)');
+    $stmt->execute([$factureId, $nbEcheances, $dateDebut, $montantParEcheance]);
+    $id = (int) $pdo->lastInsertId();
+    $stmt = $pdo->prepare('SELECT id, facture_id, nb_echeances, date_debut_echeancier, montant_par_echeance, created_at FROM echeanciers WHERE id = ?');
+    $stmt->execute([$id]);
+    $row = $stmt->fetch();
+    $row['montant_par_echeance'] = (float) $row['montant_par_echeance'];
+    $row['created_at'] = $row['created_at'] ? (new DateTime($row['created_at']))->format(DateTime::ATOM) : null;
+    sendJson($row);
+    exit;
+}
+
+if ($method === 'DELETE') {
+    $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
+    if ($id <= 0) {
+        sendError('id requis', 400);
+        exit;
+    }
+
+    if (isMockMode()) {
+        $echeanciers = loadMock('echeanciers');
+        $found = false;
+        foreach ($echeanciers as $i => $e) {
+            if ((int) $e['id'] === $id) {
+                unset($echeanciers[$i]);
+                $echeanciers = array_values($echeanciers);
+                saveMock('echeanciers', $echeanciers);
+                sendJson(['success' => true, 'id' => $id]);
+                exit;
+            }
+        }
+        sendError('Écheancier non trouvé', 404);
+        exit;
+    }
+
+    $pdo = getPdo();
+    $stmt = $pdo->prepare('DELETE FROM echeanciers WHERE id = ?');
+    $stmt->execute([$id]);
+    if ($stmt->rowCount() === 0) {
+        sendError('Écheancier non trouvé', 404);
+        exit;
+    }
+    sendJson(['success' => true, 'id' => $id]);
+    exit;
+}
+
+if ($method !== 'GET') {
+    sendError('Méthode non autorisée', 405);
+    exit;
+}
+
+$clientId = isset($_GET['client_id']) ? (int) $_GET['client_id'] : 0;
+$factureId = isset($_GET['facture_id']) ? (int) $_GET['facture_id'] : 0;
+
+if ($clientId <= 0 && $factureId <= 0) {
+    sendError('client_id ou facture_id requis', 400);
+    exit;
+}
+
+if (isMockMode()) {
+    $echeanciers = loadMock('echeanciers');
+    $factures = loadMock('factures');
+    if ($factureId > 0) {
+        $echeanciers = array_filter($echeanciers, fn($e) => (int) $e['facture_id'] === $factureId);
+    } else {
+        $factureIds = array_column(array_filter($factures, fn($f) => (int) $f['client_id'] === $clientId), 'id');
+        $echeanciers = array_filter($echeanciers, fn($e) => in_array((int) $e['facture_id'], $factureIds));
+    }
+    sendJson(array_values($echeanciers));
+    exit;
+}
+
+$pdo = getPdo();
+if ($factureId > 0) {
+    $stmt = $pdo->prepare('SELECT id, facture_id, nb_echeances, date_debut_echeancier, montant_par_echeance, created_at FROM echeanciers WHERE facture_id = ?');
+    $stmt->execute([$factureId]);
+} else {
+    $stmt = $pdo->prepare('
+        SELECT e.id, e.facture_id, e.nb_echeances, e.date_debut_echeancier, e.montant_par_echeance, e.created_at
+        FROM echeanciers e
+        INNER JOIN factures f ON f.id = e.facture_id
+        WHERE f.client_id = ?
+    ');
+    $stmt->execute([$clientId]);
+}
+$rows = $stmt->fetchAll();
+foreach ($rows as &$r) {
+    $r['montant_par_echeance'] = (float) $r['montant_par_echeance'];
+    $r['created_at'] = $r['created_at'] ? (new DateTime($r['created_at']))->format(DateTime::ATOM) : null;
+}
+sendJson($rows);

+ 243 - 0
app/api/factures.php

@@ -0,0 +1,243 @@
+<?php
+/**
+ * API Factures - liste par client (FR3), ajout manuel (FR3b).
+ * La facturation provient de Pennylane ; l’API sert au suivi (saisie manuelle des factures).
+ * GET ?client_id= | POST pour ajouter une facture (suivi).
+ */
+require_once __DIR__ . '/config.php';
+
+header('Access-Control-Allow-Origin: *');
+header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
+header('Access-Control-Allow-Headers: Content-Type');
+
+$method = $_SERVER['REQUEST_METHOD'] ?? '';
+
+if ($method === 'POST') {
+    $input = json_decode(file_get_contents('php://input'), true) ?? [];
+    $clientId = isset($input['client_id']) ? (int) $input['client_id'] : 0;
+    $nFacture = isset($input['n_facture']) ? trim($input['n_facture']) : '';
+    $nVente = isset($input['n_vente']) ? trim($input['n_vente']) : '';
+    $dateFacture = isset($input['date_facture']) ? trim($input['date_facture']) : date('Y-m-d');
+    $typeProduit = isset($input['type_produit']) ? trim($input['type_produit']) : null;
+    $cycle = isset($input['cycle']) ? trim($input['cycle']) : null;
+    $quantites = isset($input['quantites']) ? (float) $input['quantites'] : null;
+    $qteLivree = isset($input['qte_livree']) ? (float) $input['qte_livree'] : null;
+    $montantHt = isset($input['montant_ht']) ? (float) $input['montant_ht'] : 0;
+
+    if ($clientId <= 0 || $nFacture === '' || $montantHt <= 0) {
+        sendError('client_id, n_facture et montant_ht (positif) requis', 400);
+        exit;
+    }
+    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateFacture)) {
+        sendError('date_facture invalide (YYYY-MM-DD)', 400);
+        exit;
+    }
+
+    if (isMockMode()) {
+        $factures = loadMock('factures');
+        $newId = 1;
+        foreach ($factures as $f) {
+            if ((int) $f['id'] >= $newId) $newId = (int) $f['id'] + 1;
+        }
+        $row = [
+            'id' => $newId,
+            'client_id' => $clientId,
+            'n_facture' => $nFacture,
+            'n_vente' => $nVente ?: null,
+            'date_facture' => $dateFacture,
+            'type_produit' => $typeProduit ?: null,
+            'cycle' => $cycle ?: null,
+            'quantites' => $quantites,
+            'qte_livree' => $qteLivree,
+            'montant_ht' => $montantHt,
+            'created_at' => (new DateTime())->format(DateTime::ATOM),
+        ];
+        $factures[] = $row;
+        saveMock('factures', $factures);
+        sendJson($row);
+        exit;
+    }
+
+    $pdo = getPdo();
+    $stmt = $pdo->prepare('INSERT INTO factures (client_id, n_facture, n_vente, date_facture, type_produit, cycle, quantites, qte_livree, montant_ht) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
+    $stmt->execute([$clientId, $nFacture, $nVente ?: null, $dateFacture, $typeProduit ?: null, $cycle ?: null, $quantites, $qteLivree, $montantHt]);
+    $id = (int) $pdo->lastInsertId();
+    $stmt = $pdo->prepare('SELECT id, client_id, n_facture, n_vente, date_facture, type_produit, cycle, quantites, qte_livree, montant_ht, created_at FROM factures WHERE id = ?');
+    $stmt->execute([$id]);
+    $row = $stmt->fetch();
+    $row['montant_ht'] = (float) $row['montant_ht'];
+    $row['quantites'] = $row['quantites'] !== null ? (float) $row['quantites'] : null;
+    $row['qte_livree'] = $row['qte_livree'] !== null ? (float) $row['qte_livree'] : null;
+    $row['created_at'] = $row['created_at'] ? (new DateTime($row['created_at']))->format(DateTime::ATOM) : null;
+    sendJson($row);
+    exit;
+}
+
+if ($method === 'PUT') {
+    $input = json_decode(file_get_contents('php://input'), true) ?? [];
+    $id = isset($input['id']) ? (int) $input['id'] : 0;
+    $nFacture = isset($input['n_facture']) ? trim($input['n_facture']) : '';
+    $nVente = isset($input['n_vente']) ? trim($input['n_vente']) : '';
+    $dateFacture = isset($input['date_facture']) ? trim($input['date_facture']) : '';
+    $typeProduit = isset($input['type_produit']) ? trim($input['type_produit']) : null;
+    $cycle = isset($input['cycle']) ? trim($input['cycle']) : null;
+    $quantites = isset($input['quantites']) ? (float) $input['quantites'] : null;
+    $qteLivree = isset($input['qte_livree']) ? (float) $input['qte_livree'] : null;
+    $montantHt = isset($input['montant_ht']) ? (float) $input['montant_ht'] : 0;
+
+    if ($id <= 0 || $nFacture === '' || $montantHt <= 0) {
+        sendError('id, n_facture et montant_ht (positif) requis', 400);
+        exit;
+    }
+    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateFacture)) {
+        sendError('date_facture invalide (YYYY-MM-DD)', 400);
+        exit;
+    }
+
+    if (isMockMode()) {
+        $factures = loadMock('factures');
+        $found = false;
+        foreach ($factures as &$f) {
+            if ((int) $f['id'] === $id) {
+                $f['n_facture'] = $nFacture;
+                $f['n_vente'] = $nVente ?: null;
+                $f['date_facture'] = $dateFacture;
+                $f['type_produit'] = $typeProduit ?: null;
+                $f['cycle'] = $cycle ?: null;
+                $f['quantites'] = $quantites;
+                $f['qte_livree'] = $qteLivree;
+                $f['montant_ht'] = $montantHt;
+                $found = true;
+                saveMock('factures', $factures);
+                sendJson($f);
+                exit;
+            }
+        }
+        if (!$found) {
+            sendError('Facture non trouvée', 404);
+            exit;
+        }
+    }
+
+    $pdo = getPdo();
+    $stmt = $pdo->prepare('UPDATE factures SET n_facture = ?, n_vente = ?, date_facture = ?, type_produit = ?, cycle = ?, quantites = ?, qte_livree = ?, montant_ht = ? WHERE id = ?');
+    $stmt->execute([$nFacture, $nVente ?: null, $dateFacture, $typeProduit ?: null, $cycle ?: null, $quantites, $qteLivree, $montantHt, $id]);
+    $stmt = $pdo->prepare('SELECT id, client_id, n_facture, n_vente, date_facture, type_produit, cycle, quantites, qte_livree, montant_ht, created_at FROM factures WHERE id = ?');
+    $stmt->execute([$id]);
+    $row = $stmt->fetch();
+    if (!$row) {
+        sendError('Facture non trouvée', 404);
+        exit;
+    }
+    $row['montant_ht'] = (float) $row['montant_ht'];
+    $row['quantites'] = $row['quantites'] !== null ? (float) $row['quantites'] : null;
+    $row['qte_livree'] = $row['qte_livree'] !== null ? (float) $row['qte_livree'] : null;
+    $row['created_at'] = $row['created_at'] ? (new DateTime($row['created_at']))->format(DateTime::ATOM) : null;
+    sendJson($row);
+    exit;
+}
+
+if ($method === 'DELETE') {
+    $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
+    if ($id <= 0) {
+        sendError('id requis', 400);
+        exit;
+    }
+
+    if (isMockMode()) {
+        $factures = loadMock('factures');
+        $found = false;
+        foreach ($factures as $i => $f) {
+            if ((int) $f['id'] === $id) {
+                unset($factures[$i]);
+                $factures = array_values($factures);
+                saveMock('factures', $factures);
+                sendJson(['success' => true, 'id' => $id]);
+                exit;
+            }
+        }
+        sendError('Facture non trouvée', 404);
+        exit;
+    }
+
+    $pdo = getPdo();
+    $stmt = $pdo->prepare('DELETE FROM factures WHERE id = ?');
+    $stmt->execute([$id]);
+    if ($stmt->rowCount() === 0) {
+        sendError('Facture non trouvée', 404);
+        exit;
+    }
+    sendJson(['success' => true, 'id' => $id]);
+    exit;
+}
+
+if ($method !== 'GET') {
+    sendError('Méthode non autorisée', 405);
+    exit;
+}
+
+$clientId = isset($_GET['client_id']) ? (int) $_GET['client_id'] : 0;
+if ($clientId <= 0) {
+    sendError('client_id requis', 400);
+    exit;
+}
+
+if (isMockMode()) {
+    $factures = array_filter(loadMock('factures'), fn($f) => (int) $f['client_id'] === $clientId);
+    $paiements = loadMock('paiements');
+    $rows = [];
+    foreach ($factures as $f) {
+        $totalPaye = 0;
+        foreach ($paiements as $p) {
+            if ((int) $p['facture_id'] === (int) $f['id']) {
+                $totalPaye += (float) $p['montant'];
+            }
+        }
+        $montantHt = (float) $f['montant_ht'];
+        $encours = max(0, $montantHt - $totalPaye);
+        $rows[] = [
+            'id' => (int) $f['id'],
+            'client_id' => (int) $f['client_id'],
+            'n_facture' => $f['n_facture'],
+            'n_vente' => $f['n_vente'] ?? null,
+            'date_facture' => $f['date_facture'],
+            'type_produit' => $f['type_produit'] ?? null,
+            'cycle' => $f['cycle'] ?? null,
+            'quantites' => isset($f['quantites']) ? (float) $f['quantites'] : null,
+            'qte_livree' => isset($f['qte_livree']) ? (float) $f['qte_livree'] : null,
+            'montant_ht' => $montantHt,
+            'created_at' => $f['created_at'] ?? null,
+            'total_paye' => $totalPaye,
+            'encours_facture' => $encours,
+            'etat' => $encours <= 0 ? 'paye' : 'en_attente',
+        ];
+    }
+    usort($rows, fn($a, $b) => strcmp($b['date_facture'], $a['date_facture']));
+    sendJson($rows);
+    exit;
+}
+
+$pdo = getPdo();
+    $stmt = $pdo->prepare("
+        SELECT f.id, f.client_id, f.n_facture, f.n_vente, f.date_facture, f.type_produit, f.cycle, f.quantites, f.qte_livree, f.montant_ht, f.created_at,
+               COALESCE(SUM(p.montant), 0) AS total_paye,
+               GREATEST(0, f.montant_ht - COALESCE(SUM(p.montant), 0)) AS encours_facture
+        FROM factures f
+        LEFT JOIN paiements p ON p.facture_id = f.id
+        WHERE f.client_id = ?
+        GROUP BY f.id
+        ORDER BY f.date_facture DESC
+    ");
+$stmt->execute([$clientId]);
+$rows = $stmt->fetchAll();
+
+foreach ($rows as &$r) {
+    $r['total_paye'] = (float) $r['total_paye'];
+    $r['montant_ht'] = (float) $r['montant_ht'];
+    $r['quantites'] = $r['quantites'] !== null ? (float) $r['quantites'] : null;
+    $r['qte_livree'] = $r['qte_livree'] !== null ? (float) $r['qte_livree'] : null;
+    $r['encours_facture'] = (float) $r['encours_facture'];
+    $r['etat'] = $r['encours_facture'] <= 0.01 ? 'paye' : 'en_attente';
+    $r['created_at'] = $r['created_at'] ? (new DateTime($r['created_at']))->format(DateTime::ATOM) : null;
+}
+sendJson($rows);

+ 160 - 0
app/api/paiements.php

@@ -0,0 +1,160 @@
+<?php
+/**
+ * API Paiements - liste par client (FR5) et enregistrement (FR4).
+ * GET ?client_id= | POST facture_id, montant, date_paiement
+ */
+require_once __DIR__ . '/config.php';
+
+header('Access-Control-Allow-Origin: *');
+header('Access-Control-Allow-Methods: GET, POST, DELETE');
+header('Access-Control-Allow-Headers: Content-Type');
+
+$method = $_SERVER['REQUEST_METHOD'] ?? '';
+
+if ($method === 'GET') {
+    $clientId = isset($_GET['client_id']) ? (int) $_GET['client_id'] : 0;
+    if ($clientId <= 0) {
+        sendError('client_id requis', 400);
+        exit;
+    }
+    if (isMockMode()) {
+        $factures = loadMock('factures');
+        $factureIds = array_column(array_filter($factures, fn($f) => (int) $f['client_id'] === $clientId), 'id');
+        $paiements = loadMock('paiements');
+        $rows = [];
+        foreach ($paiements as $p) {
+            if (in_array((int) $p['facture_id'], $factureIds)) {
+                $nFacture = '';
+                foreach ($factures as $f) {
+                    if ((int) $f['id'] === (int) $p['facture_id']) {
+                        $nFacture = $f['n_facture'];
+                        break;
+                    }
+                }
+                $rows[] = [
+                    'id' => (int) $p['id'],
+                    'facture_id' => (int) $p['facture_id'],
+                    'montant' => (float) $p['montant'],
+                    'date_paiement' => $p['date_paiement'],
+                    'created_at' => $p['created_at'] ?? null,
+                    'n_facture' => $nFacture,
+                ];
+            }
+        }
+        usort($rows, fn($a, $b) => strcmp($b['date_paiement'], $a['date_paiement']));
+        sendJson($rows);
+        exit;
+    }
+    $pdo = getPdo();
+    $stmt = $pdo->prepare("
+        SELECT p.id, p.facture_id, p.montant, p.date_paiement, p.created_at, f.n_facture
+        FROM paiements p
+        JOIN factures f ON f.id = p.facture_id
+        WHERE f.client_id = ?
+        ORDER BY p.date_paiement DESC
+    ");
+    $stmt->execute([$clientId]);
+    $rows = $stmt->fetchAll();
+    foreach ($rows as &$r) {
+        $r['montant'] = (float) $r['montant'];
+        $r['date_paiement'] = $r['date_paiement'];
+        $r['created_at'] = $r['created_at'] ? (new DateTime($r['created_at']))->format(DateTime::ATOM) : null;
+    }
+    sendJson($rows);
+    exit;
+}
+
+if ($method === 'POST') {
+    $input = json_decode(file_get_contents('php://input'), true) ?? [];
+    $factureId = isset($input['facture_id']) ? (int) $input['facture_id'] : 0;
+    $montant = isset($input['montant']) ? (float) $input['montant'] : 0;
+    $datePaiement = isset($input['date_paiement']) ? trim($input['date_paiement']) : date('Y-m-d');
+
+    if ($factureId <= 0 || $montant <= 0) {
+        sendError('facture_id et montant (positif) requis', 400);
+        exit;
+    }
+    
+    // Vérifier que la facture existe (bonne pratique ERP)
+    if (!isMockMode()) {
+        $pdo = getPdo();
+        $stmt = $pdo->prepare('SELECT id FROM factures WHERE id = ?');
+        $stmt->execute([$factureId]);
+        if (!$stmt->fetch()) {
+            sendError('Facture introuvable', 404);
+            exit;
+        }
+    }
+    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $datePaiement)) {
+        sendError('date_paiement invalide (YYYY-MM-DD)', 400);
+        exit;
+    }
+
+    if (isMockMode()) {
+        $paiements = loadMock('paiements');
+        $newId = 1;
+        foreach ($paiements as $p) {
+            if ((int) $p['id'] >= $newId) $newId = (int) $p['id'] + 1;
+        }
+        $now = (new DateTime())->format(DateTime::ATOM);
+        $row = [
+            'id' => $newId,
+            'facture_id' => $factureId,
+            'montant' => $montant,
+            'date_paiement' => $datePaiement,
+            'created_at' => $now,
+        ];
+        $paiements[] = $row;
+        saveMock('paiements', $paiements);
+        sendJson($row);
+        exit;
+    }
+
+    $pdo = getPdo();
+    $stmt = $pdo->prepare('INSERT INTO paiements (facture_id, montant, date_paiement) VALUES (?, ?, ?)');
+    $stmt->execute([$factureId, $montant, $datePaiement]);
+    $id = (int) $pdo->lastInsertId();
+    $stmt = $pdo->prepare('SELECT id, facture_id, montant, date_paiement, created_at FROM paiements WHERE id = ?');
+    $stmt->execute([$id]);
+    $row = $stmt->fetch();
+    $row['montant'] = (float) $row['montant'];
+    $row['created_at'] = $row['created_at'] ? (new DateTime($row['created_at']))->format(DateTime::ATOM) : null;
+    sendJson($row);
+    exit;
+}
+
+if ($method === 'DELETE') {
+    $id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
+    if ($id <= 0) {
+        sendError('id requis', 400);
+        exit;
+    }
+
+    if (isMockMode()) {
+        $paiements = loadMock('paiements');
+        $found = false;
+        foreach ($paiements as $i => $p) {
+            if ((int) $p['id'] === $id) {
+                unset($paiements[$i]);
+                $paiements = array_values($paiements);
+                saveMock('paiements', $paiements);
+                sendJson(['success' => true, 'id' => $id]);
+                exit;
+            }
+        }
+        sendError('Paiement non trouvé', 404);
+        exit;
+    }
+
+    $pdo = getPdo();
+    $stmt = $pdo->prepare('DELETE FROM paiements WHERE id = ?');
+    $stmt->execute([$id]);
+    if ($stmt->rowCount() === 0) {
+        sendError('Paiement non trouvé', 404);
+        exit;
+    }
+    sendJson(['success' => true, 'id' => $id]);
+    exit;
+}
+
+sendError('Méthode non autorisée', 405);

+ 82 - 0
app/api/quantites-clients.php

@@ -0,0 +1,82 @@
+<?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,
+]);

+ 386 - 0
app/api/reporting.php

@@ -0,0 +1,386 @@
+<?php
+/**
+ * API Reporting - tableau de bord et export (FR10, FR11).
+ * GET ?format=json (défaut) | ?format=csv pour export.
+ */
+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;
+}
+
+$format = isset($_GET['format']) ? strtolower(trim($_GET['format'])) : 'json';
+
+if (isMockMode()) {
+    $clients = loadMock('clients');
+    $factures = loadMock('factures');
+    $paiements = loadMock('paiements');
+    $encoursParClient = [];
+    foreach ($clients as $c) {
+        $cid = (int) $c['id'];
+        $totalF = 0;
+        $totalP = 0;
+        foreach ($factures as $f) {
+            if ((int) $f['client_id'] === $cid) {
+                $totalF += (float) $f['montant_ht'];
+                foreach ($paiements as $p) {
+                    if ((int) $p['facture_id'] === (int) $f['id']) $totalP += (float) $p['montant'];
+                }
+            }
+        }
+        $enc = $totalF - $totalP;
+        if ($enc > 0) {
+            $encoursParClient[] = ['client_id' => $cid, 'nom' => $c['nom'], 'encours' => $enc];
+        }
+    }
+    usort($encoursParClient, fn($a, $b) => $a['encours'] <=> $b['encours']);
+    $encoursTotal = array_sum(array_column($encoursParClient, 'encours'));
+    $delaiMoyenJ = null;
+    $nbPaiements = 0;
+    $sommeJours = 0;
+    foreach ($paiements as $p) {
+        foreach ($factures as $f) {
+            if ((int) $f['id'] === (int) $p['facture_id']) {
+                $d = (new DateTime($p['date_paiement']))->diff(new DateTime($f['date_facture']))->days;
+                $sommeJours += $d;
+                $nbPaiements++;
+                break;
+            }
+        }
+    }
+    if ($nbPaiements > 0) {
+        $delaiMoyenJ = (int) round($sommeJours / $nbPaiements);
+    }
+    // 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) {
+        $tp = 0;
+        foreach ($paiements as $p) {
+            if ((int) $p['facture_id'] === (int) $f['id']) $tp += (float) $p['montant'];
+        }
+        $enc = (float) $f['montant_ht'] - $tp;
+        if ($enc > 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 ? $enc / $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' => $enc,
+                        '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' => $enc,
+                    'encours_facture' => $enc,
+                    '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);
+    
+    if ($format === 'csv') {
+        header('Content-Type: text/csv; charset=utf-8');
+        header('Content-Disposition: attachment; filename=reporting-encours-' . date('Y-m-d') . '.csv');
+        $out = fopen('php://output', 'w');
+        fprintf($out, "\xEF\xBB\xBF");
+        fputcsv($out, ['client_id', 'nom', 'encours'], ';');
+        foreach ($encoursParClient as $r) {
+            fputcsv($out, [$r['client_id'], $r['nom'], $r['encours']], ';');
+        }
+        fclose($out);
+        exit;
+    }
+    if ($format === 'factures_csv') {
+        header('Content-Type: text/csv; charset=utf-8');
+        header('Content-Disposition: attachment; filename=suivi-factures-' . date('Y-m-d') . '.csv');
+        $out = fopen('php://output', 'w');
+        fprintf($out, "\xEF\xBB\xBF");
+        // En-têtes alignés sur l’onglet Factures Excel (EMGI_FTI_Suivi des Ventes) + Total payé, Encours
+        $headers = ['EXO', 'Mois', 'CLIENT', 'PAYS', 'DEPART DEM', 'NEG.', 'TYPE', 'CYCLE', 'produc', 'PAI', 'DATE FACTUR', 'N° DE VENTE', 'N° FACTURE', 'QTE FACT', 'QTE LIVREE', '% GT', 'CA FACTURE HT', 'PU', 'Total payé', 'Encours'];
+        fputcsv($out, $headers, ';');
+        foreach ($factures as $f) {
+            $nom = '';
+            foreach ($clients as $c) {
+                if ((int) $c['id'] === (int) $f['client_id']) { $nom = $c['nom']; break; }
+            }
+            $tp = 0;
+            foreach ($paiements as $p) {
+                if ((int) $p['facture_id'] === (int) $f['id']) $tp += (float) $p['montant'];
+            }
+            $enc = (float) $f['montant_ht'] - $tp;
+            $cycle = $f['cycle'] ?? '';
+            $exo = $cycle ? str_replace('-', '/', $cycle) : ''; // 25-26 -> 25/26
+            $typeLabel = isset($f['type_produit']) ? (stripos($f['type_produit'], 'alevin') !== false ? 'Alevin Bar' : (stripos($f['type_produit'], 'larve') !== false ? 'Larve Bar' : $f['type_produit'])) : '';
+            $dateFactur = !empty($f['date_facture']) ? (new DateTime($f['date_facture']))->format('d/m/Y') : '';
+            $qteFact = $f['quantites'] ?? '';
+            $qteLivree = $f['qte_livree'] ?? '';
+            $caHt = $f['montant_ht'] ?? '';
+            $pu = '';
+            if (!empty($qteFact) && (float) $qteFact > 0 && $caHt !== '') {
+                $pu = number_format((float) $caHt / (float) $qteFact, 2, ',', ' ');
+            }
+            if (is_numeric($caHt)) $caHt = number_format((float) $caHt, 2, ',', ' ');
+            if (is_numeric($qteFact)) $qteFact = number_format((float) $qteFact, 0, ',', ' ');
+            if (is_numeric($qteLivree)) $qteLivree = number_format((float) $qteLivree, 0, ',', ' ');
+            if (is_numeric($tp)) $tp = number_format((float) $tp, 2, ',', ' ');
+            if (is_numeric($enc)) $enc = number_format((float) $enc, 2, ',', ' ');
+            fputcsv($out, [
+                $exo,
+                '', // Mois (non géré dans l’appli)
+                $nom,
+                '', // PAYS
+                'EMGI', // DEPART DEM
+                $typeLabel,
+                $typeLabel,
+                $cycle,
+                '', // produc
+                '', // PAI
+                $dateFactur,
+                $f['n_vente'] ?? '',
+                $f['n_facture'] ?? '',
+                $qteFact,
+                $qteLivree,
+                '', // % GT
+                $caHt,
+                $pu,
+                $tp,
+                $enc,
+            ], ';');
+        }
+        fclose($out);
+        exit;
+    }
+    sendJson([
+        'date_rapport' => date('Y-m-d'),
+        'encours_total' => $encoursTotal,
+        'encours_par_client' => $encoursParClient,
+        'delai_moyen_paiement_j' => $delaiMoyenJ,
+        'echeances_a_venir' => $echeances,
+    ]);
+    exit;
+}
+
+$pdo = getPdo();
+$stmt = $pdo->query("
+    SELECT c.id AS client_id, c.nom,
+           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
+");
+$encoursParClient = $stmt->fetchAll();
+
+// 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();
+
+$encoursTotal = 0;
+foreach ($encoursParClient as &$r) {
+    $r['encours'] = (float) $r['encours'];
+    $encoursTotal += $r['encours'];
+}
+$delaiMoyenJ = null;
+$stmtDelai = $pdo->query("
+    SELECT AVG(DATEDIFF(p.date_paiement, f.date_facture)) AS delai_moyen
+    FROM paiements p
+    JOIN factures f ON f.id = p.facture_id
+");
+$rowDelai = $stmtDelai->fetch();
+if ($rowDelai && $rowDelai['delai_moyen'] !== null) {
+    $delaiMoyenJ = (int) round((float) $rowDelai['delai_moyen']);
+}
+
+// Calculer les échéances à partir des écheanciers
+$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);
+
+if ($format === 'csv') {
+    header('Content-Type: text/csv; charset=utf-8');
+    header('Content-Disposition: attachment; filename=reporting-encours-' . date('Y-m-d') . '.csv');
+    $out = fopen('php://output', 'w');
+    fprintf($out, "\xEF\xBB\xBF"); // BOM UTF-8
+    fputcsv($out, ['client_id', 'nom', 'encours'], ';');
+    foreach ($encoursParClient as $r) {
+        fputcsv($out, [$r['client_id'], $r['nom'], $r['encours']], ';');
+    }
+    fclose($out);
+    exit;
+}
+
+if ($format === 'factures_csv') {
+    $stmtF = $pdo->query("
+        SELECT f.id, f.client_id, c.nom, f.n_facture, f.n_vente, f.date_facture, f.type_produit, f.cycle, f.quantites, f.qte_livree, f.montant_ht,
+               COALESCE(SUM(p.montant), 0) AS total_paye
+        FROM factures f
+        JOIN clients c ON c.id = f.client_id
+        LEFT JOIN paiements p ON p.facture_id = f.id
+        GROUP BY f.id, f.client_id, c.nom, f.n_facture, f.n_vente, f.date_facture, f.type_produit, f.cycle, f.quantites, f.qte_livree, f.montant_ht
+        ORDER BY f.date_facture DESC, c.nom
+    ");
+    $allFactures = $stmtF->fetchAll();
+    header('Content-Type: text/csv; charset=utf-8');
+    header('Content-Disposition: attachment; filename=suivi-factures-' . date('Y-m-d') . '.csv');
+    $out = fopen('php://output', 'w');
+    fprintf($out, "\xEF\xBB\xBF");
+    // En-têtes alignés sur l’onglet Factures Excel (EMGI_FTI_Suivi des Ventes) + Total payé, Encours
+    $headers = ['EXO', 'Mois', 'CLIENT', 'PAYS', 'DEPART DEM', 'NEG.', 'TYPE', 'CYCLE', 'produc', 'PAI', 'DATE FACTUR', 'N° DE VENTE', 'N° FACTURE', 'QTE FACT', 'QTE LIVREE', '% GT', 'CA FACTURE HT', 'PU', 'Total payé', 'Encours'];
+    fputcsv($out, $headers, ';');
+    foreach ($allFactures as $f) {
+        $totalPaye = (float) $f['total_paye'];
+        $enc = (float) $f['montant_ht'] - $totalPaye;
+        $cycle = $f['cycle'] ?? '';
+        $exo = $cycle ? str_replace('-', '/', $cycle) : '';
+        $typeLabel = isset($f['type_produit']) ? (stripos($f['type_produit'], 'alevin') !== false ? 'Alevin Bar' : (stripos($f['type_produit'], 'larve') !== false ? 'Larve Bar' : $f['type_produit'])) : '';
+        $dateFactur = !empty($f['date_facture']) ? (new DateTime($f['date_facture']))->format('d/m/Y') : '';
+        $qteFact = $f['quantites'] ?? '';
+        $qteLivree = $f['qte_livree'] ?? '';
+        $caHt = $f['montant_ht'];
+        $pu = '';
+        if ($qteFact !== '' && $qteFact !== null && (float) $qteFact > 0) {
+            $pu = number_format((float) $caHt / (float) $qteFact, 2, ',', ' ');
+        }
+        $caHt = number_format((float) $caHt, 2, ',', ' ');
+        if ($qteFact !== '' && $qteFact !== null) $qteFact = number_format((float) $qteFact, 0, ',', ' ');
+        if ($qteLivree !== '' && $qteLivree !== null) $qteLivree = number_format((float) $qteLivree, 0, ',', ' ');
+        $totalPayeStr = number_format($totalPaye, 2, ',', ' ');
+        $encStr = number_format($enc, 2, ',', ' ');
+        fputcsv($out, [
+            $exo,
+            '',
+            $f['nom'],
+            '',
+            'EMGI',
+            $typeLabel,
+            $typeLabel,
+            $cycle ?? '',
+            '',
+            '',
+            $dateFactur,
+            $f['n_vente'] ?? '',
+            $f['n_facture'],
+            $qteFact,
+            $qteLivree,
+            '',
+            $caHt,
+            $pu,
+            $totalPayeStr,
+            $encStr,
+        ], ';');
+    }
+    fclose($out);
+    exit;
+}
+
+sendJson([
+    'date_rapport' => date('Y-m-d'),
+    'encours_total' => $encoursTotal,
+    'encours_par_client' => $encoursParClient,
+    'delai_moyen_paiement_j' => $delaiMoyenJ,
+    'echeances_a_venir' => $echeances,
+]);

+ 93 - 0
app/api/top-clients.php

@@ -0,0 +1,93 @@
+<?php
+/**
+ * API Top clients par type de produit (FR10b).
+ * GET ?type=alevins|larves & optionnel ?cycle=24-25|25-26
+ */
+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'])) : '';
+$cycle = isset($_GET['cycle']) ? trim($_GET['cycle']) : null;
+if ($type !== 'alevins' && $type !== 'larves') {
+    sendError('type requis: alevins ou larves', 400);
+    exit;
+}
+
+if (isMockMode()) {
+    $clients = loadMock('clients');
+    $factures = loadMock('factures');
+    $byClient = [];
+    foreach ($factures as $f) {
+        $t = $f['type_produit'] ?? '';
+        if (strtolower($t) !== $type) continue;
+        if ($cycle !== null && ($f['cycle'] ?? '') !== $cycle) continue;
+        $cid = (int) $f['client_id'];
+        if (!isset($byClient[$cid])) {
+            $byClient[$cid] = ['client_id' => $cid, 'nom' => '', 'quantites' => 0, 'ca' => 0];
+            foreach ($clients as $c) {
+                if ((int) $c['id'] === $cid) { $byClient[$cid]['nom'] = $c['nom']; break; }
+            }
+        }
+        $byClient[$cid]['quantites'] += (float) ($f['quantites'] ?? 0);
+        $byClient[$cid]['ca'] += (float) $f['montant_ht'];
+    }
+    $rows = array_values($byClient);
+    usort($rows, fn($a, $b) => $b['ca'] <=> $a['ca']);
+    $totalQte = array_sum(array_column($rows, 'quantites'));
+    $totalCa = array_sum(array_column($rows, 'ca'));
+    foreach ($rows as &$r) {
+        $r['pct_qte'] = $totalQte > 0 ? round(100 * $r['quantites'] / $totalQte, 1) : 0;
+        $r['pct_ca'] = $totalCa > 0 ? round(100 * $r['ca'] / $totalCa, 1) : 0;
+    }
+    sendJson([
+        'type' => $type,
+        'cycle' => $cycle,
+        'top_clients' => $rows,
+        'total_quantites' => $totalQte,
+        'total_ca' => $totalCa,
+    ]);
+    exit;
+}
+
+$pdo = getPdo();
+$sql = "
+    SELECT c.id AS client_id, c.nom,
+           SUM(COALESCE(f.quantites, 0)) AS quantites,
+           SUM(f.montant_ht) AS ca
+    FROM clients c
+    JOIN factures f ON f.client_id = c.id
+    WHERE LOWER(TRIM(f.type_produit)) = ?
+";
+$params = [$type];
+if ($cycle !== null && $cycle !== '') {
+    $sql .= " AND TRIM(f.cycle) = ?";
+    $params[] = $cycle;
+}
+$sql .= " GROUP BY c.id, c.nom ORDER BY ca DESC";
+
+$stmt = $pdo->prepare($sql);
+$stmt->execute($params);
+$rows = $stmt->fetchAll();
+$totalQte = array_sum(array_column($rows, 'quantites'));
+$totalCa = array_sum(array_column($rows, 'ca'));
+foreach ($rows as &$r) {
+    $r['quantites'] = (float) $r['quantites'];
+    $r['ca'] = (float) $r['ca'];
+    $r['pct_qte'] = $totalQte > 0 ? round(100 * $r['quantites'] / $totalQte, 1) : 0;
+    $r['pct_ca'] = $totalCa > 0 ? round(100 * $r['ca'] / $totalCa, 1) : 0;
+}
+sendJson([
+    'type' => $type,
+    'cycle' => $cycle,
+    'top_clients' => $rows,
+    'total_quantites' => $totalQte,
+    'total_ca' => $totalCa,
+]);

+ 102 - 0
app/client.html

@@ -0,0 +1,102 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+  <meta charset="UTF-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <title>Détail client - Suivi FTI EMGI</title>
+  <script src="https://cdn.tailwindcss.com"></script>
+</head>
+<body class="bg-gray-50 min-h-screen">
+  <div class="max-w-5xl mx-auto px-4 py-8">
+    <header class="flex justify-between items-center mb-8">
+      <h1 class="text-2xl font-semibold text-gray-800">Suivi FTI EMGI</h1>
+      <nav class="space-x-4">
+        <a href="index.html" class="text-gray-600 hover:text-blue-600">Clients</a>
+        <a href="dashboard.html" class="text-gray-600 hover:text-blue-600">Tableau de bord</a>
+        <a href="top-clients.html" class="text-gray-600 hover:text-blue-600">Top clients</a>
+        <a href="quantites-clients.html" class="text-gray-600 hover:text-blue-600">Quantités</a>
+      </nav>
+    </header>
+
+    <div id="error-message" class="hidden mb-4 p-3 bg-red-100 text-red-700 rounded"></div>
+
+    <div id="client-header" class="mb-8">
+      <p class="text-gray-500">Chargement...</p>
+    </div>
+
+    <section class="bg-white rounded-lg shadow p-6 mb-8">
+      <h2 class="text-lg font-medium text-gray-800 mb-4">Factures</h2>
+      <div id="factures-list" class="overflow-x-auto -mx-2 px-2">Chargement...</div>
+    </section>
+
+    <section class="bg-white rounded-lg shadow p-6 mb-8">
+      <h2 class="text-lg font-medium text-gray-800 mb-4">Ajouter une facture (suivi)</h2>
+      <p class="text-sm text-gray-500 mb-4">La facturation provient de Pennylane ; saisir ici les données pour le suivi (même structure que l’onglet Factures Excel).</p>
+      <form id="form-facture" class="flex flex-wrap gap-4 items-end">
+        <input type="hidden" id="facture_client_id" name="client_id" value="">
+        <div><label for="n_facture" class="block text-sm text-gray-600 mb-1">N° FACTURE</label><input type="text" id="n_facture" name="n_facture" class="border border-gray-300 rounded px-3 py-2" required></div>
+        <div><label for="n_vente" class="block text-sm text-gray-600 mb-1">N° DE VENTE</label><input type="text" id="n_vente" name="n_vente" class="border border-gray-300 rounded px-3 py-2"></div>
+        <div><label for="date_facture" class="block text-sm text-gray-600 mb-1">DATE FACTUR</label><input type="date" id="date_facture" name="date_facture" class="border border-gray-300 rounded px-3 py-2" required></div>
+        <div><label for="type_produit" class="block text-sm text-gray-600 mb-1">TYPE (NEG.)</label><select id="type_produit" name="type_produit" class="border border-gray-300 rounded px-3 py-2"><option value="">—</option><option value="alevins">Alevin Bar</option><option value="larves">Larve Bar</option></select></div>
+        <div><label for="cycle" class="block text-sm text-gray-600 mb-1">CYCLE</label><input type="text" id="cycle" name="cycle" placeholder="24-25 ou 25-26" class="border border-gray-300 rounded px-3 py-2"></div>
+        <div><label for="quantites" class="block text-sm text-gray-600 mb-1">QTE FACT</label><input type="number" id="quantites" name="quantites" step="0.01" min="0" class="border border-gray-300 rounded px-3 py-2" placeholder="Qté facturée"></div>
+        <div><label for="qte_livree" class="block text-sm text-gray-600 mb-1">QTE LIVREE</label><input type="number" id="qte_livree" name="qte_livree" step="0.01" min="0" class="border border-gray-300 rounded px-3 py-2" placeholder="Qté livrée"></div>
+        <div><label for="montant_ht" class="block text-sm text-gray-600 mb-1">CA FACTURE HT (€)</label><input type="number" id="montant_ht" name="montant_ht" step="0.01" min="0.01" class="border border-gray-300 rounded px-3 py-2" required></div>
+        <button type="submit" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700">Ajouter la facture</button>
+      </form>
+    </section>
+
+    <section class="bg-white rounded-lg shadow p-6 mb-8">
+      <h2 class="text-lg font-medium text-gray-800 mb-4">Écheancier de paiement</h2>
+      <p class="text-sm text-gray-500 mb-4">Associer à une facture un plan de paiement échelonné (échéances mensuelles). Le montant de l’encours sera réparti équitablement sur le nombre d’échéances.</p>
+      <div id="echeanciers-list" class="mb-4">—</div>
+      <form id="form-echeancier" class="flex flex-wrap gap-4 items-end">
+        <div>
+          <label for="echeancier_facture_id" class="block text-sm text-gray-600 mb-1">Facture</label>
+          <select id="echeancier_facture_id" name="facture_id" class="border border-gray-300 rounded px-3 py-2 min-w-[200px]" required></select>
+        </div>
+        <div>
+          <label for="nb_echeances" class="block text-sm text-gray-600 mb-1">Nombre d’échéances</label>
+          <input type="number" id="nb_echeances" name="nb_echeances" min="1" class="border border-gray-300 rounded px-3 py-2" required>
+        </div>
+        <div>
+          <label for="date_debut_echeancier" class="block text-sm text-gray-600 mb-1">Date de début</label>
+          <input type="date" id="date_debut_echeancier" name="date_debut_echeancier" class="border border-gray-300 rounded px-3 py-2" required>
+        </div>
+        <button type="submit" class="px-4 py-2 bg-indigo-600 text-white rounded hover:bg-indigo-700">Ajouter l’écheancier</button>
+      </form>
+      <div id="apercu-echeancier"></div>
+    </section>
+
+    <section class="bg-white rounded-lg shadow p-6 mb-8">
+      <h2 class="text-lg font-medium text-gray-800 mb-4">Enregistrer un paiement</h2>
+      <form id="form-paiement" class="flex flex-wrap gap-4 items-end">
+        <div>
+          <label for="facture_id" class="block text-sm text-gray-600 mb-1">Facture</label>
+          <select id="facture_id" name="facture_id" class="border border-gray-300 rounded px-3 py-2 min-w-[200px]" required></select>
+        </div>
+        <div>
+          <label for="montant" class="block text-sm text-gray-600 mb-1">Montant (€)</label>
+          <input type="number" id="montant" name="montant" step="0.01" min="0.01" class="border border-gray-300 rounded px-3 py-2" required>
+        </div>
+        <div>
+          <label for="date_paiement" class="block text-sm text-gray-600 mb-1">Date</label>
+          <input type="date" id="date_paiement" name="date_paiement" class="border border-gray-300 rounded px-3 py-2" required>
+        </div>
+        <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">Enregistrer</button>
+      </form>
+    </section>
+
+    <section class="bg-white rounded-lg shadow p-6 mb-8">
+      <h2 class="text-lg font-medium text-gray-800 mb-4">Paiements</h2>
+      <div id="paiements-list">Chargement...</div>
+    </section>
+  </div>
+
+  <script src="js/utils.js"></script>
+  <script src="js/client-detail.js"></script>
+  <script src="js/facture-form.js"></script>
+  <script src="js/echeancier-form.js"></script>
+  <script src="js/paiements.js"></script>
+</body>
+</html>

+ 43 - 0
app/dashboard.html

@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+  <meta charset="UTF-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <title>Tableau de bord - Suivi FTI EMGI</title>
+  <script src="https://cdn.tailwindcss.com"></script>
+</head>
+<body class="bg-gray-50 min-h-screen">
+  <div class="max-w-5xl mx-auto px-4 py-8">
+    <header class="flex justify-between items-center mb-8">
+      <h1 class="text-2xl font-semibold text-gray-800">Suivi FTI EMGI</h1>
+      <nav class="space-x-4">
+        <a href="index.html" class="text-gray-600 hover:text-blue-600">Clients</a>
+        <a href="dashboard.html" class="text-blue-600 font-medium">Tableau de bord</a>
+        <a href="top-clients.html" class="text-gray-600 hover:text-blue-600">Top clients</a>
+        <a href="quantites-clients.html" class="text-gray-600 hover:text-blue-600">Quantités</a>
+      </nav>
+    </header>
+
+    <div id="error-message" class="hidden mb-4 p-3 bg-red-100 text-red-700 rounded"></div>
+
+    <section class="bg-white rounded-lg shadow overflow-hidden mb-8">
+      <div class="px-6 py-4 border-b border-gray-200 flex flex-wrap justify-between items-center gap-2">
+        <h2 id="titre-encours" class="text-lg font-medium text-gray-800">Encours clients au …</h2>
+        <div class="flex flex-wrap gap-3 text-sm">
+          <a href="api/reporting.php?format=csv" class="text-blue-600 hover:underline">Exporter encours CSV</a>
+          <a href="api/reporting.php?format=factures_csv" class="text-blue-600 hover:underline">Exporter l’ensemble des factures (PJ)</a>
+        </div>
+      </div>
+      <div id="encours-par-client" class="p-6 overflow-x-auto">Chargement...</div>
+      <div id="synthèse-encours" class="px-6 pb-6"></div>
+    </section>
+    <section class="bg-white rounded-lg shadow overflow-hidden mt-8">
+      <h2 class="px-6 py-4 border-b border-gray-200 text-lg font-medium text-gray-800">Échéances à venir</h2>
+      <div id="echeances" class="p-6">Chargement...</div>
+    </section>
+  </div>
+
+  <script src="js/utils.js"></script>
+  <script src="js/dashboard.js"></script>
+</body>
+</html>

+ 128 - 0
app/index.html

@@ -0,0 +1,128 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+  <meta charset="UTF-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <title>Clients - Suivi FTI EMGI</title>
+  <script src="https://cdn.tailwindcss.com"></script>
+</head>
+<body class="bg-gray-50 min-h-screen">
+  <div class="max-w-4xl mx-auto px-4 py-8">
+    <header class="flex justify-between items-center mb-8">
+      <h1 class="text-2xl font-semibold text-gray-800">Suivi FTI EMGI</h1>
+      <nav class="space-x-4">
+        <a href="index.html" class="text-blue-600 font-medium">Clients</a>
+        <a href="dashboard.html" class="text-gray-600 hover:text-blue-600">Tableau de bord</a>
+        <a href="top-clients.html" class="text-gray-600 hover:text-blue-600">Top clients</a>
+        <a href="quantites-clients.html" class="text-gray-600 hover:text-blue-600">Quantités</a>
+      </nav>
+    </header>
+
+    <div id="error-message" class="hidden mb-4 p-3 bg-red-100 text-red-700 rounded"></div>
+
+    <section class="bg-white rounded-lg shadow p-6 mb-6">
+      <h2 class="text-lg font-medium text-gray-800 mb-4">Ajouter un client</h2>
+      <form id="form-client" class="flex gap-4 items-end">
+        <div class="flex-1">
+          <label for="nom_client" class="block text-sm text-gray-600 mb-1">Nom du client</label>
+          <input type="text" id="nom_client" name="nom" class="w-full border border-gray-300 rounded px-3 py-2" placeholder="Ex: AQUANARIA" required>
+        </div>
+        <button type="submit" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700">Ajouter</button>
+      </form>
+    </section>
+
+    <div class="mb-6">
+      <label for="search" class="block text-sm font-medium text-gray-700 mb-1">Rechercher un client</label>
+      <input type="text" id="search" placeholder="Nom du client..." class="w-full max-w-md border border-gray-300 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
+    </div>
+
+    <div id="client-list" class="bg-white rounded-lg shadow overflow-hidden">
+      <table class="min-w-full divide-y divide-gray-200">
+        <thead class="bg-gray-100">
+          <tr>
+            <th class="px-4 py-3 text-left text-xs font-medium text-gray-600 uppercase">Client</th>
+            <th class="px-4 py-3 text-right text-xs font-medium text-gray-600 uppercase">Actions</th>
+          </tr>
+        </thead>
+        <tbody id="client-list-body" class="divide-y divide-gray-200">
+          <tr><td colspan="2" class="px-4 py-6 text-center text-gray-500">Chargement...</td></tr>
+        </tbody>
+      </table>
+    </div>
+  </div>
+
+  <script src="js/utils.js"></script>
+  <script>
+    const listBody = document.getElementById('client-list-body');
+    const searchInput = document.getElementById('search');
+
+    async function loadClients(q = '') {
+      hideError();
+      try {
+        const clients = await apiGet('/clients.php', q ? { q } : {});
+        if (clients.length === 0) {
+          listBody.innerHTML = '<tr><td colspan="2" class="px-4 py-6 text-center text-gray-500">Aucun client trouvé.</td></tr>';
+          return;
+        }
+        listBody.innerHTML = clients.map(c => {
+          const nomEscaped = escapeHtml(c.nom).replace(/'/g, "\\'").replace(/"/g, '&quot;');
+          return `
+          <tr class="hover:bg-gray-50">
+            <td class="px-4 py-3 font-medium text-gray-900">${escapeHtml(c.nom)}</td>
+            <td class="px-4 py-3 text-right">
+              <a href="client.html?id=${c.id}" class="text-blue-600 hover:underline mr-4">Voir le détail</a>
+              <button onclick="deleteClient(${c.id}, ${JSON.stringify(c.nom)})" class="text-red-600 hover:text-red-800" title="Supprimer">
+                <svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
+              </button>
+            </td>
+          </tr>
+        `;
+        }).join('');
+      } catch (e) {
+        showError(e.message);
+        listBody.innerHTML = '<tr><td colspan="2" class="px-4 py-6 text-center text-red-500">Erreur de chargement.</td></tr>';
+      }
+    }
+
+    function escapeHtml(text) {
+      const div = document.createElement('div');
+      div.textContent = text;
+      return div.innerHTML;
+    }
+
+    searchInput.addEventListener('input', () => {
+      const q = searchInput.value.trim();
+      loadClients(q);
+    });
+
+    const formClient = document.getElementById('form-client');
+    formClient.addEventListener('submit', async (e) => {
+      e.preventDefault();
+      hideError();
+      const nom = document.getElementById('nom_client').value.trim();
+      if (!nom) return;
+      try {
+        await apiPost('/clients.php', { nom });
+        document.getElementById('nom_client').value = '';
+        loadClients(searchInput.value.trim());
+      } catch (err) {
+        showError(err.message);
+      }
+    });
+
+    window.deleteClient = async function(clientId, nomClient) {
+      if (!confirm('Êtes-vous sûr de vouloir supprimer le client "' + nomClient + '" ? Cette action supprimera également toutes les factures, paiements et écheanciers associés.')) {
+        return;
+      }
+      try {
+        await apiDelete(`/clients.php?id=${clientId}`);
+        loadClients(searchInput.value.trim());
+      } catch (err) {
+        showError(err.message);
+      }
+    };
+
+    loadClients();
+  </script>
+</body>
+</html>

+ 269 - 0
app/js/client-detail.js

@@ -0,0 +1,269 @@
+/**
+ * Chargement du détail client : en-tête, encours, factures, paiements (FR2, FR3, FR5).
+ */
+(function () {
+  const params = new URLSearchParams(window.location.search);
+  const clientId = parseInt(params.get('id'), 10);
+  if (!clientId) {
+    document.getElementById('client-header').innerHTML = '<p class="text-red-600">ID client manquant.</p>';
+    return;
+  }
+
+  async function loadClient() {
+    hideError();
+    try {
+      const [client, factures, paiements, calculs, echeanciers] = await Promise.all([
+        apiGet('/clients.php', { id: clientId }),
+        apiGet('/factures.php', { client_id: clientId }),
+        apiGet('/paiements.php', { client_id: clientId }),
+        apiGet('/calculs.php', { client_id: clientId }),
+        apiGet('/echeanciers.php', { client_id: clientId }),
+      ]);
+
+      document.getElementById('client-header').innerHTML = `
+        <h2 class="text-xl font-semibold text-gray-900">${escapeHtml(client.nom)}</h2>
+        <p class="text-gray-600 mt-1">Encours : <strong>${formatMoney(calculs.encours)}</strong></p>
+      `;
+
+      const echeancierByFacture = {};
+      (echeanciers || []).forEach(e => { echeancierByFacture[e.facture_id] = e; });
+
+      const facturesList = document.getElementById('factures-list');
+      if (factures.length === 0) {
+        facturesList.innerHTML = '<p class="text-gray-500">Aucune facture.</p>';
+      } else {
+        // Colonnes alignées sur l’onglet Factures Excel (EMGI_FTI_Suivi des Ventes) + Total payé, Encours, État, Écheancier
+        const factureTypeLabel = (tp) => !tp ? '—' : (String(tp).toLowerCase().indexOf('alevin') !== -1 ? 'Alevin Bar' : (String(tp).toLowerCase().indexOf('larve') !== -1 ? 'Larve Bar' : tp));
+        facturesList.innerHTML = `
+          <div class="overflow-x-auto">
+            <table class="min-w-[1000px] w-full text-sm">
+              <thead><tr class="text-left text-gray-600 border-b">
+                <th class="pb-2 pr-2 whitespace-nowrap">EXO</th><th class="pb-2 pr-2 whitespace-nowrap">Mois</th><th class="pb-2 pr-2 whitespace-nowrap">CLIENT</th><th class="pb-2 pr-2 whitespace-nowrap">PAYS</th><th class="pb-2 pr-2 whitespace-nowrap">DEPART DEM</th>
+                <th class="pb-2 pr-2 whitespace-nowrap">NEG.</th><th class="pb-2 pr-2 whitespace-nowrap">TYPE</th><th class="pb-2 pr-2 whitespace-nowrap">CYCLE</th><th class="pb-2 pr-2 whitespace-nowrap">produc</th><th class="pb-2 pr-2 whitespace-nowrap">PAI</th>
+                <th class="pb-2 pr-2 whitespace-nowrap">DATE FACTUR</th><th class="pb-2 pr-2 whitespace-nowrap">N° DE VENTE</th><th class="pb-2 pr-2 whitespace-nowrap">N° FACTURE</th>
+                <th class="pb-2 pr-2 text-right whitespace-nowrap">QTE FACT</th><th class="pb-2 pr-2 text-right whitespace-nowrap">QTE LIVREE</th><th class="pb-2 pr-2 text-right whitespace-nowrap">% GT</th>
+                <th class="pb-2 pr-2 text-right whitespace-nowrap">CA FACTURE HT</th><th class="pb-2 pr-2 text-right whitespace-nowrap">PU</th>
+                <th class="pb-2 pr-2 text-right whitespace-nowrap">Total payé</th><th class="pb-2 pr-2 text-right whitespace-nowrap">Encours</th>
+                <th class="pb-2 pr-2 whitespace-nowrap">État</th><th class="pb-2 pr-2 whitespace-nowrap">Écheancier</th>
+                <th class="pb-2 pr-2 whitespace-nowrap text-center">Actions</th>
+              </tr></thead>
+              <tbody>
+                ${factures.map(f => {
+                  const ech = echeancierByFacture[f.id];
+                  let echText = '—';
+                  if (ech) {
+                    const encours = parseFloat(f.encours_facture) || 0;
+                    const montantParEch = ech.montant_par_echeance != null ? parseFloat(ech.montant_par_echeance) : (ech.nb_echeances > 0 ? encours / ech.nb_echeances : 0);
+                    echText = `${ech.nb_echeances} éch. × ${formatMoney(montantParEch)}<br><span class="text-xs text-gray-500">dès ${formatDate(ech.date_debut_echeancier)}</span>`;
+                  }
+                  const exo = (f.cycle || '').replace(/-/g, '/') || '—';
+                  const typeLabel = factureTypeLabel(f.type_produit);
+                  const totalPaye = (parseFloat(f.montant_ht) || 0) - (parseFloat(f.encours_facture) || 0);
+                  const qteNum = parseFloat(f.quantites);
+                  const pu = (qteNum > 0 && f.montant_ht != null) ? (parseFloat(f.montant_ht) / qteNum) : null;
+                  return `
+                  <tr class="border-b border-gray-100">
+                    <td class="py-2 pr-2 whitespace-nowrap">${escapeHtml(exo)}</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">—</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">${escapeHtml(client.nom)}</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">—</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">EMGI</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">${escapeHtml(typeLabel)}</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">${escapeHtml(typeLabel)}</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">${escapeHtml(f.cycle || '—')}</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">—</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">—</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">${formatDate(f.date_facture)}</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">${escapeHtml(f.n_vente || '—')}</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">${escapeHtml(f.n_facture)}</td>
+                    <td class="py-2 pr-2 text-right whitespace-nowrap">${f.quantites != null ? formatNumber(f.quantites) : '—'}</td>
+                    <td class="py-2 pr-2 text-right whitespace-nowrap">${f.qte_livree != null ? formatNumber(f.qte_livree) : '—'}</td>
+                    <td class="py-2 pr-2 text-right whitespace-nowrap">—</td>
+                    <td class="py-2 pr-2 text-right whitespace-nowrap">${formatMoney(f.montant_ht)}</td>
+                    <td class="py-2 pr-2 text-right whitespace-nowrap">${pu != null ? formatMoney(pu) : '—'}</td>
+                    <td class="py-2 pr-2 text-right whitespace-nowrap">${formatMoney(totalPaye)}</td>
+                    <td class="py-2 pr-2 text-right whitespace-nowrap">${formatMoney(f.encours_facture)}</td>
+                    <td class="py-2 pr-2 whitespace-nowrap"><span class="px-2 py-0.5 rounded text-xs ${f.etat === 'paye' ? 'bg-green-100 text-green-800' : 'bg-amber-100 text-amber-800'}">${f.etat === 'paye' ? 'Payé' : 'En attente'}</span></td>
+                    <td class="py-2 pr-2 text-sm text-gray-600">${echText}</td>
+                    <td class="py-2 pr-2 whitespace-nowrap">
+                      <button onclick="editFacture(${f.id})" class="text-blue-600 hover:text-blue-800 mr-2" title="Modifier">
+                        <svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
+                      </button>
+                      <button onclick="deleteFacture(${f.id})" class="text-red-600 hover:text-red-800" title="Supprimer">
+                        <svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
+                      </button>
+                    </td>
+                  </tr>
+                `; }).join('')}
+              </tbody>
+            </table>
+          </div>
+        `;
+      }
+
+      const echeanciersListEl = document.getElementById('echeanciers-list');
+      if (echeanciersListEl) {
+        if (!echeanciers || echeanciers.length === 0) {
+          echeanciersListEl.innerHTML = '<p class="text-gray-500">Aucun écheancier pour ce client.</p>';
+        } else {
+          const factureById = {};
+          factures.forEach(f => { factureById[f.id] = f; });
+          
+          echeanciersListEl.innerHTML = `
+            <div class="overflow-x-auto text-sm">
+              <table class="min-w-full">
+                <thead>
+                  <tr class="text-left text-gray-600 border-b">
+                    <th class="pb-2 pr-4">Facture</th>
+                    <th class="pb-2 pr-4">Nombre d'échéances</th>
+                    <th class="pb-2 pr-4">Date de début</th>
+                    <th class="pb-2 pr-4 text-right">Montant par échéance</th>
+                    <th class="pb-2 text-right">Encours</th>
+                    <th class="pb-2 text-center">Actions</th>
+                  </tr>
+                </thead>
+                <tbody>
+                  ${echeanciers.map(e => {
+                    const f = factureById[e.facture_id];
+                    if (!f) return '';
+                    const encours = parseFloat(f.encours_facture) || 0;
+                    const montantParEch = e.montant_par_echeance != null ? parseFloat(e.montant_par_echeance) : (e.nb_echeances > 0 ? encours / e.nb_echeances : 0);
+                    return `
+                      <tr class="border-b border-gray-100">
+                        <td class="py-2 pr-4">${f ? escapeHtml(f.n_facture) : e.facture_id}</td>
+                        <td class="py-2 pr-4">${e.nb_echeances}</td>
+                        <td class="py-2 pr-4">${formatDate(e.date_debut_echeancier)}</td>
+                        <td class="py-2 pr-4 text-right">${formatMoney(montantParEch)}</td>
+                        <td class="py-2 text-right">${formatMoney(encours)}</td>
+                        <td class="py-2 text-center">
+                          <button onclick="deleteEcheancier(${e.id})" class="text-red-600 hover:text-red-800" title="Supprimer">
+                            <svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
+                          </button>
+                        </td>
+                      </tr>
+                    `;
+                  }).join('')}
+                </tbody>
+              </table>
+            </div>
+          `;
+        }
+      }
+
+      const paiementsList = document.getElementById('paiements-list');
+      if (paiements.length === 0) {
+        paiementsList.innerHTML = '<p class="text-gray-500">Aucun paiement.</p>';
+      } else {
+        paiementsList.innerHTML = `
+          <div class="overflow-x-auto">
+            <table class="min-w-full text-sm">
+              <thead><tr class="text-left text-gray-600 border-b"><th class="pb-2">Facture</th><th class="pb-2">Date</th><th class="pb-2 text-right">Montant</th><th class="pb-2 text-center">Actions</th></tr></thead>
+              <tbody>
+                ${paiements.map(p => `
+                  <tr class="border-b border-gray-100">
+                    <td class="py-2">${escapeHtml(p.n_facture)}</td>
+                    <td class="py-2">${formatDate(p.date_paiement)}</td>
+                    <td class="py-2 text-right">${formatMoney(p.montant)}</td>
+                    <td class="py-2 text-center">
+                      <button onclick="deletePaiement(${p.id})" class="text-red-600 hover:text-red-800" title="Supprimer">
+                        <svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
+                      </button>
+                    </td>
+                  </tr>
+                `).join('')}
+              </tbody>
+            </table>
+          </div>
+        `;
+      }
+
+      window.__clientId = clientId;
+      window.__factures = factures;
+      window.__echeanciers = echeanciers || [];
+      if (typeof initPaiementsForm === 'function') initPaiementsForm();
+      if (typeof initFactureForm === 'function') initFactureForm();
+      if (typeof initEcheancierForm === 'function') initEcheancierForm();
+    } catch (e) {
+      showError(e.message);
+      document.getElementById('client-header').innerHTML = '<p class="text-red-600">Erreur de chargement.</p>';
+      document.getElementById('factures-list').innerHTML = '-';
+      document.getElementById('paiements-list').innerHTML = '-';
+    }
+  }
+
+  function escapeHtml(text) {
+    const div = document.createElement('div');
+    div.textContent = text;
+    return div.innerHTML;
+  }
+
+  // Fonctions globales pour les actions
+  window.editFacture = function(factureId) {
+    const facture = window.__factures.find(f => f.id === factureId);
+    if (!facture) return;
+    
+    // Pré-remplir le formulaire
+    document.getElementById('facture_client_id').value = facture.client_id;
+    document.getElementById('n_facture').value = facture.n_facture;
+    document.getElementById('n_vente').value = facture.n_vente || '';
+    document.getElementById('date_facture').value = facture.date_facture;
+    document.getElementById('type_produit').value = facture.type_produit || '';
+    document.getElementById('cycle').value = facture.cycle || '';
+    document.getElementById('quantites').value = facture.quantites || '';
+    document.getElementById('qte_livree').value = facture.qte_livree || '';
+    document.getElementById('montant_ht').value = facture.montant_ht;
+    
+    // Modifier le formulaire pour utiliser PUT
+    const form = document.getElementById('form-facture');
+    const submitBtn = form.querySelector('button[type="submit"]');
+    submitBtn.textContent = 'Modifier la facture';
+    submitBtn.classList.remove('bg-green-600', 'hover:bg-green-700');
+    submitBtn.classList.add('bg-blue-600', 'hover:bg-blue-700');
+    
+    form.dataset.editId = factureId;
+    
+    // Afficher le bouton annuler s'il existe
+    const cancelBtn = form.querySelector('button[type="button"]');
+    if (cancelBtn) cancelBtn.style.display = 'inline-block';
+    
+    form.scrollIntoView({ behavior: 'smooth', block: 'start' });
+  };
+
+  window.deleteFacture = async function(factureId) {
+    if (!confirm('Êtes-vous sûr de vouloir supprimer cette facture ? Cette action supprimera également les paiements et écheanciers associés.')) {
+      return;
+    }
+    try {
+      await apiDelete(`/factures.php?id=${factureId}`);
+      window.location.reload();
+    } catch (err) {
+      showError(err.message);
+    }
+  };
+
+  window.deleteEcheancier = async function(echeancierId) {
+    if (!confirm('Êtes-vous sûr de vouloir supprimer cet écheancier ?')) {
+      return;
+    }
+    try {
+      await apiDelete(`/echeanciers.php?id=${echeancierId}`);
+      window.location.reload();
+    } catch (err) {
+      showError(err.message);
+    }
+  };
+
+  window.deletePaiement = async function(paiementId) {
+    if (!confirm('Êtes-vous sûr de vouloir supprimer ce paiement ? L\'encours de la facture sera recalculé.')) {
+      return;
+    }
+    try {
+      await apiDelete(`/paiements.php?id=${paiementId}`);
+      window.location.reload();
+    } catch (err) {
+      showError(err.message);
+    }
+  };
+
+  loadClient();
+})();

+ 114 - 0
app/js/dashboard.js

@@ -0,0 +1,114 @@
+/**
+ * Tableau de bord : encours par client (tri croissant), synthèse, échéances (FR10, FR11).
+ * Même structure que la slide : Client, Encours, accord, j out, situation + encadré synthèse.
+ */
+(function () {
+  function formatDateRapport(str) {
+    if (!str) return '—';
+    const d = new Date(str);
+    return isNaN(d.getTime()) ? str : d.toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', year: '2-digit' });
+  }
+
+  function formatKeur(n) {
+    if (n == null || isNaN(n)) return '—';
+    const k = (n / 1000).toFixed(1);
+    return new Intl.NumberFormat('fr-FR').format(parseFloat(k)) + ' k€';
+  }
+
+  async function loadDashboard() {
+    hideError();
+    try {
+      const data = await apiGet('/reporting.php');
+      const dateRapport = data.date_rapport || new Date().toISOString().slice(0, 10);
+      const titreEl = document.getElementById('titre-encours');
+      if (titreEl) titreEl.textContent = 'Encours clients au ' + formatDateRapport(dateRapport);
+
+      const encoursEl = document.getElementById('encours-par-client');
+      if (!data.encours_par_client || data.encours_par_client.length === 0) {
+        encoursEl.innerHTML = '<p class="text-gray-500">Aucun encours.</p>';
+      } else {
+        encoursEl.innerHTML = `
+          <table class="min-w-full divide-y divide-gray-200 text-sm">
+            <thead class="bg-gray-50">
+              <tr>
+                <th class="px-4 py-2 text-left text-xs font-medium text-gray-600 uppercase">Client</th>
+                <th class="px-4 py-2 text-right text-xs font-medium text-gray-600 uppercase">Encours</th>
+                <th class="px-4 py-2 text-center text-xs font-medium text-gray-600 uppercase">accord</th>
+                <th class="px-4 py-2 text-center text-xs font-medium text-gray-600 uppercase">j out</th>
+                <th class="px-4 py-2 text-left text-xs font-medium text-gray-600 uppercase">situation</th>
+                <th class="px-4 py-2 text-right text-xs font-medium text-gray-600 uppercase">Action</th>
+              </tr>
+            </thead>
+            <tbody class="divide-y divide-gray-200 bg-white">
+              ${data.encours_par_client.map(c => `
+                <tr class="hover:bg-gray-50">
+                  <td class="px-4 py-2 font-medium text-gray-900">${escapeHtml(c.nom)}</td>
+                  <td class="px-4 py-2 text-right tabular-nums">${formatMoney(c.encours)}</td>
+                  <td class="px-4 py-2 text-center text-gray-500">—</td>
+                  <td class="px-4 py-2 text-center text-gray-500">—</td>
+                  <td class="px-4 py-2 text-gray-500">—</td>
+                  <td class="px-4 py-2 text-right"><a href="client.html?id=${c.client_id}" class="text-blue-600 hover:underline">Voir</a></td>
+                </tr>
+              `).join('')}
+            </tbody>
+          </table>
+        `;
+      }
+
+      const synthèseEl = document.getElementById('synthèse-encours');
+      if (synthèseEl) {
+        const encoursTotalK = formatKeur(data.encours_total);
+        const delaiJ = data.delai_moyen_paiement_j != null ? data.delai_moyen_paiement_j + ' j' : '—';
+        synthèseEl.innerHTML = `
+          <div class="mt-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
+            <p class="text-sm text-gray-700"><strong>Encours client total au ${formatDateRapport(dateRapport)}</strong> : ${encoursTotalK}</p>
+            <p class="text-sm text-gray-700 mt-1"><strong>Délai moyen de paiement à date</strong> : ${delaiJ}</p>
+          </div>
+        `;
+      }
+
+      const echeancesEl = document.getElementById('echeances');
+      if (!data.echeances_a_venir || data.echeances_a_venir.length === 0) {
+        echeancesEl.innerHTML = '<p class="text-gray-500">Aucune échéance en attente.</p>';
+      } else {
+        echeancesEl.innerHTML = `
+          <table class="min-w-full divide-y divide-gray-200">
+            <thead class="bg-gray-50"><tr><th class="px-4 py-2 text-left text-xs font-medium text-gray-600">Client</th><th class="px-4 py-2 text-left text-xs font-medium text-gray-600">N° facture</th><th class="px-4 py-2 text-left text-xs font-medium text-gray-600">Date échéance</th><th class="px-4 py-2 text-right text-xs font-medium text-gray-600">Montant</th><th class="px-4 py-2 text-right text-xs font-medium text-gray-600">Action</th></tr></thead>
+            <tbody class="divide-y divide-gray-200">
+              ${data.echeances_a_venir.map(e => {
+                const dateEch = e.date_echeance || e.date_facture;
+                const montantEch = e.montant_echeance != null ? e.montant_echeance : e.encours_facture;
+                const echLabel = e.echeance_num ? `Éch. ${e.echeance_num}/${e.echeance_total}` : '';
+                return `
+                <tr class="hover:bg-gray-50">
+                  <td class="px-4 py-2 text-gray-900">${escapeHtml(e.nom)}</td>
+                  <td class="px-4 py-2">${escapeHtml(e.n_facture)}${echLabel ? ' <span class="text-xs text-gray-500">(' + echLabel + ')</span>' : ''}</td>
+                  <td class="px-4 py-2">${formatDate(dateEch)}</td>
+                  <td class="px-4 py-2 text-right">${formatMoney(montantEch)}</td>
+                  <td class="px-4 py-2 text-right"><a href="client.html?id=${e.client_id}" class="text-blue-600 hover:underline">Voir</a></td>
+                </tr>
+              `;
+              }).join('')}
+            </tbody>
+          </table>
+        `;
+      }
+    } catch (e) {
+      showError(e.message);
+      const titreEl = document.getElementById('titre-encours');
+      if (titreEl) titreEl.textContent = 'Encours clients';
+      document.getElementById('encours-par-client').innerHTML = '<p class="text-red-500">Erreur de chargement.</p>';
+      const syn = document.getElementById('synthèse-encours');
+      if (syn) syn.innerHTML = '';
+      document.getElementById('echeances').innerHTML = '<p class="text-red-500">Erreur de chargement.</p>';
+    }
+  }
+
+  function escapeHtml(text) {
+    const div = document.createElement('div');
+    div.textContent = text;
+    return div.innerHTML;
+  }
+
+  loadDashboard();
+})();

+ 82 - 0
app/js/echeancier-form.js

@@ -0,0 +1,82 @@
+/**
+ * Formulaire d'ajout d'un écheancier de paiement (FR4b).
+ * Facture associée, nombre d'échéances, date de début d'écheancier.
+ * Aperçu du plan de paiement avec dates et montants par échéance.
+ */
+function initEcheancierForm() {
+  const form = document.getElementById('form-echeancier');
+  const selectFacture = document.getElementById('echeancier_facture_id');
+  if (!form || !selectFacture || !window.__factures) return;
+
+  const factureIdsAvecEcheancier = (window.__echeanciers || []).map(e => parseInt(e.facture_id, 10));
+  const facturesSansEcheancier = window.__factures.filter(f => !factureIdsAvecEcheancier.includes(f.id));
+
+  selectFacture.innerHTML = '<option value="">— Choisir une facture —</option>' +
+    facturesSansEcheancier.map(f => {
+      const encours = parseFloat(f.encours_facture) || 0;
+      return `<option value="${f.id}" data-encours="${encours}">${escapeHtml(f.n_facture)} – ${formatDate(f.date_facture)} – Encours: ${formatMoney(encours)}</option>`;
+    }).join('');
+
+  const dateDebut = document.getElementById('date_debut_echeancier');
+  const nbEcheances = document.getElementById('nb_echeances');
+  const apercuEl = document.getElementById('apercu-echeancier');
+  
+  if (dateDebut && !dateDebut.value) dateDebut.value = new Date().toISOString().slice(0, 10);
+
+  // Fonction pour calculer et afficher l'aperçu simple
+  const mettreAJourApercu = () => {
+    if (!apercuEl) return;
+    const factureId = parseInt(selectFacture.value, 10);
+    const nb = parseInt(nbEcheances?.value || 0, 10);
+    const dateDeb = dateDebut?.value || '';
+    
+    if (!factureId || nb < 1 || !dateDeb) {
+      apercuEl.innerHTML = '';
+      return;
+    }
+    
+    const facture = window.__factures.find(f => f.id === factureId);
+    if (!facture) return;
+    
+    const encours = parseFloat(facture.encours_facture) || 0;
+    const montantParEch = nb > 0 ? Math.round((encours / nb) * 100) / 100 : 0;
+    
+    apercuEl.innerHTML = `
+      <div class="mt-3 p-3 bg-blue-50 border border-blue-200 rounded text-sm">
+        <strong>Encours :</strong> ${formatMoney(encours)} | <strong>Montant par échéance :</strong> ${formatMoney(montantParEch)}
+      </div>
+    `;
+  };
+
+  selectFacture.addEventListener('change', mettreAJourApercu);
+  nbEcheances?.addEventListener('input', mettreAJourApercu);
+  dateDebut?.addEventListener('change', mettreAJourApercu);
+
+  form.addEventListener('submit', async (e) => {
+    e.preventDefault();
+    hideError();
+    const factureId = parseInt(selectFacture.value, 10);
+    const nb = parseInt(nbEcheances?.value || 0, 10);
+    const dateDeb = dateDebut?.value || '';
+    if (!factureId || nb < 1 || !dateDeb) {
+      showError('Veuillez remplir tous les champs.');
+      return;
+    }
+    try {
+      await apiPost('/echeanciers.php', {
+        facture_id: factureId,
+        nb_echeances: nb,
+        date_debut_echeancier: dateDeb,
+      });
+      window.location.reload();
+    } catch (err) {
+      showError(err.message);
+    }
+  });
+}
+
+function escapeHtml(text) {
+  const div = document.createElement('div');
+  div.textContent = text;
+  return div.innerHTML;
+}

+ 68 - 0
app/js/facture-form.js

@@ -0,0 +1,68 @@
+/**
+ * Formulaire d'ajout d'une facture pour le suivi (FR3b).
+ */
+function initFactureForm() {
+  const form = document.getElementById('form-facture');
+  const clientIdEl = document.getElementById('facture_client_id');
+  if (!form || !window.__clientId) return;
+
+  clientIdEl.value = window.__clientId;
+  document.getElementById('date_facture').value = new Date().toISOString().slice(0, 10);
+
+  form.addEventListener('submit', async (e) => {
+    e.preventDefault();
+    hideError();
+    const editId = form.dataset.editId;
+    const payload = {
+      client_id: parseInt(clientIdEl.value, 10),
+      n_facture: document.getElementById('n_facture').value.trim(),
+      n_vente: document.getElementById('n_vente').value.trim() || null,
+      date_facture: document.getElementById('date_facture').value,
+      type_produit: document.getElementById('type_produit').value || null,
+      cycle: document.getElementById('cycle').value.trim() || null,
+      quantites: document.getElementById('quantites').value ? parseFloat(document.getElementById('quantites').value) : null,
+      qte_livree: document.getElementById('qte_livree').value ? parseFloat(document.getElementById('qte_livree').value) : null,
+      montant_ht: parseFloat(document.getElementById('montant_ht').value),
+    };
+    if (!payload.n_facture || payload.montant_ht <= 0) return;
+    try {
+      if (editId) {
+        payload.id = parseInt(editId, 10);
+        await apiPut('/factures.php', payload);
+      } else {
+        await apiPost('/factures.php', payload);
+      }
+      window.location.reload();
+    } catch (err) {
+      showError(err.message);
+    }
+  });
+  
+  // Réinitialiser le formulaire après édition
+  const resetForm = () => {
+    form.dataset.editId = '';
+    const submitBtn = form.querySelector('button[type="submit"]');
+    submitBtn.textContent = 'Ajouter la facture';
+    submitBtn.classList.remove('bg-blue-600', 'hover:bg-blue-700');
+    submitBtn.classList.add('bg-green-600', 'hover:bg-green-700');
+    form.reset();
+    clientIdEl.value = window.__clientId;
+    document.getElementById('date_facture').value = new Date().toISOString().slice(0, 10);
+  };
+  
+  // Bouton annuler si en mode édition
+  const submitBtn = form.querySelector('button[type="submit"]');
+  const cancelBtn = document.createElement('button');
+  cancelBtn.type = 'button';
+  cancelBtn.textContent = 'Annuler';
+  cancelBtn.className = 'px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600';
+  cancelBtn.style.display = 'none';
+  cancelBtn.onclick = resetForm;
+  submitBtn.parentNode.insertBefore(cancelBtn, submitBtn.nextSibling);
+  
+  // Observer les changements du formulaire pour afficher/masquer le bouton annuler
+  const observer = new MutationObserver(() => {
+    cancelBtn.style.display = form.dataset.editId ? 'inline-block' : 'none';
+  });
+  observer.observe(form, { attributes: true, attributeFilter: ['data-edit-id'] });
+}

+ 30 - 0
app/js/paiements.js

@@ -0,0 +1,30 @@
+/**
+ * Formulaire d'enregistrement d'un paiement (FR4).
+ */
+function initPaiementsForm() {
+  const form = document.getElementById('form-paiement');
+  const selectFacture = document.getElementById('facture_id');
+  if (!form || !selectFacture || !window.__factures) return;
+
+  const facturesEnAttente = window.__factures.filter(f => f.etat === 'en_attente' && f.encours_facture > 0);
+  selectFacture.innerHTML = facturesEnAttente.length === 0
+    ? '<option value="">Aucune facture en attente</option>'
+    : facturesEnAttente.map(f => `<option value="${f.id}" data-max="${f.encours_facture}">${f.n_facture} - encours ${formatMoney(f.encours_facture)}</option>`).join('');
+
+  document.getElementById('date_paiement').value = new Date().toISOString().slice(0, 10);
+
+  form.addEventListener('submit', async (e) => {
+    e.preventDefault();
+    hideError();
+    const factureId = parseInt(selectFacture.value, 10);
+    const montant = parseFloat(document.getElementById('montant').value);
+    const datePaiement = document.getElementById('date_paiement').value;
+    if (!factureId || montant <= 0) return;
+    try {
+      await apiPost('/paiements.php', { facture_id: factureId, montant, date_paiement: datePaiement });
+      window.location.reload();
+    } catch (err) {
+      showError(err.message);
+    }
+  });
+}

+ 52 - 0
app/js/quantites-clients.js

@@ -0,0 +1,52 @@
+(function () {
+  const typeEl = document.getElementById('type');
+  const listEl = document.getElementById('quantites-list');
+
+  async function load() {
+    hideError();
+    const type = typeEl.value || null;
+    try {
+      const params = type ? { type } : {};
+      const data = await apiGet('/quantites-clients.php', params);
+      if (!data.quantites_par_client || data.quantites_par_client.length === 0) {
+        listEl.innerHTML = '<p class="text-gray-500">Aucune donnée.</p>';
+        return;
+      }
+      listEl.innerHTML = `
+        <table class="min-w-full divide-y divide-gray-200">
+          <thead class="bg-gray-50">
+            <tr>
+              <th class="px-4 py-2 text-left text-xs font-medium text-gray-600">Client</th>
+              <th class="px-4 py-2 text-right text-xs font-medium text-gray-600">Qté facturée</th>
+              <th class="px-4 py-2 text-right text-xs font-medium text-gray-600">Qté livrée</th>
+              <th class="px-4 py-2 text-right text-xs font-medium text-gray-600">Action</th>
+            </tr>
+          </thead>
+          <tbody class="divide-y divide-gray-200">
+            ${data.quantites_par_client.map(c => `
+              <tr class="hover:bg-gray-50">
+                <td class="px-4 py-2 font-medium text-gray-900">${escapeHtml(c.nom)}</td>
+                <td class="px-4 py-2 text-right">${formatNumber(c.qte_facturee)}</td>
+                <td class="px-4 py-2 text-right">${formatNumber(c.qte_livree)}</td>
+                <td class="px-4 py-2 text-right"><a href="client.html?id=${c.client_id}" class="text-blue-600 hover:underline">Voir</a></td>
+              </tr>
+            `).join('')}
+          </tbody>
+        </table>
+      `;
+    } catch (e) {
+      showError(e.message);
+      listEl.innerHTML = '<p class="text-red-500">Erreur de chargement.</p>';
+    }
+  }
+
+  function escapeHtml(text) {
+    const div = document.createElement('div');
+    div.textContent = text;
+    return div.innerHTML;
+  }
+
+  document.getElementById('btn-refresh').addEventListener('click', load);
+  typeEl.addEventListener('change', load);
+  load();
+})();

+ 67 - 0
app/js/top-clients.js

@@ -0,0 +1,67 @@
+(function () {
+  const typeEl = document.getElementById('type');
+  const cycleEl = document.getElementById('cycle');
+  const topListEl = document.getElementById('top-list');
+  const titleEl = document.getElementById('title-section');
+  const totauxEl = document.getElementById('totaux');
+
+  async function load() {
+    hideError();
+    const type = typeEl.value;
+    const cycle = cycleEl.value || null;
+    try {
+      const params = { type };
+      if (cycle) params.cycle = cycle;
+      const data = await apiGet('/top-clients.php', params);
+      const label = type === 'alevins' ? 'Alevins' : 'Larves';
+      titleEl.textContent = 'Top clients ' + label + (cycle ? ' (cycle ' + cycle + ')' : '');
+      if (!data.top_clients || data.top_clients.length === 0) {
+        topListEl.innerHTML = '<p class="text-gray-500">Aucune donnée pour ce filtre.</p>';
+        totauxEl.textContent = '';
+        return;
+      }
+      topListEl.innerHTML = `
+        <table class="min-w-full divide-y divide-gray-200">
+          <thead class="bg-gray-50">
+            <tr>
+              <th class="px-4 py-2 text-left text-xs font-medium text-gray-600">Client</th>
+              <th class="px-4 py-2 text-right text-xs font-medium text-gray-600">Quantités</th>
+              <th class="px-4 py-2 text-right text-xs font-medium text-gray-600">% qté</th>
+              <th class="px-4 py-2 text-right text-xs font-medium text-gray-600">CA HT</th>
+              <th class="px-4 py-2 text-right text-xs font-medium text-gray-600">% CA</th>
+              <th class="px-4 py-2 text-right text-xs font-medium text-gray-600">Action</th>
+            </tr>
+          </thead>
+          <tbody class="divide-y divide-gray-200">
+            ${data.top_clients.map(c => `
+              <tr class="hover:bg-gray-50">
+                <td class="px-4 py-2 font-medium text-gray-900">${escapeHtml(c.nom)}</td>
+                <td class="px-4 py-2 text-right">${formatNumber(c.quantites)}</td>
+                <td class="px-4 py-2 text-right">${c.pct_qte} %</td>
+                <td class="px-4 py-2 text-right">${formatMoney(c.ca)}</td>
+                <td class="px-4 py-2 text-right">${c.pct_ca} %</td>
+                <td class="px-4 py-2 text-right"><a href="client.html?id=${c.client_id}" class="text-blue-600 hover:underline">Voir</a></td>
+              </tr>
+            `).join('')}
+          </tbody>
+        </table>
+      `;
+      totauxEl.textContent = 'Total quantités : ' + formatNumber(data.total_quantites) + ' — Total CA HT : ' + formatMoney(data.total_ca);
+    } catch (e) {
+      showError(e.message);
+      topListEl.innerHTML = '<p class="text-red-500">Erreur de chargement.</p>';
+      totauxEl.textContent = '';
+    }
+  }
+
+  function escapeHtml(text) {
+    const div = document.createElement('div');
+    div.textContent = text;
+    return div.innerHTML;
+  }
+
+  document.getElementById('btn-refresh').addEventListener('click', load);
+  typeEl.addEventListener('change', load);
+  cycleEl.addEventListener('change', load);
+  load();
+})();

+ 85 - 0
app/js/utils.js

@@ -0,0 +1,85 @@
+/**
+ * Utilitaires communs : appels API, affichage erreurs.
+ */
+const API_BASE = '/api';
+
+async function apiGet(path, params = {}) {
+  const url = new URL(API_BASE + path, window.location.origin);
+  Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
+  const res = await fetch(url.toString());
+  const data = await res.json().catch(() => ({}));
+  if (!res.ok) {
+    throw new Error(data.error || res.statusText || 'Erreur API');
+  }
+  return data;
+}
+
+async function apiPost(path, body) {
+  const res = await fetch(API_BASE + path, {
+    method: 'POST',
+    headers: { 'Content-Type': 'application/json' },
+    body: JSON.stringify(body),
+  });
+  const data = await res.json().catch(() => ({}));
+  if (!res.ok) {
+    throw new Error(data.error || res.statusText || 'Erreur API');
+  }
+  return data;
+}
+
+async function apiPut(path, body) {
+  const res = await fetch(API_BASE + path, {
+    method: 'PUT',
+    headers: { 'Content-Type': 'application/json' },
+    body: JSON.stringify(body),
+  });
+  const data = await res.json().catch(() => ({}));
+  if (!res.ok) {
+    throw new Error(data.error || res.statusText || 'Erreur API');
+  }
+  return data;
+}
+
+async function apiDelete(path) {
+  const res = await fetch(API_BASE + path, {
+    method: 'DELETE',
+  });
+  const data = await res.json().catch(() => ({}));
+  if (!res.ok) {
+    throw new Error(data.error || res.statusText || 'Erreur API');
+  }
+  return data;
+}
+
+function showError(message) {
+  const el = document.getElementById('error-message');
+  if (el) {
+    el.textContent = message;
+    el.classList.remove('hidden');
+  } else {
+    alert(message);
+  }
+}
+
+function hideError() {
+  const el = document.getElementById('error-message');
+  if (el) {
+    el.classList.add('hidden');
+    el.textContent = '';
+  }
+}
+
+function formatMoney(value) {
+  return new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(value);
+}
+
+function formatDate(str) {
+  if (!str) return '-';
+  const d = new Date(str);
+  return isNaN(d.getTime()) ? str : d.toLocaleDateString('fr-FR');
+}
+
+function formatNumber(value) {
+  if (value == null) return '-';
+  return new Intl.NumberFormat('fr-FR').format(value);
+}

+ 22 - 0
app/mock/clients.json

@@ -0,0 +1,22 @@
+[
+    {
+        "id": 1,
+        "nom": "AQUANARIA",
+        "created_at": "2026-02-01T09:00:00+00:00"
+    },
+    {
+        "id": 2,
+        "nom": "PHILOSOFISH",
+        "created_at": "2026-02-02T10:00:00+00:00"
+    },
+    {
+        "id": 3,
+        "nom": "AQN",
+        "created_at": "2026-02-03T11:00:00+00:00"
+    },
+    {
+        "id": 4,
+        "nom": "Test client",
+        "created_at": "2026-02-09T17:54:23+00:00"
+    }
+]

+ 34 - 0
app/mock/echeanciers.json

@@ -0,0 +1,34 @@
+[
+    {
+        "id": 1,
+        "facture_id": 101,
+        "nb_echeances": 3,
+        "date_debut_echeancier": "2026-02-01",
+        "montant_par_echeance": 266.67,
+        "created_at": "2026-02-01T10:00:00+00:00"
+    },
+    {
+        "id": 2,
+        "facture_id": 201,
+        "nb_echeances": 3,
+        "date_debut_echeancier": "2026-02-09",
+        "montant_par_echeance": 333.33,
+        "created_at": "2026-02-09T16:36:43+00:00"
+    },
+    {
+        "id": 5,
+        "facture_id": 303,
+        "nb_echeances": 2,
+        "date_debut_echeancier": "2026-02-09",
+        "montant_par_echeance": 50,
+        "created_at": "2026-02-09T17:58:01+00:00"
+    },
+    {
+        "id": 6,
+        "facture_id": 301,
+        "nb_echeances": 2,
+        "date_debut_echeancier": "2026-02-09",
+        "montant_par_echeance": 225,
+        "created_at": "2026-02-09T18:02:36+00:00"
+    }
+]

+ 67 - 0
app/mock/factures.json

@@ -0,0 +1,67 @@
+[
+    {
+        "id": 101,
+        "client_id": 1,
+        "n_facture": "FA260025",
+        "n_vente": "AL-25\/26-14",
+        "date_facture": "2026-01-15",
+        "type_produit": "alevins",
+        "cycle": "25-26",
+        "quantites": 1200,
+        "qte_livree": 1000,
+        "montant_ht": 1000,
+        "created_at": "2026-02-01T09:10:00+00:00"
+    },
+    {
+        "id": 102,
+        "client_id": 1,
+        "n_facture": "FA-002",
+        "n_vente": "LV-25\/26-11",
+        "date_facture": "2026-02-01",
+        "type_produit": "larves",
+        "cycle": "25-26",
+        "quantites": 800,
+        "qte_livree": 800,
+        "montant_ht": 500,
+        "created_at": "2026-02-01T09:11:00+00:00"
+    },
+    {
+        "id": 201,
+        "client_id": 2,
+        "n_facture": "F-2025-11-1",
+        "n_vente": "AL-25\/26-02",
+        "date_facture": "2026-01-20",
+        "type_produit": "alevins",
+        "cycle": "24-25",
+        "quantites": 500,
+        "qte_livree": 450,
+        "montant_ht": 750,
+        "created_at": "2026-02-02T10:10:00+00:00"
+    },
+    {
+        "id": 301,
+        "client_id": 3,
+        "n_facture": "FA260031",
+        "n_vente": "LV-25\/26-05",
+        "date_facture": "2026-02-05",
+        "type_produit": "larves",
+        "cycle": "25-26",
+        "quantites": 300,
+        "qte_livree": null,
+        "montant_ht": 450,
+        "created_at": "2026-02-05T09:00:00+00:00"
+    },
+    {
+        "id": 303,
+        "client_id": 4,
+        "n_facture": "56",
+        "n_vente": "465",
+        "date_facture": "2026-02-09",
+        "type_produit": "alevins",
+        "cycle": "56456",
+        "quantites": 10,
+        "qte_livree": 10,
+        "montant_ht": 100,
+        "created_at": "2026-02-09T17:57:25+00:00"
+    }
+]

+ 58 - 0
app/mock/paiements.json

@@ -0,0 +1,58 @@
+[
+    {
+        "id": 1001,
+        "facture_id": 101,
+        "montant": 500,
+        "date_paiement": "2026-02-01",
+        "created_at": "2026-02-01T12:00:00+00:00"
+    },
+    {
+        "id": 1002,
+        "facture_id": 201,
+        "montant": 250,
+        "date_paiement": "2026-02-03",
+        "created_at": "2026-02-03T08:00:00+00:00"
+    },
+    {
+        "id": 1003,
+        "facture_id": 102,
+        "montant": 500,
+        "date_paiement": "2026-02-09",
+        "created_at": "2026-02-09T12:57:16+00:00"
+    },
+    {
+        "id": 1004,
+        "facture_id": 101,
+        "montant": 400,
+        "date_paiement": "2026-02-09",
+        "created_at": "2026-02-09T12:57:22+00:00"
+    },
+    {
+        "id": 1005,
+        "facture_id": 201,
+        "montant": 500,
+        "date_paiement": "2026-02-09",
+        "created_at": "2026-02-09T16:37:06+00:00"
+    },
+    {
+        "id": 1006,
+        "facture_id": 302,
+        "montant": 333,
+        "date_paiement": "2026-02-09",
+        "created_at": "2026-02-09T17:46:03+00:00"
+    },
+    {
+        "id": 1007,
+        "facture_id": 301,
+        "montant": 225,
+        "date_paiement": "2026-02-09",
+        "created_at": "2026-02-09T18:02:46+00:00"
+    },
+    {
+        "id": 1008,
+        "facture_id": 301,
+        "montant": 225,
+        "date_paiement": "2026-02-09",
+        "created_at": "2026-02-09T18:03:02+00:00"
+    }
+]

+ 43 - 0
app/quantites-clients.html

@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+  <meta charset="UTF-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <title>Quantités par client - Suivi FTI EMGI</title>
+  <script src="https://cdn.tailwindcss.com"></script>
+</head>
+<body class="bg-gray-50 min-h-screen">
+  <div class="max-w-5xl mx-auto px-4 py-8">
+    <header class="flex justify-between items-center mb-8">
+      <h1 class="text-2xl font-semibold text-gray-800">Suivi FTI EMGI</h1>
+      <nav class="space-x-4">
+        <a href="index.html" class="text-gray-600 hover:text-blue-600">Clients</a>
+        <a href="dashboard.html" class="text-gray-600 hover:text-blue-600">Tableau de bord</a>
+        <a href="top-clients.html" class="text-gray-600 hover:text-blue-600">Top clients</a>
+        <a href="quantites-clients.html" class="text-blue-600 font-medium">Quantités</a>
+      </nav>
+    </header>
+
+    <div id="error-message" class="hidden mb-4 p-3 bg-red-100 text-red-700 rounded"></div>
+
+    <div class="mb-6">
+      <label for="type" class="block text-sm font-medium text-gray-700 mb-1">Filtrer par type (optionnel)</label>
+      <select id="type" class="border border-gray-300 rounded px-3 py-2">
+        <option value="">Tous</option>
+        <option value="alevins">Alevins</option>
+        <option value="larves">Larves</option>
+      </select>
+      <button type="button" id="btn-refresh" class="ml-2 px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">Actualiser</button>
+    </div>
+
+    <div class="bg-white rounded-lg shadow overflow-hidden">
+      <h2 class="px-6 py-4 border-b text-lg font-medium text-gray-800">Quantités vendues par client</h2>
+      <p class="px-6 text-sm text-gray-500">Qté facturée = quantité sur facture ; Qté livrée = déjà livré.</p>
+      <div id="quantites-list" class="p-6">Chargement...</div>
+    </div>
+  </div>
+
+  <script src="js/utils.js"></script>
+  <script src="js/quantites-clients.js"></script>
+</body>
+</html>

+ 35 - 0
app/sql/migration-echeanciers-montant.sql

@@ -0,0 +1,35 @@
+-- Migration : Ajout du champ montant_par_echeance dans la table echeanciers
+-- Date : 2026-02-09
+-- Description : Ajoute le champ montant_par_echeance et recalcule les valeurs pour les écheanciers existants
+
+-- 1. Ajouter la colonne montant_par_echeance
+ALTER TABLE echeanciers 
+ADD COLUMN montant_par_echeance DECIMAL(12,2) NULL COMMENT 'Montant calculé au moment de la création (encours / nb_echeances)';
+
+-- 2. Calculer et mettre à jour les valeurs pour les écheanciers existants
+UPDATE echeanciers e
+INNER JOIN (
+    SELECT 
+        f.id AS facture_id,
+        GREATEST(0, f.montant_ht - COALESCE(SUM(p.montant), 0)) AS encours_actuel
+    FROM factures f
+    LEFT JOIN paiements p ON p.facture_id = f.id
+    GROUP BY f.id, f.montant_ht
+) enc ON enc.facture_id = e.facture_id
+SET e.montant_par_echeance = ROUND(enc.encours_actuel / e.nb_echeances, 2)
+WHERE e.montant_par_echeance IS NULL;
+
+-- 3. Rendre la colonne NOT NULL maintenant qu'elle est remplie
+ALTER TABLE echeanciers 
+MODIFY COLUMN montant_par_echeance DECIMAL(12,2) NOT NULL;
+
+-- 4. Ajouter la contrainte CHECK pour montant > 0
+ALTER TABLE echeanciers 
+ADD CONSTRAINT chk_echeanciers_montant CHECK (montant_par_echeance > 0);
+
+-- 5. Ajouter la contrainte d'unicité sur facture_id (si pas déjà présente)
+-- Vérifier d'abord si l'index existe, sinon créer
+-- ALTER TABLE echeanciers ADD UNIQUE KEY uk_echeanciers_facture_id (facture_id);
+
+-- 6. Ajouter l'index sur date_paiement pour les paiements (si pas déjà présent)
+-- CREATE INDEX idx_paiements_date ON paiements(date_paiement);

+ 13 - 0
app/sql/migration-echeanciers.sql

@@ -0,0 +1,13 @@
+-- Migration : ajout de la table echeanciers (FR4b, FR5b)
+-- À exécuter si la base a déjà été créée sans la table echeanciers.
+
+CREATE TABLE IF NOT EXISTS echeanciers (
+    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+    facture_id INT UNSIGNED NOT NULL,
+    nb_echeances INT UNSIGNED NOT NULL,
+    date_debut_echeancier DATE NOT NULL,
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    CONSTRAINT fk_echeanciers_facture FOREIGN KEY (facture_id) REFERENCES factures(id) ON DELETE CASCADE
+);
+
+CREATE INDEX idx_echeanciers_facture_id ON echeanciers(facture_id);

+ 7 - 0
app/sql/migration-type-produit-cycle.sql

@@ -0,0 +1,7 @@
+-- Migration : ajout type_produit, cycle, qte_livree sur factures (si tables déjà créées sans ces colonnes)
+-- Exécuter une seule fois. Si une colonne existe déjà, ignorer la ligne concernée ou recréer la table depuis schema.sql.
+ALTER TABLE factures ADD COLUMN type_produit VARCHAR(32) DEFAULT NULL COMMENT 'alevins, larves' AFTER date_facture;
+ALTER TABLE factures ADD COLUMN cycle VARCHAR(16) DEFAULT NULL COMMENT 'ex: 24-25, 25-26' AFTER type_produit;
+ALTER TABLE factures ADD COLUMN qte_livree DECIMAL(12,2) DEFAULT NULL AFTER quantites;
+CREATE INDEX idx_factures_type_produit ON factures(type_produit);
+CREATE INDEX idx_factures_cycle ON factures(cycle);

+ 56 - 0
app/sql/schema.sql

@@ -0,0 +1,56 @@
+-- Schéma POC suivi facturation / échéancier / paiement (EMGI)
+-- MariaDB/MySQL
+-- Factures : type_produit (alevins, larves), cycle (24-25, 25-26), qte_livree
+
+SET NAMES utf8mb4;
+
+CREATE TABLE IF NOT EXISTS clients (
+    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+    nom VARCHAR(255) NOT NULL,
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
+);
+
+CREATE TABLE IF NOT EXISTS factures (
+    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+    client_id INT UNSIGNED NOT NULL,
+    n_facture VARCHAR(64) NOT NULL,
+    n_vente VARCHAR(64) DEFAULT NULL,
+    date_facture DATE NOT NULL,
+    type_produit VARCHAR(32) DEFAULT NULL COMMENT 'alevins, larves',
+    cycle VARCHAR(16) DEFAULT NULL COMMENT 'ex: 24-25, 25-26',
+    quantites DECIMAL(12,2) DEFAULT NULL,
+    qte_livree DECIMAL(12,2) DEFAULT NULL,
+    montant_ht DECIMAL(12,2) NOT NULL,
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    CONSTRAINT fk_factures_client FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE
+);
+
+CREATE TABLE IF NOT EXISTS paiements (
+    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+    facture_id INT UNSIGNED NOT NULL,
+    montant DECIMAL(12,2) NOT NULL,
+    date_paiement DATE NOT NULL,
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    CONSTRAINT fk_paiements_facture FOREIGN KEY (facture_id) REFERENCES factures(id) ON DELETE CASCADE,
+    CONSTRAINT chk_paiements_montant CHECK (montant > 0)
+);
+
+CREATE TABLE IF NOT EXISTS echeanciers (
+    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
+    facture_id INT UNSIGNED NOT NULL,
+    nb_echeances INT UNSIGNED NOT NULL,
+    date_debut_echeancier DATE NOT NULL,
+    montant_par_echeance DECIMAL(12,2) NOT NULL COMMENT 'Montant calculé au moment de la création (encours / nb_echeances)',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    CONSTRAINT fk_echeanciers_facture FOREIGN KEY (facture_id) REFERENCES factures(id) ON DELETE CASCADE,
+    CONSTRAINT chk_echeanciers_nb_echeances CHECK (nb_echeances > 0),
+    CONSTRAINT chk_echeanciers_montant CHECK (montant_par_echeance > 0),
+    UNIQUE KEY uk_echeanciers_facture_id (facture_id) COMMENT 'Une facture = un écheancier maximum'
+);
+
+CREATE INDEX idx_factures_client_id ON factures(client_id);
+CREATE INDEX idx_factures_type_produit ON factures(type_produit);
+CREATE INDEX idx_factures_cycle ON factures(cycle);
+CREATE INDEX idx_paiements_facture_id ON paiements(facture_id);
+CREATE INDEX idx_paiements_date ON paiements(date_paiement);
+CREATE INDEX idx_echeanciers_facture_id ON echeanciers(facture_id);

+ 52 - 0
app/top-clients.html

@@ -0,0 +1,52 @@
+<!DOCTYPE html>
+<html lang="fr">
+<head>
+  <meta charset="UTF-8">
+  <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <title>Top clients - Suivi FTI EMGI</title>
+  <script src="https://cdn.tailwindcss.com"></script>
+</head>
+<body class="bg-gray-50 min-h-screen">
+  <div class="max-w-5xl mx-auto px-4 py-8">
+    <header class="flex justify-between items-center mb-8">
+      <h1 class="text-2xl font-semibold text-gray-800">Suivi FTI EMGI</h1>
+      <nav class="space-x-4">
+        <a href="index.html" class="text-gray-600 hover:text-blue-600">Clients</a>
+        <a href="dashboard.html" class="text-gray-600 hover:text-blue-600">Tableau de bord</a>
+        <a href="top-clients.html" class="text-blue-600 font-medium">Top clients</a>
+        <a href="quantites-clients.html" class="text-gray-600 hover:text-blue-600">Quantités</a>
+      </nav>
+    </header>
+
+    <div id="error-message" class="hidden mb-4 p-3 bg-red-100 text-red-700 rounded"></div>
+
+    <div class="flex flex-wrap gap-4 mb-6">
+      <div>
+        <label for="type" class="block text-sm font-medium text-gray-700 mb-1">Type de produit</label>
+        <select id="type" class="border border-gray-300 rounded px-3 py-2">
+          <option value="alevins">Alevins</option>
+          <option value="larves">Larves</option>
+        </select>
+      </div>
+      <div>
+        <label for="cycle" class="block text-sm font-medium text-gray-700 mb-1">Cycle (optionnel)</label>
+        <select id="cycle" class="border border-gray-300 rounded px-3 py-2">
+          <option value="">Tous</option>
+          <option value="24-25">24-25</option>
+          <option value="25-26">25-26</option>
+        </select>
+      </div>
+      <div class="flex items-end"><button type="button" id="btn-refresh" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">Actualiser</button></div>
+    </div>
+
+    <div class="bg-white rounded-lg shadow overflow-hidden mb-8">
+      <h2 id="title-section" class="px-6 py-4 border-b text-lg font-medium text-gray-800">Top clients Alevins</h2>
+      <div id="top-list" class="p-6">Chargement...</div>
+      <div id="totaux" class="px-6 pb-4 text-sm text-gray-600"></div>
+    </div>
+  </div>
+
+  <script src="js/utils.js"></script>
+  <script src="js/top-clients.js"></script>
+</body>
+</html>

二進制
doc projet/new captures/2026-01-13_10-33-26.jpg


二進制
doc projet/new captures/2026-01-13_10-34-49.jpg


二進制
doc projet/new captures/2026-01-13_10-37-15.jpg


二進制
doc projet/new captures/2026-01-13_10-37-45.jpg


二進制
doc projet/new captures/2026-01-13_10-59-25.jpg


二進制
doc projet/new captures/en plus previsionnel/2026-01-13_11-18-02.jpg


二進制
doc projet/new captures/listing facturation.jpg