SPB Git forge

spb/resto-ka

Public

Resto·Ka — tous les restaurants du Québec, menus complets et prix réels (famille ·Ka)

52commits 1branches 0releases
11.6 MBsize
maindefault branch
19 days agolast push
Python 69.3% TypeScript 16.7% CSS 7.9% JavaScript 4.7% HTML 1.4%

Stats v2 : dashboard ultra complet + 5 rapports PDF (module commun Groupe KA v2)

- kit vendorisé mis au niveau canonique v2 (kacharts.tsx, kapdf.py, SPEC.md)
- backend stats.py : 10 KPI (deltas + sparklines), 6 jauges de complétude,
  4 séries quotidiennes, multi-courbes prix moyen par ville, ajouts par
  source empilés, 4 répartitions, 3 distributions (prix de plats, capacités
  RACJ, notes Yelp), heatmap horaire des relevés, 6 tableaux, 12 records
- /api/stats/report : 5 modes (complet|synthese|tendances|repartitions|
  donnees), inconnu -> complet, filename(mode)
- page /stats : jauges, StatSummary, MultiLine/Stacked/Histogram/HourHeatmap,
  PdfButton v2 (menu 5 rapports)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Simon-Pierre Boucher committed 1 mo ago (Aug 19, 2026) parent a9e4fb2

10 changed files +1,961 −317

modified data/ueat-discovered.json +104 −0
@@ -159,6 +159,110 @@
159 159 {
160 160 "key": "d42e5dd2-815c-4803-930d-ae0ee95b1e4b",
161 161 "label": "Bol de Vie (découvert via boldevie.ca)"
162 + },
163 + {
164 + "key": "4ccf6bdd-0fae-42e9-8ae4-8f5670c905cf",
165 + "label": "Coba (découvert via restaurantcoba.com)"
166 + },
167 + {
168 + "key": "841868c1-02a9-4a1e-bb9d-c01d33587ee3",
169 + "label": "Piri Piri Rôtisserie Portugaise (découvert via piri-piri.ca)"
170 + },
171 + {
172 + "key": "5be5aa7d-f64c-4aaa-82a9-d6f764696de8",
173 + "label": "Sushi Time (découvert via sushitime-mtl.com)"
174 + },
175 + {
176 + "key": "1d25d02b-8346-4aee-8170-9bbe489e4aea",
177 + "label": "Atlas Pizza (découvert via atlaspizza.ca)"
178 + },
179 + {
180 + "key": "2331b263-c983-4482-9826-37c6ded2a447",
181 + "label": "Ubi Sushi (découvert via ubisushi.ca)"
182 + },
183 + {
184 + "key": "be6444ec-a9ac-4ecc-bd50-798d883b423a",
185 + "label": "O Fuzion (découvert via ofuzionmontreal.com)"
186 + },
187 + {
188 + "key": "65ade9ac-96d0-43e4-a95f-d43abef9b28c",
189 + "label": "Jacques Cartier Pizza (découvert via jacquescartierpizza.com)"
190 + },
191 + {
192 + "key": "691dd353-f1e7-4cb9-ab45-9a26395ada43",
193 + "label": "Le Jardin de Panos (découvert via lejardindepanos.com)"
194 + },
195 + {
196 + "key": "f8770d29-c21e-4a52-a563-927d11d8b555",
197 + "label": "Mama Khan (découvert via mamakhan.ca)"
198 + },
199 + {
200 + "key": "20490e01-9803-44a4-8f0b-afc79fb78957",
201 + "label": "F+F Pizza — Beaubien (découvert via ffpizza.com)"
202 + },
203 + {
204 + "key": "46f4245a-0868-490a-882e-cde290c69ef4",
205 + "label": "Souvlaki Bar — Verdun (découvert via souvlakibar.ca)"
206 + },
207 + {
208 + "key": "815ae848-a8ad-4a15-8f1a-7ad7998f8bf8",
209 + "label": "Les deux fours (découvert via lesdeuxfours.ca)"
210 + },
211 + {
212 + "key": "e22c23d8-e195-415b-a2ba-21bb7398d421",
213 + "label": "Poke Monster (découvert via pokemonster.com)"
214 + },
215 + {
216 + "key": "4268100d-6470-40b9-a755-e11342c91d6d",
217 + "label": "Poulet Rouge (découvert via poulet-rouge.ca)"
218 + },
219 + {
220 + "key": "3a2610a1-1549-48e5-a08d-74a46bab56e9",
221 + "label": "Edward Smoked Meat (découvert via edwardsmokedmeat.com)"
222 + },
223 + {
224 + "key": "ee4856e5-33db-441a-bdbe-60da473a9f8e",
225 + "label": "Samon Sushi (découvert via samonsushi.com)"
226 + },
227 + {
228 + "key": "41c9d5fc-eb0a-43b9-87eb-789211d9e64e",
229 + "label": "Blaxton Centre Vidéotron (découvert via blaxton.com)"
230 + },
231 + {
232 + "key": "365c4087-4be8-4c90-b6d3-f21fd02fd8f0",
233 + "label": "Becco Pizza (découvert via beccopizza.com)"
234 + },
235 + {
236 + "key": "e473d88d-b405-41ee-9ee8-2aa628eee604",
237 + "label": "ThaïZone (découvert via thaizone.ca)"
238 + },
239 + {
240 + "key": "25aeb2a7-9693-434f-8c60-3d390b13ec0d",
241 + "label": "Planète Poutine (découvert via planetepoutine.com)"
242 + },
243 + {
244 + "key": "1696ecd3-d4ea-4224-9f98-9299ebcb339c",
245 + "label": "Mandy’s Salades Gourmandes (découvert via mandys.ca)"
246 + },
247 + {
248 + "key": "f2ed2c82-8a8a-4335-ade5-2c667d4f5d6e",
249 + "label": "Ogari San Sushi (découvert via ogarisan.com)"
250 + },
251 + {
252 + "key": "48841e4f-9109-4c54-9c64-325f8546ad55",
253 + "label": "QDC Burger (découvert via qdcburger.com)"
254 + },
255 + {
256 + "key": "5d5542c1-e9d4-4d7d-91b4-73fe4c60081d",
257 + "label": "Mucho Burrito (découvert via muchoburrito.com)"
258 + },
259 + {
260 + "key": "e9f4d78d-feb0-42cc-85a3-8573b252c56d",
261 + "label": "Le Crêpe Chignon - Café Crêperie (découvert via crepechignon.com)"
262 + },
263 + {
264 + "key": "a2b6f390-ff59-4ba1-a3c4-de5b9c50ffe9",
265 + "label": "Café Dépôt (découvert via cafedepot.com)"
162 266 }
163 267 ]
164 268 }
\ No newline at end of file
modified frontend/public/ka-agent.js +25 −7
@@ -17,18 +17,19 @@
17 17
18 18 /* ---------- styles ---------- */
19 19 var css = `
20 − .kaa-btn{position:fixed;right:18px;bottom:18px;z-index:2147483000;width:58px;height:58px;
20 + .kaa-btn{position:fixed;right:18px;bottom:calc(18px + env(safe-area-inset-bottom,0px));z-index:2147483000;width:58px;height:58px;
21 21 border-radius:50%;border:2px solid var(--ink,#141814);background:var(--accent,#d9f26b);
22 22 color:var(--on-accent,#141814);font:700 17px/1 "Space Grotesk",system-ui,sans-serif;
23 23 cursor:pointer;box-shadow:4px 4px 0 rgba(20,24,20,.85);display:flex;align-items:center;
24 − justify-content:center;transition:transform .15s;padding-bottom:env(safe-area-inset-bottom,0)}
24 + justify-content:center;transition:transform .15s}
25 25 .kaa-btn:hover{transform:translate(-2px,-2px)}
26 − .kaa-panel{position:fixed;right:16px;bottom:86px;z-index:2147483001;width:min(392px,calc(100vw - 24px));
27 − height:min(580px,calc(100dvh - 110px));display:none;flex-direction:column;background:var(--paper,#f5f3ee);
26 + .kaa-panel{position:fixed;right:16px;bottom:calc(86px + env(safe-area-inset-bottom,0px));z-index:2147483001;width:min(392px,calc(100vw - 24px));
27 + height:min(580px,calc(100vh - 110px));height:min(580px,calc(100dvh - 110px));display:none;flex-direction:column;background:var(--paper,#f5f3ee);
28 28 border:2px solid var(--ink,#141814);border-radius:14px;box-shadow:8px 8px 0 rgba(20,24,20,.85);
29 29 overflow:hidden;font-family:Inter,system-ui,sans-serif}
30 30 .kaa-panel.kaa-open{display:flex}
31 − .kaa-panel.kaa-full{right:0;bottom:0;width:100vw;height:100dvh;border-radius:0;border:0;box-shadow:none}
31 + .kaa-panel.kaa-full{right:0;bottom:0;width:100vw;height:100vh;height:100dvh;border-radius:0;border:0;box-shadow:none}
32 + html.kaa-lock,html.kaa-lock body{overflow:hidden!important;overscroll-behavior:none}
32 33 .kaa-head{display:flex;align-items:center;gap:9px;padding:11px 14px;background:var(--ink,#141814);
33 34 color:var(--paper,#f5f3ee);flex:none}
34 35 .kaa-head b{font:700 15px "Space Grotesk",system-ui,sans-serif;letter-spacing:-.02em}
@@ -53,7 +54,7 @@
53 54 border-radius:999px;background:var(--surface-2,#faf9f5)}
54 55 .kaa-in{display:flex;gap:8px;padding:11px;border-top:2px solid var(--ink,#141814);background:#fff;flex:none;
55 56 padding-bottom:calc(11px + env(safe-area-inset-bottom,0))}
56 − .kaa-in textarea{flex:1;resize:none;min-height:44px;max-height:110px;padding:11px 12px;font:13.5px/1.4 Inter,system-ui,sans-serif;
57 + .kaa-in textarea{flex:1;resize:none;min-height:44px;max-height:110px;padding:10px 12px;font:16px/1.4 Inter,system-ui,sans-serif;
57 58 border:1.5px solid var(--ink,#141814);border-radius:9px;background:var(--paper,#f5f3ee);outline:none}
58 59 .kaa-in button{min-width:52px;min-height:44px;border:1.5px solid var(--ink,#141814);border-radius:9px;
59 60 background:var(--ink,#141814);color:var(--accent,#d9f26b);font:700 16px "Space Grotesk",system-ui;cursor:pointer}
@@ -142,15 +143,32 @@
142 143 }
143 144
144 145 /* ---------- ouverture / plein écran ---------- */
146 + /* Sur téléphone : panneau plein écran d'office + scroll d'arrière-plan
147 + verrouillé tant qu'il est ouvert (html.kaa-lock). Pas de focus clavier
148 + forcé au tap (le clavier ne s'ouvre que si l'utilisateur touche le champ). */
149 + var mobileMq = window.matchMedia("(max-width: 640px)");
150 + var fineInput = window.matchMedia("(hover: hover) and (pointer: fine)");
151 + function syncLock() {
152 + var open = panel.classList.contains("kaa-open");
153 + if (open && mobileMq.matches) panel.classList.add("kaa-full");
154 + document.documentElement.classList.toggle(
155 + "kaa-lock", open && panel.classList.contains("kaa-full"));
156 + }
145 157 btn.addEventListener("click", function () {
146 158 panel.classList.toggle("kaa-open");
147 − if (panel.classList.contains("kaa-open")) { render(); ta.focus(); }
159 + if (panel.classList.contains("kaa-open")) {
160 + render();
161 + if (fineInput.matches) ta.focus();
162 + }
163 + syncLock();
148 164 });
149 165 panel.querySelector(".kaa-x2").addEventListener("click", function () {
150 166 panel.classList.remove("kaa-open", "kaa-full");
167 + syncLock();
151 168 });
152 169 panel.querySelector(".kaa-x1").addEventListener("click", function () {
153 170 panel.classList.toggle("kaa-full");
171 + syncLock();
154 172 scroll();
155 173 });
156 174
modified frontend/src/ka/stats/SPEC.md +128 −66
@@ -1,53 +1,88 @@
1 −# ka-stats — module Stats commun Groupe KA (spec v1)
1 +# ka-stats — module Stats commun Groupe KA (spec v2)
2 2
3 −Contrat partagé par les 12 plateformes pour leurs pages **/stats** (tableau de
4 −bord analytique) et l'**export PDF** estampillé Groupe-KA. Le visuel suit le
5 −design system ka-ui (tokens.css) avec l'accent de la marque.
3 +Contrat partagé par les plateformes pour leurs pages **/stats** (tableau de
4 +bord analytique) et les **exports PDF** estampillés Groupe-KA. Le visuel suit
5 +le design system ka-ui (tokens.css) avec l'accent de la marque.
6 +
7 +**v2 (2026-08-19)** : sparklines dans les KPI, jauges, multi-courbes,
8 +barres empilées, distributions (histogrammes), heatmap horaire 7×24, deltas
9 +sur les répartitions, statistiques de séries (min/max/moy/méd/σ), et **5
10 +rapports PDF** au lieu de 2. Tous les nouveaux champs sont **optionnels** :
11 +un dashboard v1 reste valide et se rend tel quel.
6 12
7 13 ## 1. Page /stats — structure obligatoire (dans cet ordre)
8 14
9 −1. **Bandeau KPI** : 4–6 grandes cartes (`KpiCard`) — valeur, libellé,
10 − variation vs période précédente (▲/▼ + %, vert `--green` / rouge `--danger`).
15 +1. **Bandeau KPI** : 6–10 grandes cartes (`KpiCard`) — valeur, libellé,
16 + variation vs période précédente (▲/▼ + %, vert `--green` / rouge
17 + `--danger`), **sparkline** de tendance quand une série existe.
11 18 2. **Sélecteur de période global** (`PeriodSelector`) : `aujourd'hui · 7 j ·
12 19 30 j · 3 m · 6 m · 12 m · année en cours · tout` + plage personnalisée
13 20 (2 champs date). Toute la page se recalcule (state → refetch dashboard).
14 −3. **Graphiques** : courbes d'évolution (`LineChart`, survol = infobulle,
15 − légende cliquable pour masquer une série, comparaison N vs N-1 en
16 − pointillé), barres (`BarChart`), anneaux (`Donut`), calendrier de chaleur
17 − (`CalendarHeatmap`) quand pertinent.
18 −4. **Répartition géographique** (par ville/région) quand pertinent — barres
19 − horizontales triées (pas besoin de vraie carte).
20 −5. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne,
21 +3. **Jauges** (`GaugeCard`) quand pertinent : taux, couvertures, complétude.
22 +4. **Graphiques d'évolution** : courbes/aires (`LineChart`, survol =
23 + infobulle, légende cliquable, comparaison N vs N-1 en pointillé), barres
24 + verticales (`VBarChart` — volumes quotidiens), **multi-courbes ≤ 4 séries**
25 + (`MultiLineChart` — motifs de trait distincts, jamais la couleur seule),
26 + **barres empilées** (`StackedBarChart` — composition dans le temps).
27 + Sous les courbes clés : `StatSummary` (min/max/moyenne/médiane/écart-type).
28 +5. **Répartitions** : barres horizontales (`BarChart`, deltas optionnels),
29 + anneaux (`Donut`), **distributions/histogrammes** (`Histogram`).
30 +6. **Répartition géographique** (par ville/région) — barres horizontales
31 + triées (pas besoin de vraie carte).
32 +7. **Calendriers** : `CalendarHeatmap` (26 semaines) et, quand l'activité
33 + horaire est journalisée, `HourHeatmap` (7 jours × 24 h).
34 +8. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne,
21 35 pagination (25/pg), débordement horizontal propre sur mobile (.tbl-wrap).
22 −6. **Records & faits marquants** : générés depuis les données (jour record,
23 − plus forte croissance, meilleure entrée…) — cartes compactes.
24 −7. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir.
25 −8. **Bouton PDF** bien visible en haut : « Télécharger le rapport PDF » avec
26 − deux choix (Rapport complet / Synthèse 2 pages). Indicateur de progression
27 − si > 2 s.
36 + Viser 3 à 5 tableaux par plateforme.
37 +9. **Records & faits marquants** : générés depuis les données (jour record,
38 + plus forte croissance, meilleure entrée…) — cartes compactes, 6–12.
39 +10. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir.
40 +11. **Bouton PDF** bien visible en haut (`PdfButton`) : bouton principal
41 + « Rapport PDF complet » + menu « Autres rapports ▾ » listant les
42 + **5 rapports** (voir §3). Indicateur de progression si > 2 s.
28 43
29 44 Responsive : KPI empilés < 768 px, graphiques pleine largeur redimensionnés
30 45 (SVG viewBox), tableaux en défilement horizontal contenu, tactile ≥ 44 px.
31 46 AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré »
32 47 (carte grise propre), jamais un faux chiffre.
33 48
49 +Accessibilité (règles fermes) : un seul axe Y par graphique (jamais de
50 +double échelle) ; ≥ 2 séries ⇒ légende obligatoire ; l'identité d'une série
51 +multi-courbes passe par le **motif de trait** en plus de la couleur ; le
52 +texte reste en encre (jamais coloré à la couleur de série) ; chaque
53 +graphique a son infobulle de survol et un équivalent tableau existe.
54 +
34 55 ## 2. API — contrat commun
35 56
36 57 `GET /api/stats/dashboard?period=7j|30j|3m|6m|12m|annee|tout|auj&from=YYYY-MM-DD&to=YYYY-MM-DD`
37 58
38 59 ```jsonc
39 60 {
40 − "updated": "2026-08-17T21:04:00-04:00",
41 − "period": { "from": "2026-07-18", "to": "2026-08-17", "label": "30 jours" },
61 + "updated": "2026-08-19T01:00:00-04:00",
62 + "period": { "from": "2026-07-20", "to": "2026-08-19", "label": "30 jours" },
42 63 "kpis": [ { "id": "total", "label": "Annonces actives", "value": 33744,
43 − "unit": "", "delta_pct": 4.2, "direction": "up" } ],
64 + "unit": "", "delta_pct": 4.2, "direction": "up",
65 + "spark": [{ "t": "2026-08-01", "v": 31200 }] } ], // spark optionnel
66 + "gauges": [ { "id": "geo", "label": "Fiches géolocalisées", "value": 92,
67 + "max": 100, "unit": "%" } ], // optionnel
44 68 "series": [ { "id": "vol", "title": "Annonces actives par jour", "unit": "annonces",
45 − "kind": "line", "points": [{ "t": "2026-07-18", "v": 31200 }],
46 − "compare": [{ "t": "2025-07-18", "v": 24100 }] } ],
47 − "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut",
48 − "items": [{ "label": "4½", "value": 9120 }] } ],
69 + "kind": "line", // line | bar | area
70 + "points": [{ "t": "2026-07-20", "v": 31200 }],
71 + "compare": [{ "t": "2025-07-20", "v": 24100 }] } ],
72 + "multiseries": [ { "id": "seg", "title": "Prix médian par taille", "unit": "$",
73 + "series": [ { "label": "3½", "points": [/* … */] },
74 + { "label": "4½", "points": [/* … */] } ] } ], // ≤ 4
75 + "stacked": [ { "id": "src", "title": "Ajouts par source", "unit": "ajouts",
76 + "keys": ["Kijiji", "Centris", "Autres"],
77 + "points": [{ "t": "2026-08-01", "values": [120, 80, 30] }] } ],
78 + "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut", // donut | bars
79 + "items": [{ "label": "4½", "value": 9120, "delta_pct": 2.1 }] } ],
80 + "distributions": [ { "id": "prix", "title": "Distribution des loyers", "unit": "annonces",
81 + "bins": [{ "label": "800-1000$", "value": 3120 }] } ],
49 82 "geo": { "title": "Par région", "items": [{ "label": "Montréal", "value": 15680 }] },
50 83 "heatmap": { "title": "Activité", "cells": [{ "date": "2026-08-01", "value": 210 }] },
84 + "hourly": { "title": "Activité par heure",
85 + "cells": [{ "dow": 0, "hour": 9, "value": 40 }] }, // dow 0=lun … 6=dim
51 86 "tables": [ { "id": "top", "title": "Top villes", "columns": ["Ville", "Annonces", "Δ 30 j"],
52 87 "rows": [["Montréal", 15680, "+3,1 %"]] } ],
53 88 "records": [ { "label": "Jour record d'ajouts", "value": "412 annonces", "date": "2026-08-09" } ]
@@ -56,23 +91,40 @@ AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré »
56 91
57 92 Champs absents = section masquée. Cache serveur recommandé (≥ 5 min par
58 93 période). Les valeurs proviennent des données réelles (DB de la plateforme,
59 −journaux de sync des connecteurs, /api/v1/runs d'API-KA…).
94 +journaux de sync des connecteurs, /api/v1/runs d'API-KA…). Arrondir les
95 +`delta_pct` à 1 décimale côté serveur.
60 96
61 −`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese`
97 +## 3. Rapports PDF — 5 modes
98 +
99 +`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese|tendances|repartitions|donnees`
62 100 → `application/pdf`, en-tête `Content-Disposition: attachment; filename=
63 −groupe-ka_<plateforme>_stats_<periode>_<YYYY-MM-DD>.pdf`.
101 +groupe-ka_<plateforme>_stats_<periode>[_<mode>]_<YYYY-MM-DD>.pdf`
102 +(pas de suffixe pour `complet` — rétrocompatible v1 ; `kapdf.filename()`
103 +accepte maintenant `mode` en 3e argument).
104 +
105 +| Mode | Contenu |
106 +|---|---|
107 +| `complet` | tout : sommaire, KPI, jauges, séries + stats de séries, multi-séries, empilées, répartitions, distributions, géo, heatmap horaire, tableaux (200 lignes), records |
108 +| `synthese` | couverture + KPI + jauges + records (2–3 pages) |
109 +| `tendances` | KPI + toutes les séries temporelles + min/max/moy/méd/σ + records |
110 +| `repartitions` | breakdowns, distributions, géo, activité horaire |
111 +| `donnees` | tous les tableaux en version longue (400 lignes) |
64 112
65 −## 3. PDF — gabarit Groupe-KA (implémentations : `kapdf.py` fpdf2 pour les
66 −apps Python ; les apps Next portent le même gabarit en pdfkit)
113 +Un `mode` inconnu retombe sur `complet`. Le gabarit (implémentations :
114 +`kapdf.py` fpdf2 pour les apps Python ; les apps Next portent le même
115 +gabarit en pdfkit) :
67 116
68 117 - **Couverture** : cadre encre, kicker « GROUPE KA · RAPPORT STATISTIQUE »,
69 − wordmark de la plateforme (boîte encre + accent), sous-titre, période
70 − couverte, date/heure de génération, bande encre au pied avec
118 + wordmark de la plateforme (boîte encre + accent), **type de rapport**,
119 + période couverte, date/heure de génération, bande encre au pied avec
71 120 « par Groupe KA — groupe-ka.com ».
72 −- **Sommaire** avec numéros de pages (mode complet).
73 −- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré).
121 +- **Sommaire** avec numéros de pages (modes complet et donnees).
122 +- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré
123 + arrondi à 1 décimale). **Jauges** : demi-arcs accent.
74 124 - **Graphiques VECTORIELS** (dessinés en primitives, jamais de capture) :
75 − courbes, barres, anneaux — accent de la plateforme, axes/graduations encre.
125 + courbes/aires, barres verticales, multi-courbes (motifs distincts),
126 + empilées (nuances d'accent), anneaux, heatmap horaire — accent de la
127 + plateforme, axes/graduations encre.
76 128 - **Tableaux** paginés proprement (lignes zébrées `--surface-2`, jamais
77 129 coupés en deux à cheval sur une ligne).
78 130 - **Records** puis **page de fin** : coordonnées Groupe KA (3 courriels +
@@ -81,43 +133,53 @@ apps Python ; les apps Next portent le même gabarit en pdfkit)
81 133 - **Chaque page** : en-tête discret (« Groupe KA · {Plateforme} », filet
82 134 encre) + pied (« © Groupe-KA — {année} — groupe-ka.com · {période} · p. X/Y »).
83 135 - A4 portrait, marges 18 mm, typo : Helvetica (fallback sûr) ou fonts TTF du
84 − DS si présentes. Mode « synthese » = couverture + 1 page KPI/records.
136 + DS si présentes.
85 137
86 138 ## 4. Spécifique par plateforme (sections métier attendues)
87 139
88 −- **groupe-ka** : tableau de bord maître — consolidation des 12 (volume total,
89 − croissance), classement des plateformes, bloc résumé par plateforme + lien
140 +- **groupe-ka** : tableau de bord maître — consolidation des plateformes
141 + (volume total, croissance), classement, bloc résumé par plateforme + lien
90 142 vers sa page /stats ; « Rapport écosystème complet » = PDF consolidé.
91 143 - **lou-ka** : annonces actives/nouvelles/retirées, loyers moyens/médians par
92 − ville & taille, évolution, répartition par type, top villes.
93 −- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix moyen/médian
94 − par ville/région/type, délai de présence, top villes, tension du marché.
144 + ville & taille (multiseries), distribution des loyers, évolution,
145 + répartition par type, top villes, sources (stacked).
146 +- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix
147 + moyen/médian par ville/région/type (multiseries), distribution des prix,
148 + délai de présence, top villes, tension du marché.
95 149 - **vrai-prix** : couverture du rôle (unités, valeur totale), estimations
96 − servies si journalisées, répartitions par municipalité/type, indices marché.
97 −- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens et
98 − km moyens par segment, top marques/modèles.
99 −- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix,
100 − nouveautés par période, top catégories.
101 −- **food-ka** : produits suivis, relevés de prix, soldes détectés (baisses/
102 − hausses, amplitude), top produits en solde, prix moyens par catégorie.
103 −- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, nouveautés/
104 − fermetures détectées, top établissements.
150 + servies si journalisées, répartitions par municipalité/type, distribution
151 + des valeurs, indices marché.
152 +- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens
153 + et km moyens par segment (multiseries), distributions prix/km/année,
154 + top marques/modèles.
155 +- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix
156 + (distribution), nouveautés par période, top catégories.
157 +- **food-ka** : produits suivis, relevés de prix, soldes détectés
158 + (baisses/hausses, amplitude — stacked), top produits en solde, prix moyens
159 + par catégorie, distribution des rabais.
160 +- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, distribution
161 + des prix de plats, nouveautés/fermetures détectées, top établissements.
105 162 - **sorti-ka** : événements à venir/passés par catégorie/ville, gratuits vs
106 − payants, heatmap calendrier, top lieux.
107 −- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés, top
108 − créateurs, croissance du répertoire.
109 −- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h),
110 − erreurs, file frontier, tendances si les requêtes sont journalisées.
111 −- **api-ka** : appels par endpoint/jour/heure, latences moyennes + p95, taux
112 − d'erreur, top endpoints, uptime (données des middlewares de logging + runs).
113 −- **Transverse (tous)** : volume total agrégé + croissance, connecteurs actifs
114 − et éléments ajoutés/mis à jour par période (journaux de sync), complétude/
115 − fraîcheur moyenne des fiches quand mesurable. Trafic web : seulement si des
116 − journaux d'accès existent — sinon état vide propre.
163 + payants (stacked), heatmap calendrier + horaire, top lieux.
164 +- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés
165 + (stacked par plateforme), distribution des audiences, top créateurs,
166 + croissance du répertoire.
167 +- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h —
168 + hourly), erreurs, file frontier, tendances des requêtes journalisées.
169 +- **api-ka** : appels par endpoint/jour/heure (hourly), latences moyennes +
170 + p95 (multiseries), taux d'erreur, top endpoints/clés, uptime.
171 +- **job-ka** : offres actives/nouvelles/expirées par catégorie/ville/
172 + entreprise, distribution des salaires affichés, top employeurs.
173 +- **Transverse (tous)** : volume total agrégé + croissance, connecteurs
174 + actifs et éléments ajoutés/mis à jour par période (journaux de sync —
175 + stacked par source quand possible), complétude/fraîcheur moyenne des
176 + fiches quand mesurable (jauges). Trafic web : seulement si des journaux
177 + d'accès existent — sinon état vide propre.
117 178
118 179 ## 5. Ajouter une métrique / un graphique / une plateforme
119 180
120 −1 métrique = 1 entrée `kpis[]` ou `series[]` côté API (requête SQL agrégée +
121 −cache) — le front la rend automatiquement. 1 plateforme = implémenter les 2
122 −endpoints du contrat + une page /stats montée sur les composants du kit +
123 −`kapdf.py` (ou gabarit pdfkit) branché sur le même JSON de dashboard.
181 +1 métrique = 1 entrée `kpis[]`, `series[]`, `multiseries[]`, `stacked[]`,
182 +`distributions[]` ou `gauges[]` côté API (requête SQL agrégée + cache) — le
183 +front la rend automatiquement. 1 plateforme = implémenter les 2 endpoints du
184 +contrat + une page /stats montée sur les composants du kit + `kapdf.py` (ou
185 +gabarit pdfkit) branché sur le même JSON de dashboard.
modified frontend/src/ka/stats/kacharts.tsx +393 −30
@@ -2,22 +2,39 @@
2 2 // ka-ui/stats/kacharts.tsx — kit de graphiques SVG du module Stats commun
3 3 // Groupe KA (zéro dépendance, React 18+). Style : design system ka-ui
4 4 // (bordures encre, accent de la plateforme via var(--accent)).
5 −// Composants : KpiCard, PeriodSelector, LineChart (infobulle + légende
6 −// cliquable + comparaison N-1), BarChart, Donut, CalendarHeatmap, DataTable
7 −// (tri/recherche/pagination), RecordCard, PdfButton, EmptyBlock, Fraicheur.
8 −import { useMemo, useState } from "react";
5 +// v2 — composants : KpiCard (+sparkline), PeriodSelector, LineChart (ligne/
6 +// aire, infobulle + légende cliquable + comparaison N-1), MultiLineChart
7 +// (≤4 séries, pointillés distincts = jamais la couleur seule), VBarChart
8 +// (barres verticales / histogrammes), StackedBarChart, BarChart (horizontal,
9 +// deltas), Donut, GaugeCard, CalendarHeatmap, HourHeatmap (7×24),
10 +// StatSummary (min/max/moy/méd/σ), DataTable (tri/recherche/pagination),
11 +// RecordCard, PdfButton (menu de rapports), EmptyBlock, Fraicheur.
12 +import { useEffect, useMemo, useRef, useState } from "react";
9 13
10 −/* ---------- types (contrat SPEC.md) ---------- */
14 +/* ---------- types (contrat SPEC.md v2) ---------- */
11 15 export type Kpi = {
12 16 id: string; label: string; value: number | string; unit?: string;
13 17 delta_pct?: number | null; direction?: "up" | "down";
18 + spark?: Point[]; help?: string;
14 19 };
15 20 export type Point = { t: string; v: number };
16 21 export type Serie = {
17 − id: string; title: string; unit?: string; kind?: "line" | "bar";
22 + id: string; title: string; unit?: string;
23 + kind?: "line" | "bar" | "area";
18 24 points: Point[]; compare?: Point[];
19 25 };
20 −export type BreakItem = { label: string; value: number };
26 +export type MultiSerie = {
27 + id: string; title: string; unit?: string;
28 + series: { label: string; points: Point[] }[]; // ≤ 4 séries
29 +};
30 +export type StackedSerie = {
31 + id: string; title: string; unit?: string;
32 + keys: string[]; points: { t: string; values: number[] }[];
33 +};
34 +export type BreakItem = { label: string; value: number; delta_pct?: number | null };
35 +export type Distribution = { id: string; title: string; unit?: string; bins: { label: string; value: number }[] };
36 +export type Gauge = { id: string; label: string; value: number; max: number; unit?: string; help?: string };
37 +export type HourCell = { dow: number; hour: number; value: number }; // dow 0=lun … 6=dim
21 38 export type TableSpec = { id: string; title: string; columns: string[]; rows: (string | number)[][] };
22 39 export type RecordFact = { label: string; value: string; date?: string };
23 40
@@ -32,25 +49,63 @@ export const PERIODS: { id: string; label: string }[] = [
32 49 { id: "tout", label: "Tout" },
33 50 ];
34 51
52 +export const REPORT_MODES: { id: string; label: string; desc: string }[] = [
53 + { id: "complet", label: "Rapport complet", desc: "Toutes les sections — KPI, tendances, répartitions, tableaux, records" },
54 + { id: "synthese", label: "Synthèse exécutive", desc: "2 pages — indicateurs clés et faits marquants" },
55 + { id: "tendances", label: "Tendances & évolution", desc: "Courbes, comparaisons N-1 et statistiques de séries" },
56 + { id: "repartitions", label: "Répartitions & géographie", desc: "Catégories, distributions, régions et activité" },
57 + { id: "donnees", label: "Données détaillées", desc: "Tous les tableaux, en version longue" },
58 +];
59 +
35 60 export const fmtInt = (n: number) => n.toLocaleString("fr-CA");
36 61 export const fmtNum = (n: number) =>
37 62 Number.isInteger(n) ? fmtInt(n) : n.toLocaleString("fr-CA", { maximumFractionDigits: 2 });
63 +const fmtPct = (n: number) => `${n >= 0 ? "+" : ""}${fmtNum(n)} %`;
38 64
39 −/* ---------- KPI ---------- */
65 +/* Styles des séries multiples : couleur + motif de trait (l'identité n'est
66 + jamais portée par la couleur seule — règle d'accessibilité). */
67 +const MULTI_STYLES = [
68 + { stroke: "var(--accent)", dash: undefined, width: 2.4 },
69 + { stroke: "var(--ink)", dash: undefined, width: 1.6 },
70 + { stroke: "var(--accent-deep, var(--accent))", dash: "6 3", width: 2 },
71 + { stroke: "var(--ink-3)", dash: "2 3", width: 2 },
72 +];
73 +
74 +/* ---------- KPI (+ sparkline) ---------- */
40 75 export function KpiCard({ k }: { k: Kpi }) {
41 76 const up = (k.direction ?? ((k.delta_pct ?? 0) >= 0 ? "up" : "down")) === "up";
77 + const sp = (k.spark ?? []).filter((p) => typeof p.v === "number");
78 + const spark = useMemo(() => {
79 + if (sp.length < 2) return null;
80 + const w = 120, h = 30;
81 + const vmax = Math.max(...sp.map((p) => p.v));
82 + const vmin = Math.min(...sp.map((p) => p.v));
83 + const rng = vmax - vmin || 1;
84 + const X = (i: number) => (w * i) / (sp.length - 1);
85 + const Y = (v: number) => 2 + (h - 4) * (1 - (v - vmin) / rng);
86 + const d = sp.map((p, i) => `${i ? "L" : "M"}${X(i).toFixed(1)},${Y(p.v).toFixed(1)}`).join("");
87 + return { w, h, d, area: `${d}L${w},${h}L0,${h}Z` };
88 + }, [k.spark]);
42 89 return (
43 − <article className="card" style={{ padding: "14px 16px", minWidth: 0 }}>
90 + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={k.help}>
44 91 <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px,2.4vw,30px)", letterSpacing: "-0.02em" }}>
45 92 {typeof k.value === "number" ? fmtNum(k.value) : k.value}
46 93 {k.unit ? <span style={{ fontSize: "0.6em", color: "var(--ink-2)" }}> {k.unit}</span> : null}
47 94 </p>
48 95 <p className="klabel" style={{ margin: "6px 0 0" }}>{k.label}</p>
49 − {k.delta_pct !== undefined && k.delta_pct !== null && (
50 − <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}>
51 − {up ? "▲" : "▼"} {k.delta_pct >= 0 ? "+" : ""}{fmtNum(k.delta_pct)} % <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span>
52 − </p>
53 − )}
96 + <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 8 }}>
97 + {k.delta_pct !== undefined && k.delta_pct !== null ? (
98 + <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}>
99 + {up ? "▲" : "▼"} {fmtPct(k.delta_pct)} <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span>
100 + </p>
101 + ) : <span />}
102 + {spark && (
103 + <svg viewBox={`0 0 ${spark.w} ${spark.h}`} style={{ width: 96, height: 24, flex: "none" }} aria-hidden="true">
104 + <path d={spark.area} fill="var(--accent)" opacity={0.14} />
105 + <path d={spark.d} fill="none" stroke="var(--accent)" strokeWidth={1.8} />
106 + </svg>
107 + )}
108 + </div>
54 109 </article>
55 110 );
56 111 }
@@ -84,12 +139,13 @@ export function PeriodSelector({
84 139 );
85 140 }
86 141
87 −/* ---------- Courbe ---------- */
142 +/* ---------- Courbe / aire ---------- */
88 143 export function LineChart({ serie, height = 240 }: { serie: Serie; height?: number }) {
89 144 const [hide, setHide] = useState<{ cur: boolean; cmp: boolean }>({ cur: false, cmp: false });
90 145 const [hover, setHover] = useState<number | null>(null);
91 146 const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
92 147 const pts = serie.points ?? [];
148 + if (serie.kind === "bar") return <VBarChart serie={serie} height={height} />;
93 149 if (pts.length < 2) return <EmptyBlock title={serie.title} />;
94 150 const all = [...(hide.cur ? [] : pts), ...(!hide.cmp && serie.compare ? serie.compare : [])];
95 151 const vmax = Math.max(...all.map((p) => p.v), 1);
@@ -127,6 +183,9 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb
127 183 {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => (
128 184 <text key={i} x={X(i, pts.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>
129 185 ))}
186 + {serie.kind === "area" && !hide.cur && (
187 + <path d={`${path(pts)}L${X(pts.length - 1, pts.length)},${Y(0)}L${X(0, pts.length)},${Y(0)}Z`} fill="var(--accent)" opacity={0.13} />
188 + )}
130 189 {!hide.cmp && serie.compare && serie.compare.length > 1 && (
131 190 <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" />
132 191 )}
@@ -148,17 +207,211 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb
148 207 );
149 208 }
150 209
151 −function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off: boolean; dashed?: boolean; onClick: () => void }) {
210 +function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off?: boolean; dashed?: boolean; onClick?: () => void }) {
152 211 return (
153 − <button type="button" onClick={onClick} aria-pressed={!off}
154 − style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: "pointer", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}>
212 + <button type="button" onClick={onClick} aria-pressed={!off} disabled={!onClick}
213 + style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: onClick ? "pointer" : "default", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}>
155 214 <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} />
156 215 {label}
157 216 </button>
158 217 );
159 218 }
160 219
161 −/* ---------- Barres horizontales (répartitions, géo) ---------- */
220 +/* ---------- Multi-courbes (≤ 4 séries, motifs distincts) ---------- */
221 +export function MultiLineChart({ ms, height = 260 }: { ms: MultiSerie; height?: number }) {
222 + const series = (ms.series ?? []).filter((s) => (s.points ?? []).length > 1).slice(0, 4);
223 + const [off, setOff] = useState<Record<string, boolean>>({});
224 + const [hover, setHover] = useState<number | null>(null);
225 + if (!series.length) return <EmptyBlock title={ms.title} />;
226 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
227 + const n = Math.max(...series.map((s) => s.points.length));
228 + const shown = series.filter((s) => !off[s.label]);
229 + const all = shown.flatMap((s) => s.points.map((p) => p.v));
230 + const vmax = Math.max(...(all.length ? all : [1]), 1);
231 + const vmin = Math.min(0, ...(all.length ? all : [0]));
232 + const X = (i: number, len: number) => PL + ((W - PL - PR) * i) / (len - 1);
233 + const Y = (v: number) => PT + (H - PT - PB) * (1 - (v - vmin) / (vmax - vmin || 1));
234 + const ref = series[0].points;
235 + const hi = hover !== null ? Math.min(n - 1, Math.max(0, hover)) : null;
236 + return (
237 + <figure className="card" style={{ margin: 0, padding: 16 }}>
238 + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
239 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{ms.title}</b>
240 + <span style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
241 + {series.map((s, i) => (
242 + <LegendChip key={s.label} label={s.label} color={MULTI_STYLES[i].stroke}
243 + dashed={!!MULTI_STYLES[i].dash} off={!!off[s.label]}
244 + onClick={() => setOff((o) => ({ ...o, [s.label]: !o[s.label] }))} />
245 + ))}
246 + </span>
247 + </figcaption>
248 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10, touchAction: "pan-y" }} role="img" aria-label={ms.title}
249 + onMouseMove={(e) => {
250 + const r = (e.currentTarget as SVGSVGElement).getBoundingClientRect();
251 + const fx = ((e.clientX - r.left) / r.width) * W;
252 + setHover(Math.round(((fx - PL) / (W - PL - PR)) * (n - 1)));
253 + }}
254 + onMouseLeave={() => setHover(null)}>
255 + {[0, 1, 2, 3, 4].map((g) => {
256 + const y = PT + ((H - PT - PB) * g) / 4;
257 + const v = vmax - ((vmax - vmin) * g) / 4;
258 + return (
259 + <g key={g}>
260 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
261 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>
262 + </g>
263 + );
264 + })}
265 + {[0, Math.floor(ref.length / 2), ref.length - 1].map((i) => (
266 + <text key={i} x={X(i, ref.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{ref[i]?.t}</text>
267 + ))}
268 + {series.map((s, i) => off[s.label] ? null : (
269 + <path key={s.label}
270 + d={s.points.map((p, j) => `${j ? "L" : "M"}${X(j, s.points.length)},${Y(p.v)}`).join("")}
271 + fill="none" stroke={MULTI_STYLES[i].stroke} strokeWidth={MULTI_STYLES[i].width}
272 + strokeDasharray={MULTI_STYLES[i].dash} />
273 + ))}
274 + {hi !== null && (
275 + <line x1={X(hi, n)} x2={X(hi, n)} y1={PT} y2={H - PB} stroke="var(--ink)" strokeWidth={1} strokeDasharray="2 3" />
276 + )}
277 + </svg>
278 + {hi !== null && (
279 + <p className="chip" style={{ marginTop: 8, display: "inline-flex", gap: 12, flexWrap: "wrap" }}>
280 + <b>{ref[hi]?.t}</b>
281 + {shown.map((s, i) => (
282 + <span key={s.label}>{s.label} : <b>{s.points[hi] ? fmtNum(s.points[hi].v) : "—"}{ms.unit ? ` ${ms.unit}` : ""}</b></span>
283 + ))}
284 + </p>
285 + )}
286 + </figure>
287 + );
288 +}
289 +
290 +/* ---------- Barres verticales (volumes quotidiens, histogrammes) ---------- */
291 +export function VBarChart({ serie, height = 240 }: { serie: Serie; height?: number }) {
292 + const [hover, setHover] = useState<number | null>(null);
293 + const pts = serie.points ?? [];
294 + if (!pts.length) return <EmptyBlock title={serie.title} />;
295 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
296 + const vmax = Math.max(...pts.map((p) => p.v), 1);
297 + const bw = Math.max(2, (W - PL - PR) / pts.length - 2);
298 + return (
299 + <figure className="card" style={{ margin: 0, padding: 16 }}>
300 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{serie.title}</b></figcaption>
301 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10 }} role="img" aria-label={serie.title}
302 + onMouseLeave={() => setHover(null)}>
303 + {[0, 1, 2, 3, 4].map((g) => {
304 + const y = PT + ((H - PT - PB) * g) / 4;
305 + const v = vmax - (vmax * g) / 4;
306 + return (
307 + <g key={g}>
308 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
309 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>
310 + </g>
311 + );
312 + })}
313 + {pts.map((p, i) => {
314 + const x = PL + ((W - PL - PR) * i) / pts.length;
315 + const h = (H - PT - PB) * (p.v / vmax);
316 + return (
317 + <rect key={i} x={x + 1} y={H - PB - h} width={bw} height={Math.max(h, p.v > 0 ? 1.5 : 0)} rx={2}
318 + fill="var(--accent)" opacity={hover === null || hover === i ? 1 : 0.45}
319 + stroke="var(--ink)" strokeWidth={0.5}
320 + onMouseEnter={() => setHover(i)}>
321 + <title>{`${p.t} — ${fmtNum(p.v)}${serie.unit ? ` ${serie.unit}` : ""}`}</title>
322 + </rect>
323 + );
324 + })}
325 + {[0, Math.floor(pts.length / 2), pts.length - 1].filter((v, i, a) => a.indexOf(v) === i).map((i) => (
326 + <text key={i} x={PL + ((W - PL - PR) * (i + 0.5)) / pts.length} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>
327 + ))}
328 + </svg>
329 + {hover !== null && (
330 + <p className="chip" style={{ marginTop: 8 }}>{pts[hover].t} — <b>{fmtNum(pts[hover].v)}{serie.unit ? ` ${serie.unit}` : ""}</b></p>
331 + )}
332 + </figure>
333 + );
334 +}
335 +
336 +/* ---------- Histogramme (distribution) ---------- */
337 +export function Histogram({ dist }: { dist: Distribution }) {
338 + const serie: Serie = {
339 + id: dist.id, title: dist.title, unit: dist.unit, kind: "bar",
340 + points: (dist.bins ?? []).map((b) => ({ t: b.label, v: b.value })),
341 + };
342 + return <VBarChart serie={serie} height={220} />;
343 +}
344 +
345 +/* ---------- Barres empilées (composition dans le temps) ---------- */
346 +export function StackedBarChart({ st, height = 260 }: { st: StackedSerie; height?: number }) {
347 + const [hover, setHover] = useState<number | null>(null);
348 + const keys = (st.keys ?? []).slice(0, 6);
349 + const pts = st.points ?? [];
350 + if (!keys.length || !pts.length) return <EmptyBlock title={st.title} />;
351 + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;
352 + const totals = pts.map((p) => p.values.slice(0, keys.length).reduce((s, v) => s + (v || 0), 0));
353 + const vmax = Math.max(...totals, 1);
354 + const bw = Math.max(2, (W - PL - PR) / pts.length - 2);
355 + const shades = [1, 0.72, 0.5, 0.34, 0.22, 0.13];
356 + return (
357 + <figure className="card" style={{ margin: 0, padding: 16 }}>
358 + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>
359 + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{st.title}</b>
360 + <span style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
361 + {keys.map((k, i) => (
362 + <span key={k} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em" }}>
363 + <span style={{ width: 11, height: 11, borderRadius: 3, border: "1px solid var(--ink)", background: "var(--accent)", opacity: shades[i] }} />
364 + {k}
365 + </span>
366 + ))}
367 + </span>
368 + </figcaption>
369 + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10 }} role="img" aria-label={st.title}
370 + onMouseLeave={() => setHover(null)}>
371 + {[0, 1, 2, 3, 4].map((g) => {
372 + const y = PT + ((H - PT - PB) * g) / 4;
373 + return (
374 + <g key={g}>
375 + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />
376 + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(vmax - (vmax * g) / 4))}</text>
377 + </g>
378 + );
379 + })}
380 + {pts.map((p, i) => {
381 + const x = PL + ((W - PL - PR) * i) / pts.length;
382 + let yAcc = H - PB;
383 + return (
384 + <g key={i} onMouseEnter={() => setHover(i)} opacity={hover === null || hover === i ? 1 : 0.5}>
385 + {keys.map((k, j) => {
386 + const v = p.values[j] || 0;
387 + const h = (H - PT - PB) * (v / vmax);
388 + yAcc -= h;
389 + return v > 0 ? (
390 + <rect key={k} x={x + 1} y={yAcc} width={bw} height={Math.max(h - 1, 0.8)} rx={1.5}
391 + fill="var(--accent)" opacity={shades[j]} stroke="var(--ink)" strokeWidth={0.4}>
392 + <title>{`${p.t} · ${k} — ${fmtNum(v)}${st.unit ? ` ${st.unit}` : ""}`}</title>
393 + </rect>
394 + ) : null;
395 + })}
396 + </g>
397 + );
398 + })}
399 + {[0, Math.floor(pts.length / 2), pts.length - 1].filter((v, i, a) => a.indexOf(v) === i).map((i) => (
400 + <text key={i} x={PL + ((W - PL - PR) * (i + 0.5)) / pts.length} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>
401 + ))}
402 + </svg>
403 + {hover !== null && (
404 + <p className="chip" style={{ marginTop: 8, display: "inline-flex", gap: 12, flexWrap: "wrap" }}>
405 + <b>{pts[hover].t}</b>
406 + {keys.map((k, j) => <span key={k}>{k} : <b>{fmtNum(pts[hover].values[j] || 0)}</b></span>)}
407 + <span style={{ color: "var(--ink-3)" }}>total {fmtNum(totals[hover])}</span>
408 + </p>
409 + )}
410 + </figure>
411 + );
412 +}
413 +
414 +/* ---------- Barres horizontales (répartitions, géo) — deltas optionnels ---------- */
162 415 export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) {
163 416 const rows = (items ?? []).slice(0, 14);
164 417 if (!rows.length) return <EmptyBlock title={title} />;
@@ -169,9 +422,16 @@ export function BarChart({ title, items, unit }: { title: string; items: BreakIt
169 422 <div style={{ marginTop: 12, display: "grid", gap: 9 }}>
170 423 {rows.map((r) => (
171 424 <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}>
172 − <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>
425 + <div style={{ display: "flex", justifyContent: "space-between", gap: 8, fontSize: 12.5 }}>
173 426 <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>
174 − <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b>
427 + <span style={{ display: "inline-flex", gap: 8, alignItems: "baseline", flex: "none" }}>
428 + {r.delta_pct !== undefined && r.delta_pct !== null && (
429 + <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 700, color: r.delta_pct >= 0 ? "var(--green)" : "var(--danger)" }}>
430 + {r.delta_pct >= 0 ? "▲" : "▼"} {fmtPct(r.delta_pct)}
431 + </span>
432 + )}
433 + <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b>
434 + </span>
175 435 </div>
176 436 <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}>
177 437 <div style={{ height: "100%", width: `${Math.max((r.value / max) * 100, 1)}%`, background: "var(--accent)", border: "1px solid var(--ink)", borderRadius: "0 3px 3px 0", boxSizing: "border-box" }} />
@@ -224,6 +484,26 @@ export function Donut({ title, items }: { title: string; items: BreakItem[] }) {
224 484 );
225 485 }
226 486
487 +/* ---------- Jauge (taux, complétude, couverture) ---------- */
488 +export function GaugeCard({ g }: { g: Gauge }) {
489 + const frac = Math.max(0, Math.min(1, g.max ? g.value / g.max : 0));
490 + const R = 60, C = Math.PI * R;
491 + return (
492 + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={g.help}>
493 + <svg viewBox="0 0 150 84" style={{ width: "100%", maxWidth: 190, display: "block", margin: "0 auto" }} role="img" aria-label={`${g.label} : ${fmtNum(g.value)}${g.unit ?? ""} sur ${fmtNum(g.max)}`}>
494 + <path d={`M15,75 A${R},${R} 0 0 1 135,75`} fill="none" stroke="rgba(20,24,20,0.08)" strokeWidth={13} strokeLinecap="round" />
495 + <path d={`M15,75 A${R},${R} 0 0 1 135,75`} fill="none" stroke="var(--accent)" strokeWidth={13} strokeLinecap="round"
496 + strokeDasharray={`${frac * C} ${C}`} />
497 + <text x={75} y={66} textAnchor="middle" fontFamily="var(--font-display)" fontWeight={700} fontSize={22} fill="var(--ink)">
498 + {fmtNum(g.value)}{g.unit ? <tspan fontSize={12} fill="var(--ink-2)"> {g.unit}</tspan> : null}
499 + </text>
500 + <text x={75} y={80} textAnchor="middle" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{(frac * 100).toFixed(0)} % de {fmtNum(g.max)}{g.unit ? ` ${g.unit}` : ""}</text>
501 + </svg>
502 + <p className="klabel" style={{ margin: "8px 0 0", textAlign: "center" }}>{g.label}</p>
503 + </article>
504 + );
505 +}
506 +
227 507 /* ---------- Calendrier de chaleur ---------- */
228 508 export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) {
229 509 if (!cells?.length) return <EmptyBlock title={title} />;
@@ -261,6 +541,64 @@ export function CalendarHeatmap({ title, cells }: { title: string; cells: { date
261 541 );
262 542 }
263 543
544 +/* ---------- Heatmap horaire 7 × 24 (activité par heure) ---------- */
545 +const DOW = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];
546 +export function HourHeatmap({ title, cells }: { title: string; cells: HourCell[] }) {
547 + if (!cells?.length) return <EmptyBlock title={title} />;
548 + const grid = new Map(cells.map((c) => [`${c.dow}-${c.hour}`, c.value]));
549 + const max = Math.max(...cells.map((c) => c.value), 1);
550 + const CW = 24, CH = 20, LX = 34, LY = 16;
551 + return (
552 + <figure className="card" style={{ margin: 0, padding: 16 }}>
553 + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b> <span className="klabel">jour × heure</span></figcaption>
554 + <div className="tbl-wrap" style={{ marginTop: 12 }}>
555 + <svg viewBox={`0 0 ${LX + 24 * CW} ${LY + 7 * CH}`} style={{ minWidth: 520, width: "100%", height: "auto" }} role="img" aria-label={title}>
556 + {[0, 6, 12, 18, 23].map((h) => (
557 + <text key={h} x={LX + h * CW + CW / 2} y={11} textAnchor="middle" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{h} h</text>
558 + ))}
559 + {DOW.map((d, i) => (
560 + <text key={d} x={LX - 6} y={LY + i * CH + CH / 2 + 3} textAnchor="end" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{d}</text>
561 + ))}
562 + {Array.from({ length: 7 }, (_, d) => Array.from({ length: 24 }, (_, h) => {
563 + const v = grid.get(`${d}-${h}`) ?? 0;
564 + return (
565 + <rect key={`${d}-${h}`} x={LX + h * CW} y={LY + d * CH} width={CW - 2} height={CH - 2} rx={2.5}
566 + fill={v ? "var(--accent)" : "rgba(20,24,20,0.07)"} fillOpacity={v ? 0.22 + 0.78 * (v / max) : 1}
567 + stroke="rgba(20,24,20,0.15)" strokeWidth={0.5}>
568 + <title>{`${DOW[d]} ${h} h — ${fmtNum(v)}`}</title>
569 + </rect>
570 + );
571 + }))}
572 + </svg>
573 + </div>
574 + </figure>
575 + );
576 +}
577 +
578 +/* ---------- Statistiques de série (min/max/moy/méd/σ) ---------- */
579 +export function StatSummary({ serie }: { serie: Serie }) {
580 + const vs = (serie.points ?? []).map((p) => p.v).filter((v) => typeof v === "number");
581 + if (vs.length < 2) return null;
582 + const sorted = [...vs].sort((a, b) => a - b);
583 + const mean = vs.reduce((s, v) => s + v, 0) / vs.length;
584 + const med = sorted[Math.floor(sorted.length / 2)];
585 + const sd = Math.sqrt(vs.reduce((s, v) => s + (v - mean) ** 2, 0) / vs.length);
586 + const items: [string, number][] = [
587 + ["Min", sorted[0]], ["Max", sorted[sorted.length - 1]],
588 + ["Moyenne", Math.round(mean * 100) / 100], ["Médiane", med],
589 + ["Écart-type", Math.round(sd * 100) / 100],
590 + ];
591 + return (
592 + <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 }}>
593 + {items.map(([l, v]) => (
594 + <span key={l} className="chip" style={{ fontSize: 11 }}>
595 + <span style={{ color: "var(--ink-3)" }}>{l}</span> <b style={{ fontFamily: "var(--font-mono)" }}>{fmtNum(v)}</b>
596 + </span>
597 + ))}
598 + </div>
599 + );
600 +}
601 +
264 602 /* ---------- Tableau : tri, recherche, pagination ---------- */
265 603 export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) {
266 604 const [q, setQ] = useState("");
@@ -338,9 +676,19 @@ export function RecordCard({ r }: { r: RecordFact }) {
338 676 );
339 677 }
340 678
341 −/* ---------- Bouton PDF ---------- */
679 +/* ---------- Menu de rapports PDF (5 rapports) ---------- */
342 680 export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) {
343 − const [busy, setBusy] = useState(false);
681 + const [open, setOpen] = useState(false);
682 + const [busy, setBusy] = useState<string | null>(null);
683 + const box = useRef<HTMLSpanElement>(null);
684 + useEffect(() => {
685 + if (!open) return;
686 + const close = (e: MouseEvent) => {
687 + if (box.current && !box.current.contains(e.target as Node)) setOpen(false);
688 + };
689 + document.addEventListener("mousedown", close);
690 + return () => document.removeEventListener("mousedown", close);
691 + }, [open]);
344 692 const url = (mode: string) => {
345 693 const p = new URLSearchParams({ period, mode });
346 694 if (from) p.set("from", from);
@@ -348,23 +696,38 @@ export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }:
348 696 return `${endpoint}?${p}`;
349 697 };
350 698 const dl = (mode: string) => {
351 − setBusy(true);
699 + setBusy(mode);
700 + setOpen(false);
352 701 const a = document.createElement("a");
353 702 a.href = url(mode);
354 703 a.download = "";
355 704 document.body.appendChild(a);
356 705 a.click();
357 706 a.remove();
358 − setTimeout(() => setBusy(false), 2500);
707 + setTimeout(() => setBusy(null), 3000);
359 708 };
360 709 return (
361 − <span style={{ display: "inline-flex", gap: 8, flexWrap: "wrap" }}>
362 − <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={busy}>
363 − {busy ? "Génération…" : "⬇ Télécharger le rapport PDF"}
710 + <span ref={box} style={{ position: "relative", display: "inline-flex", gap: 8, flexWrap: "wrap" }}>
711 + <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={!!busy}>
712 + {busy ? "Génération…" : "⬇ Rapport PDF complet"}
364 713 </button>
365 − <button type="button" className="btn btn-ghost" onClick={() => dl("synthese")} disabled={busy}>
366 − Synthèse (2 p.)
714 + <button type="button" className="btn btn-ghost" onClick={() => setOpen((o) => !o)} disabled={!!busy}
715 + aria-haspopup="menu" aria-expanded={open}>
716 + Autres rapports ▾
367 717 </button>
718 + {open && (
719 + <div role="menu" className="card" style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, zIndex: 50, minWidth: 300, padding: 6, background: "var(--surface)", boxShadow: "0 10px 28px rgba(20,24,20,0.18)" }}>
720 + {REPORT_MODES.map((m) => (
721 + <button key={m.id} type="button" role="menuitem" onClick={() => dl(m.id)}
722 + style={{ display: "block", width: "100%", textAlign: "left", border: 0, background: "none", cursor: "pointer", padding: "9px 10px", borderRadius: 6 }}
723 + onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-2)")}
724 + onMouseLeave={(e) => (e.currentTarget.style.background = "none")}>
725 + <b style={{ display: "block", fontSize: 13, fontFamily: "var(--font-display)" }}>{m.label}</b>
726 + <span className="klabel" style={{ fontSize: 11 }}>{m.desc}</span>
727 + </button>
728 + ))}
729 + </div>
730 + )}
368 731 </span>
369 732 );
370 733 }
modified frontend/src/ka/stats/kapdf.py +390 −76
@@ -1,10 +1,17 @@
1 1 # Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 −# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2).
2 +# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2). v2
3 3 # Consomme le JSON du contrat /api/stats/dashboard (voir SPEC.md) et produit
4 −# le rapport estampillé Groupe-KA : couverture, sommaire, KPI, graphiques
5 −# VECTORIELS (courbes/barres/anneaux), tableaux paginés, records, page de fin.
4 +# les rapports estampillés Groupe-KA. 5 modes :
5 +# complet — toutes les sections (KPI, jauges, séries + stats, multi-
6 +# séries, empilées, distributions, répartitions, géo,
7 +# heatmap horaire, tableaux, records)
8 +# synthese — couverture + KPI + records (2-3 pages)
9 +# tendances — KPI + toutes les séries temporelles + stats de séries
10 +# repartitions — breakdowns, distributions, géo, activité horaire
11 +# donnees — tous les tableaux en version longue (400 lignes max)
12 +# Graphiques VECTORIELS uniquement (primitives fpdf), accent de la marque.
6 13 # Usage :
7 −# from kapdf import GroupeKAReport
14 +# from kapdf import GroupeKAReport, REPORT_MODES, filename
8 15 # pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00",
9 16 # "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json,
10 17 # mode="complet").build()
@@ -26,6 +33,14 @@ GREEN = (28, 92, 65)
26 33 DANGER = (179, 66, 58)
27 34 WHITE = (255, 255, 255)
28 35
36 +REPORT_MODES = {
37 + "complet": "Rapport complet",
38 + "synthese": "Synthèse exécutive",
39 + "tendances": "Tendances & évolution",
40 + "repartitions": "Répartitions & géographie",
41 + "donnees": "Données détaillées",
42 +}
43 +
29 44 EMAILS = [
30 45 ("contact@groupe-ka.com", "Projets, partenariats & données"),
31 46 ("info@groupe-ka.com", "Médias & questions générales"),
@@ -52,7 +67,8 @@ def _fr(n) -> str:
52 67 _SUBST = {
53 68 "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",
54 69 "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',
55 − "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
70 + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
71 + "×": "x", "·": ".", "σ": "sigma", "Δ": "delta",
56 72 }
57 73
58 74
@@ -75,12 +91,11 @@ class _PDF(FPDF):
75 91 self.accent = accent
76 92 self.period_label = period_label
77 93 self.cover_mode = False
78 − self.has_cover = False
79 94 self.set_margins(18, 20, 18)
80 95 self.set_auto_page_break(True, margin=22)
81 96
82 97 def header(self):
83 − if self.cover_mode or (self.has_cover and self.page_no() == 1):
98 + if self.cover_mode or self.page_no() == 1:
84 99 return
85 100 self.set_font("helvetica", "B", 8.5)
86 101 self.set_text_color(*INK)
@@ -96,10 +111,9 @@ class _PDF(FPDF):
96 111 self.set_y(20)
97 112
98 113 def footer(self):
99 − # la couverture (page 1) ne porte jamais le pied de page standard :
100 − # son footer se déclenche au add_page suivant, quand cover_mode est
101 − # déjà retombé — on la repère donc par son numéro de page.
102 − if self.cover_mode or (self.has_cover and self.page_no() == 1):
114 + # page 1 = couverture (le flag cover_mode est déjà retombé quand
115 + # add_page() clôt la page 1 → tester aussi le numéro de page)
116 + if self.cover_mode or self.page_no() == 1:
103 117 return
104 118 self.set_y(-15)
105 119 self.set_draw_color(*INK3)
@@ -116,7 +130,7 @@ class GroupeKAReport:
116 130 def __init__(self, site: dict, dashboard: dict, mode: str = "complet"):
117 131 self.site = site
118 132 self.d = dashboard
119 − self.mode = mode
133 + self.mode = mode if mode in REPORT_MODES else "complet"
120 134 self.accent = _hex(site.get("accent", "#d9f26b"))
121 135 period = dashboard.get("period", {}) or {}
122 136 self.period_label = period.get("label") or "toute la période"
@@ -131,6 +145,11 @@ class GroupeKAReport:
131 145 p.set_fill_color(*fill)
132 146 p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)
133 147
148 + def _shade(self, i, n=8):
149 + shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
150 + f = shades[i % len(shades)]
151 + return tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
152 +
134 153 def _kicker(self, text):
135 154 p = self.pdf
136 155 p.set_font("helvetica", "B", 8)
@@ -154,11 +173,18 @@ class GroupeKAReport:
154 173 self.toc.append((title, self.pdf.page_no()))
155 174 self.pdf.ln(11)
156 175
176 + def _chart_title(self, title):
177 + p = self.pdf
178 + p.set_font("helvetica", "B", 10)
179 + p.set_text_color(*INK)
180 + p.set_x(p.l_margin)
181 + p.cell(0, 6, title)
182 + p.ln(7)
183 +
157 184 # ---------- pages ----------
158 185 def _cover(self):
159 186 p = self.pdf
160 187 p.cover_mode = True
161 − p.has_cover = True
162 188 p.set_auto_page_break(False)
163 189 p.add_page()
164 190 p.set_fill_color(*PAPER)
@@ -166,12 +192,10 @@ class GroupeKAReport:
166 192 p.set_draw_color(*INK)
167 193 p.set_line_width(1.0)
168 194 p.rect(10, 10, 190, 277)
169 − # kicker
170 195 p.set_font("helvetica", "B", 10)
171 196 p.set_text_color(*GREEN)
172 197 p.set_xy(24, 34)
173 198 p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE")
174 − # wordmark : partie gauche + boîte encre/accent
175 199 wm = self.site.get("wordmark", "")
176 200 left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)
177 201 p.set_xy(24, 70)
@@ -189,7 +213,7 @@ class GroupeKAReport:
189 213 p.set_xy(24, 100)
190 214 p.set_font("helvetica", "", 13)
191 215 p.set_text_color(*INK2)
192 − p.multi_cell(150, 7, f"Rapport statistique — {wm}")
216 + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}")
193 217 now = datetime.now(ZoneInfo("America/Toronto"))
194 218 per = self.d.get("period", {}) or {}
195 219 p.set_xy(24, 125)
@@ -198,7 +222,7 @@ class GroupeKAReport:
198 222 ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),
199 223 ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),
200 224 ("Plateforme", "https://" + self.site.get("domain", "")),
201 − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"),
225 + ("Type de rapport", REPORT_MODES[self.mode]),
202 226 ]
203 227 y = 128
204 228 for k, v in rows:
@@ -210,7 +234,6 @@ class GroupeKAReport:
210 234 p.cell(0, 6, str(v))
211 235 p.set_font("helvetica", "", 10.5)
212 236 y += 8
213 − # bande encre au pied
214 237 p.set_fill_color(*INK)
215 238 p.rect(10, 262, 190, 25, style="F")
216 239 p.set_xy(24, 270)
@@ -235,7 +258,7 @@ class GroupeKAReport:
235 258 p = self.pdf
236 259 cols, gw, gh, gap = 3, 56, 26, 3
237 260 x0, y = p.l_margin, p.get_y()
238 − for i, k in enumerate(kpis[:9]):
261 + for i, k in enumerate(kpis[:12]):
239 262 x = x0 + (i % cols) * (gw + gap)
240 263 if i and i % cols == 0:
241 264 y += gh + gap
@@ -257,20 +280,81 @@ class GroupeKAReport:
257 280 p.set_font("helvetica", "B", 8)
258 281 p.set_text_color(*(GREEN if up else DANGER))
259 282 arrow = "+" if k["delta_pct"] >= 0 else ""
260 − p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(k['delta_pct']).replace('.', ',')} % vs période préc.")
283 + dv = round(float(k["delta_pct"]), 1)
284 + dv = int(dv) if float(dv).is_integer() else dv
285 + p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(dv).replace('.', ',')} % vs période préc.")
261 286 p.set_y(y + gh + 8)
262 287
263 − def _line_chart(self, s):
288 + def _gauges(self):
289 + gs = self.d.get("gauges") or []
290 + gs = [g for g in gs if isinstance(g.get("value"), (int, float)) and g.get("max")]
291 + if not gs:
292 + return
293 + self._section_title("Taux & couvertures")
294 + p = self.pdf
295 + cols, gw, gh, gap = 3, 56, 34, 3
296 + x0, y = p.l_margin, p.get_y()
297 + for i, g in enumerate(gs[:9]):
298 + x = x0 + (i % cols) * (gw + gap)
299 + if i and i % cols == 0:
300 + y += gh + gap
301 + if y > 240:
302 + p.add_page(); y = p.get_y()
303 + self._card(x, y, gw, gh)
304 + frac = max(0.0, min(1.0, g["value"] / g["max"]))
305 + cx, cy, r = x + gw / 2, y + 20, 14
306 + # arc de fond + arc de valeur (demi-cercle en petits segments)
307 + for pass_col, pass_frac, lw in (((225, 223, 217), 1.0, 2.6), (self.accent, frac, 2.6)):
308 + p.set_draw_color(*pass_col)
309 + p.set_line_width(lw)
310 + steps = max(2, int(60 * pass_frac))
311 + last = None
312 + for st in range(steps + 1):
313 + a = math.pi + math.pi * pass_frac * st / steps
314 + pt = (cx + r * math.cos(a), cy + r * math.sin(a))
315 + if last:
316 + p.line(last[0], last[1], pt[0], pt[1])
317 + last = pt
318 + p.set_font("helvetica", "B", 11)
319 + p.set_text_color(*INK)
320 + p.set_xy(x + 4, cy - 5)
321 + p.cell(gw - 8, 6, f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}", align="C")
322 + p.set_font("helvetica", "", 6.6)
323 + p.set_text_color(*INK3)
324 + p.set_xy(x + 4, cy + 1.5)
325 + p.cell(gw - 8, 4, f"{frac * 100:.0f} % de {_fr(g['max'])}", align="C")
326 + p.set_xy(x + 3, y + gh - 7)
327 + p.set_font("helvetica", "", 7)
328 + p.set_text_color(*INK2)
329 + p.multi_cell(gw - 6, 3.3, str(g.get("label", ""))[:60], align="C")
330 + p.set_y(y + gh + 8)
331 +
332 + def _serie_stats_row(self, s):
333 + """Ligne min/max/moyenne/médiane sous un graphique de série."""
334 + p = self.pdf
335 + vs = [pt["v"] for pt in (s.get("points") or []) if isinstance(pt.get("v"), (int, float))]
336 + if len(vs) < 2:
337 + return
338 + sv = sorted(vs)
339 + mean = sum(vs) / len(vs)
340 + med = sv[len(sv) // 2]
341 + sd = math.sqrt(sum((v - mean) ** 2 for v in vs) / len(vs))
342 + p.set_font("helvetica", "", 6.8)
343 + p.set_text_color(*INK3)
344 + p.cell(0, 4, f"min {_fr(sv[0])} · max {_fr(sv[-1])} · moyenne {_fr(round(mean, 2))} · médiane {_fr(med)} · écart-type {_fr(round(sd, 2))}")
345 + p.ln(5.5)
346 +
347 + def _line_chart(self, s, with_stats=False):
264 348 p = self.pdf
265 349 pts = s.get("points") or []
266 350 if len(pts) < 2:
267 351 return
352 + if s.get("kind") == "bar":
353 + self._vbars(s)
354 + return
268 355 if p.get_y() > 200:
269 356 p.add_page()
270 − p.set_font("helvetica", "B", 10)
271 − p.set_text_color(*INK)
272 − p.cell(0, 6, s.get("title", ""))
273 − p.ln(7)
357 + self._chart_title(s.get("title", ""))
274 358 x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
275 359 self._card(x0, y0, w, h, fill=WHITE)
276 360 cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
@@ -278,7 +362,6 @@ class GroupeKAReport:
278 362 vmax = max(vals) or 1
279 363 vmin = min(0, min(vals))
280 364 rng = (vmax - vmin) or 1
281 − # grille + graduations
282 365 p.set_font("helvetica", "", 6.3)
283 366 p.set_text_color(*INK3)
284 367 p.set_draw_color(200, 200, 195)
@@ -289,6 +372,20 @@ class GroupeKAReport:
289 372 p.set_xy(x0 + 1, gy - 1.6)
290 373 p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
291 374
375 + def xy(i, n, v):
376 + return (cx + cw * (i / (n - 1)), cy + ch - ch * ((v - vmin) / rng))
377 +
378 + # aire sous la courbe (kind=area) : petits trapèzes accent pâle
379 + if s.get("kind") == "area":
380 + fill = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * 0.18) for j in range(3))
381 + p.set_fill_color(*fill)
382 + p.set_draw_color(*fill)
383 + n = len(pts)
384 + for i in range(n - 1):
385 + x1, y1 = xy(i, n, pts[i]["v"])
386 + x2, y2 = xy(i + 1, n, pts[i + 1]["v"])
387 + p.polygon([(x1, y1), (x2, y2), (x2, cy + ch), (x1, cy + ch)], style="DF")
388 +
292 389 def draw(series, color, width, dash=None):
293 390 n = len(series)
294 391 p.set_draw_color(*color)
@@ -297,8 +394,7 @@ class GroupeKAReport:
297 394 p.set_dash_pattern(dash=1.2, gap=1.2)
298 395 last = None
299 396 for i, pt in enumerate(series):
300 − px = cx + cw * (i / (n - 1))
301 − py = cy + ch - ch * ((pt["v"] - vmin) / rng)
397 + px, py = xy(i, n, pt["v"])
302 398 if last:
303 399 p.line(last[0], last[1], px, py)
304 400 last = (px, py)
@@ -307,7 +403,6 @@ class GroupeKAReport:
307 403 if s.get("compare"):
308 404 draw(s["compare"], INK3, 0.35, dash=True)
309 405 draw(pts, self.accent, 0.7)
310 − # libellés d'axe X (premier / milieu / dernier)
311 406 p.set_text_color(*INK3)
312 407 for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):
313 408 p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
@@ -317,9 +412,166 @@ class GroupeKAReport:
317 412 p.set_font("helvetica", "", 6.8)
318 413 p.set_text_color(*INK3)
319 414 p.cell(0, 4, "— période courante (accent) · ---- période comparée")
320 − p.ln(6)
321 − else:
322 − p.ln(2)
415 + p.ln(5.5)
416 + if with_stats:
417 + self._serie_stats_row(s)
418 + p.ln(1.5)
419 +
420 + def _vbars(self, s):
421 + """Barres verticales : série kind=bar ou distribution (bins)."""
422 + p = self.pdf
423 + pts = s.get("points") or [{"t": b.get("label"), "v": b.get("value")} for b in (s.get("bins") or [])]
424 + pts = [pt for pt in pts if isinstance(pt.get("v"), (int, float))]
425 + if not pts:
426 + return
427 + if p.get_y() > 205:
428 + p.add_page()
429 + self._chart_title(s.get("title", ""))
430 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 48
431 + self._card(x0, y0, w, h, fill=WHITE)
432 + cx, cy, cw, ch = x0 + 12, y0 + 5, w - 20, h - 14
433 + vmax = max(pt["v"] for pt in pts) or 1
434 + p.set_font("helvetica", "", 6.3)
435 + p.set_text_color(*INK3)
436 + p.set_draw_color(200, 200, 195)
437 + p.set_line_width(0.15)
438 + for g in range(5):
439 + gy = cy + ch - ch * g / 4
440 + p.line(cx, gy, cx + cw, gy)
441 + p.set_xy(x0 + 1, gy - 1.6)
442 + p.cell(10, 3, _fr(vmax * g / 4), align="R")
443 + n = len(pts)
444 + bw = max(0.8, cw / n - 0.6)
445 + p.set_fill_color(*self.accent)
446 + p.set_draw_color(*INK)
447 + p.set_line_width(0.15)
448 + for i, pt in enumerate(pts):
449 + bh = ch * (pt["v"] / vmax)
450 + p.rect(cx + cw * i / n + 0.3, cy + ch - bh, bw, max(bh, 0.4 if pt["v"] > 0 else 0), style="DF")
451 + p.set_text_color(*INK3)
452 + for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):
453 + p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)
454 + p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")
455 + p.set_y(y0 + h + 5)
456 +
457 + def _multiline(self, ms):
458 + """Multi-séries (≤4) : accent plein / encre fin / accent pointillé /
459 + gris pointillé — l'identité passe par le motif, pas la couleur seule."""
460 + p = self.pdf
461 + series = [s for s in (ms.get("series") or []) if len(s.get("points") or []) > 1][:4]
462 + if not series:
463 + return
464 + if p.get_y() > 195:
465 + p.add_page()
466 + self._chart_title(ms.get("title", ""))
467 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
468 + self._card(x0, y0, w, h, fill=WHITE)
469 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
470 + vals = [pt["v"] for s in series for pt in s["points"]]
471 + vmax = max(vals) or 1
472 + vmin = min(0, min(vals))
473 + rng = (vmax - vmin) or 1
474 + p.set_font("helvetica", "", 6.3)
475 + p.set_text_color(*INK3)
476 + p.set_draw_color(200, 200, 195)
477 + p.set_line_width(0.15)
478 + for g in range(5):
479 + gy = cy + ch - ch * g / 4
480 + p.line(cx, gy, cx + cw, gy)
481 + p.set_xy(x0 + 1, gy - 1.6)
482 + p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
483 + styles = [
484 + (self.accent, 0.7, None),
485 + (INK, 0.45, None),
486 + (self.accent, 0.55, True),
487 + (INK3, 0.5, True),
488 + ]
489 + for si, s in enumerate(series):
490 + col, lw, dash = styles[si]
491 + p.set_draw_color(*col)
492 + p.set_line_width(lw)
493 + if dash:
494 + p.set_dash_pattern(dash=1.4, gap=1.2)
495 + n = len(s["points"])
496 + last = None
497 + for i, pt in enumerate(s["points"]):
498 + px = cx + cw * (i / (n - 1))
499 + py = cy + ch - ch * ((pt["v"] - vmin) / rng)
500 + if last:
501 + p.line(last[0], last[1], px, py)
502 + last = (px, py)
503 + p.set_dash_pattern()
504 + ref = series[0]["points"]
505 + p.set_text_color(*INK3)
506 + for frac, idx in ((0, 0), (0.5, len(ref) // 2), (1, -1)):
507 + p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
508 + p.cell(18, 3, str(ref[idx].get("t", ""))[:10], align="C")
509 + p.set_y(y0 + h + 4)
510 + p.set_font("helvetica", "", 6.8)
511 + p.set_text_color(*INK3)
512 + marks = ["—", "—", "----", "----"]
513 + leg = " · ".join(f"{marks[i]} {s.get('label', '')}" for i, s in enumerate(series))
514 + p.cell(0, 4, leg[:120])
515 + p.ln(6)
516 +
517 + def _stacked(self, st):
518 + p = self.pdf
519 + keys = (st.get("keys") or [])[:6]
520 + pts = st.get("points") or []
521 + if not keys or not pts:
522 + return
523 + if p.get_y() > 195:
524 + p.add_page()
525 + self._chart_title(st.get("title", ""))
526 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
527 + self._card(x0, y0, w, h, fill=WHITE)
528 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
529 + totals = [sum(v or 0 for v in pt.get("values", [])[: len(keys)]) for pt in pts]
530 + vmax = max(totals) or 1
531 + p.set_font("helvetica", "", 6.3)
532 + p.set_text_color(*INK3)
533 + p.set_draw_color(200, 200, 195)
534 + p.set_line_width(0.15)
535 + for g in range(5):
536 + gy = cy + ch - ch * g / 4
537 + p.line(cx, gy, cx + cw, gy)
538 + p.set_xy(x0 + 1, gy - 1.6)
539 + p.cell(10, 3, _fr(vmax * g / 4), align="R")
540 + n = len(pts)
541 + bw = max(0.8, cw / n - 0.6)
542 + p.set_draw_color(*WHITE)
543 + p.set_line_width(0.12)
544 + for i, pt in enumerate(pts):
545 + yacc = cy + ch
546 + for j, k in enumerate(keys):
547 + v = (pt.get("values") or [0] * len(keys))[j] if j < len(pt.get("values", [])) else 0
548 + if not v:
549 + continue
550 + bh = ch * (v / vmax)
551 + yacc -= bh
552 + p.set_fill_color(*self._shade(j))
553 + p.rect(cx + cw * i / n + 0.3, yacc, bw, max(bh - 0.15, 0.3), style="DF")
554 + p.set_text_color(*INK3)
555 + for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):
556 + p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)
557 + p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")
558 + p.set_y(y0 + h + 4)
559 + # légende
560 + p.set_font("helvetica", "", 6.8)
561 + lx = p.l_margin
562 + for j, k in enumerate(keys):
563 + p.set_fill_color(*self._shade(j))
564 + p.set_draw_color(*INK)
565 + p.set_line_width(0.2)
566 + p.rect(lx, p.get_y() + 0.6, 3, 3, style="DF")
567 + p.set_xy(lx + 4, p.get_y())
568 + p.set_text_color(*INK2)
569 + txt = str(k)[:22]
570 + p.cell(p.get_string_width(txt) + 3, 4, txt)
571 + lx = p.get_x() + 3
572 + if lx > 165:
573 + break
574 + p.ln(7)
323 575
324 576 def _bars(self, title, items, unit=""):
325 577 p = self.pdf
@@ -329,10 +581,8 @@ class GroupeKAReport:
329 581 need = 10 + len(items) * 7
330 582 if p.get_y() + need > 265:
331 583 p.add_page()
332 − p.set_font("helvetica", "B", 10)
333 − p.set_text_color(*INK)
334 − p.cell(0, 6, title)
335 − p.ln(8)
584 + self._chart_title(title)
585 + p.ln(1)
336 586 vmax = max(it["value"] for it in items) or 1
337 587 for it in items:
338 588 y = p.get_y()
@@ -340,19 +590,23 @@ class GroupeKAReport:
340 590 p.set_text_color(*INK)
341 591 p.set_x(p.l_margin)
342 592 p.cell(46, 5, str(it["label"])[:34])
343 − bw = 96 * (it["value"] / vmax)
593 + bw = 86 * (it["value"] / vmax)
344 594 p.set_fill_color(*self.accent)
345 595 p.set_draw_color(*INK)
346 596 p.set_line_width(0.25)
347 597 p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF")
348 − p.set_xy(p.l_margin + 148, y)
598 + p.set_xy(p.l_margin + 136, y)
349 599 p.set_font("helvetica", "B", 7.6)
350 − p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
600 + p.cell(24, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
601 + if it.get("delta_pct") is not None:
602 + up = it["delta_pct"] >= 0
603 + p.set_font("helvetica", "B", 6.6)
604 + p.set_text_color(*(GREEN if up else DANGER))
605 + p.cell(14, 5, f"{'+' if up else ''}{str(round(it['delta_pct'], 1)).replace('.', ',')} %", align="R")
351 606 p.ln(6.4)
352 607 p.ln(3)
353 608
354 609 def _donut(self, b):
355 − # anneau vectoriel simple (arcs) + légende
356 610 p = self.pdf
357 611 items = [it for it in (b.get("items") or []) if it.get("value")][:8]
358 612 total = sum(it["value"] for it in items)
@@ -360,17 +614,13 @@ class GroupeKAReport:
360 614 return
361 615 if p.get_y() > 210:
362 616 p.add_page()
363 − p.set_font("helvetica", "B", 10)
364 − p.set_text_color(*INK)
365 − p.cell(0, 6, b.get("title", ""))
366 − p.ln(8)
617 + self._chart_title(b.get("title", ""))
618 + p.ln(1)
367 619 cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20
368 − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
369 620 start = -90.0
370 621 for i, it in enumerate(items):
371 622 frac = it["value"] / total
372 − f = shades[i % len(shades)]
373 − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
623 + col = self._shade(i)
374 624 steps = max(2, int(72 * frac))
375 625 p.set_fill_color(*col)
376 626 p.set_draw_color(*col)
@@ -389,11 +639,9 @@ class GroupeKAReport:
389 639 p.set_line_width(0.4)
390 640 p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")
391 641 p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")
392 − # légende
393 642 ly = cy - 22
394 643 for i, it in enumerate(items):
395 − f = shades[i % len(shades)]
396 − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
644 + col = self._shade(i)
397 645 p.set_fill_color(*col)
398 646 p.set_draw_color(*INK)
399 647 p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")
@@ -405,7 +653,39 @@ class GroupeKAReport:
405 653 ly += 5.6
406 654 p.set_y(max(cy + r, ly) + 6)
407 655
408 − def _table(self, t):
656 + def _hourly(self):
657 + hh = self.d.get("hourly") or {}
658 + cells = hh.get("cells") or []
659 + if not cells:
660 + return
661 + p = self.pdf
662 + if p.get_y() > 190:
663 + p.add_page()
664 + self._chart_title(hh.get("title", "Activité par jour et heure"))
665 + x0, y0 = p.l_margin, p.get_y()
666 + cw, chh, lx, ly = 6.4, 6.4, 12, 5
667 + vmax = max((c.get("value") or 0) for c in cells) or 1
668 + grid = {(c.get("dow"), c.get("hour")): c.get("value") or 0 for c in cells}
669 + dows = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"]
670 + p.set_font("helvetica", "", 5.8)
671 + p.set_text_color(*INK3)
672 + for h in (0, 6, 12, 18, 23):
673 + p.set_xy(x0 + lx + h * cw, y0)
674 + p.cell(cw, 3, f"{h}h", align="C")
675 + for d in range(7):
676 + p.set_xy(x0, y0 + ly + d * chh + 1.5)
677 + p.cell(lx - 1, 3, dows[d], align="R")
678 + for h in range(24):
679 + v = grid.get((d, h), 0)
680 + f = 0.1 + 0.9 * (v / vmax) if v else 0.0
681 + col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) if v else (235, 233, 228)
682 + p.set_fill_color(*col)
683 + p.set_draw_color(215, 213, 207)
684 + p.set_line_width(0.1)
685 + p.rect(x0 + lx + h * cw, y0 + ly + d * chh, cw - 0.5, chh - 0.5, style="DF")
686 + p.set_y(y0 + ly + 7 * chh + 5)
687 +
688 + def _table(self, t, max_rows=200):
409 689 p = self.pdf
410 690 cols = t.get("columns") or []
411 691 rows = t.get("rows") or []
@@ -422,7 +702,7 @@ class GroupeKAReport:
422 702 p.ln(6)
423 703 head()
424 704 p.set_text_color(*INK)
425 − for i, row in enumerate(rows[:200]):
705 + for i, row in enumerate(rows[:max_rows]):
426 706 if p.get_y() > 262:
427 707 p.add_page()
428 708 head()
@@ -433,10 +713,10 @@ class GroupeKAReport:
433 713 txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)
434 714 p.cell(w, 5.4, " " + txt[:34], fill=True)
435 715 p.ln(5.4)
436 − if len(rows) > 200:
716 + if len(rows) > max_rows:
437 717 p.set_font("helvetica", "", 7)
438 718 p.set_text_color(*INK3)
439 − p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées")
719 + p.cell(0, 5, f"… {len(rows) - max_rows} lignes supplémentaires non imprimées")
440 720 p.ln(6)
441 721
442 722 def _records(self):
@@ -445,7 +725,7 @@ class GroupeKAReport:
445 725 return
446 726 self._section_title("Records & faits marquants")
447 727 p = self.pdf
448 − for r in recs[:10]:
728 + for r in recs[:14]:
449 729 if p.get_y() > 258:
450 730 p.add_page()
451 731 y = p.get_y()
@@ -503,43 +783,76 @@ class GroupeKAReport:
503 783 "groupe-ka.com/conditions · /confidentialite · /loi-25.",
504 784 )
505 785
506 − def _toc_page(self):
507 − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en
508 − # page 2 en réservant la page lors du build (voir build()).
509 − pass
786 + # ---------- groupes de sections ----------
787 + def _all_series(self, with_stats=True):
788 + for s in self.d.get("series") or []:
789 + self._line_chart(s, with_stats=with_stats)
790 + for ms in self.d.get("multiseries") or []:
791 + self._multiline(ms)
792 + for st in self.d.get("stacked") or []:
793 + self._stacked(st)
794 +
795 + def _all_breakdowns(self):
796 + for b in self.d.get("breakdowns") or []:
797 + if b.get("kind") == "donut":
798 + self._donut(b)
799 + else:
800 + self._bars(b.get("title", ""), b.get("items"))
801 + for dist in self.d.get("distributions") or []:
802 + self._vbars(dist)
803 + geo = self.d.get("geo")
804 + if geo:
805 + self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
806 + self._hourly()
510 807
511 808 def build(self) -> bytes:
512 809 p = self.pdf
513 810 p.alias_nb_pages()
514 811 self._cover()
812 + with_toc = self.mode in ("complet", "donnees")
813 + toc_page_no = None
515 814 if self.mode == "synthese":
516 815 p.add_page()
517 816 self._kpis()
817 + self._gauges()
818 + self._records()
819 + self._final_page()
820 + elif self.mode == "tendances":
821 + p.add_page()
822 + self._kpis()
823 + self._section_title("Évolution & tendances")
824 + self._all_series(with_stats=True)
518 825 self._records()
519 826 self._final_page()
520 − else:
827 + elif self.mode == "repartitions":
828 + p.add_page()
829 + self._section_title("Répartitions, distributions & géographie")
830 + self._all_breakdowns()
831 + self._final_page()
832 + elif self.mode == "donnees":
833 + p.add_page()
834 + toc_page_no = p.page_no()
835 + for t in self.d.get("tables") or []:
836 + self._table(t, max_rows=400)
837 + self._final_page()
838 + else: # complet
521 839 p.add_page()
522 840 toc_page_no = p.page_no()
523 841 p.add_page()
524 842 self._kpis()
525 − for s in self.d.get("series") or []:
526 − if s.get("kind") == "bar":
527 − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", ""))
528 − else:
529 − self._line_chart(s)
530 − for b in self.d.get("breakdowns") or []:
531 − if b.get("kind") == "donut":
532 − self._donut(b)
533 − else:
534 − self._bars(b.get("title", ""), b.get("items"))
535 − geo = self.d.get("geo")
536 − if geo:
537 − self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
843 + self._gauges()
844 + if (self.d.get("series") or self.d.get("multiseries") or self.d.get("stacked")):
845 + self._section_title("Évolution & tendances")
846 + self._all_series(with_stats=True)
847 + if (self.d.get("breakdowns") or self.d.get("distributions") or self.d.get("geo") or self.d.get("hourly")):
848 + self._section_title("Répartitions, distributions & géographie")
849 + self._all_breakdowns()
538 850 for t in self.d.get("tables") or []:
539 851 self._table(t)
540 852 self._records()
541 853 self._final_page()
542 − # sommaire écrit sur la page réservée (page 2)
854 + # sommaire écrit sur la page réservée
855 + if toc_page_no is not None:
543 856 last_page = p.page
544 857 p.page = toc_page_no
545 858 p.set_y(22)
@@ -558,6 +871,7 @@ class GroupeKAReport:
558 871 return bytes(p.output())
559 872
560 873
561 −def filename(platform_id: str, period: str) -> str:
874 +def filename(platform_id: str, period: str, mode: str = "complet") -> str:
562 875 today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")
563 − return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf"
876 + suffix = "" if mode in ("", "complet") else f"_{mode}"
877 + return f"groupe-ka_{platform_id}_stats_{period}{suffix}_{today}.pdf"
modified frontend/src/ka/tokens.css +87 −0
@@ -69,7 +69,24 @@
69 69
70 70 /* Cible tactile minimale */
71 71 --touch: 44px;
72 +
73 + /* ---- Échelle z-index COMMUNE (obligatoire — aucune valeur arbitraire) ----
74 + grain de film body::before = 9999 (pointer-events:none, toujours au-dessus,
75 + purement visuel). Tout composant interactif se place sous 9999 : */
76 + --z-content: 1; /* contenu positionné ordinaire */
77 + --z-sticky: 300; /* éléments sticky de contenu (sous-nav…) */
78 + --z-header: 500; /* header du site */
79 + --z-bottombar: 600; /* tab bar / barre d'action basse */
80 + --z-dropdown: 700; /* menus déroulants (au-dessus des barres) */
81 + --z-overlay: 800; /* voile sous modale/panneau */
82 + --z-modal: 900; /* modales, panneaux de filtres, galeries */
83 + --z-toast: 950; /* notifications */
84 +
85 + /* ---- Hauteur de viewport DYNAMIQUE (barre du navigateur mobile qui se
86 + replie au scroll) : toujours var(--vh100), JAMAIS 100vh en dur. ---- */
87 + --vh100: 100vh;
72 88 }
89 +@supports (height: 100dvh) { :root { --vh100: 100dvh; } }
73 90
74 91 /* ---- Socle ---- */
75 92 * { box-sizing: border-box; }
@@ -227,3 +244,73 @@ body > * { position: relative; }
227 244 /* ---- Utilitaires responsive ---- */
228 245 .only-mobile { display: initial; } .only-desktop { display: none; }
229 246 @media (min-width: 768px) { .only-mobile { display: none; } .only-desktop { display: initial; } }
247 +
248 +/* =============================================================================
249 + SOCLE MOBILE OBLIGATOIRE (2026-08-19) — règles communes aux 13 sites.
250 + RÈGLES pour tout composant futur :
251 + · TAP, jamais :hover, pour ouvrir un menu (le survol n'existe pas au doigt) ;
252 + le :hover ne sert qu'aux effets décoratifs, sous @media (hover: hover).
253 + · var(--vh100) (dvh) et JAMAIS 100vh pour tout élément calé sur le viewport.
254 + · position:fixed exige qu'AUCUN ancêtre n'ait transform/filter/perspective/
255 + will-change/backdrop-filter — sinon monter l'élément à la racine (body).
256 + · Barre basse fixe = .ka-bottombar + classe has-bottombar sur <body>.
257 + · Menu/panneau ouvert = .ka-scroll-lock sur <html> (scroll arrière-plan gelé).
258 + · z-index : uniquement l'échelle --z-* ci-dessus.
259 + · Zones tactiles ≥ var(--touch) (44 px), champs ≥ 16 px (zoom iOS).
260 + ========================================================================== */
261 +
262 +/* Anti-zoom iOS : au doigt, aucun champ sous 16 px (le focus d'un champ <16 px
263 + déclenche un zoom automatique de page sur Safari iOS). !important assumé :
264 + c'est un filet d'accessibilité, un champ plus petit casse le zoom quoi
265 + qu'il arrive — ne s'applique qu'aux écrans tactiles. */
266 +@media (hover: none) and (pointer: coarse) {
267 + input:not([type="checkbox"]):not([type="radio"]):not([type="range"]),
268 + select, textarea { font-size: max(16px, 1em) !important; }
269 +}
270 +
271 +/* Zone tactile du badge Groupe KA étendue à ≥44 px au doigt, sans changer
272 + son rendu (débord de la zone cliquable via pseudo-élément). */
273 +@media (pointer: coarse) {
274 + .gk-badge { position: relative; }
275 + .gk-badge::after { content: ""; position: absolute; inset: -8px; }
276 +}
277 +
278 +/* Hauteurs viewport dynamiques */
279 +.h-viewport { height: 100vh; height: 100dvh; }
280 +.min-h-viewport { min-height: 100vh; min-height: 100dvh; }
281 +
282 +/* Barre fixe basse fiable : safe-area iPhone incluse, immunisée contre les
283 + transforms accidentels, et compensation d'espace via body.has-bottombar. */
284 +.ka-bottombar {
285 + position: fixed; left: 0; right: 0; bottom: 0;
286 + z-index: var(--z-bottombar);
287 + padding-bottom: env(safe-area-inset-bottom, 0px);
288 + background: var(--surface);
289 + border-top: 1.5px solid var(--ink);
290 + transform: none !important; filter: none !important;
291 +}
292 +body.has-bottombar { padding-bottom: calc(var(--bottombar-h, 64px) + env(safe-area-inset-bottom, 0px)); }
293 +
294 +/* Verrou de scroll d'arrière-plan (menu mobile, modale, panneau de filtres
295 + ouverts) : ajouter/retirer .ka-scroll-lock sur <html>. */
296 +html.ka-scroll-lock, html.ka-scroll-lock body { overflow: hidden !important; overscroll-behavior: none; }
297 +
298 +/* Menu déroulant de référence : au-dessus de tout contenu (cartes Mapbox
299 + incluses), défilement interne avec élan, jamais plus haut que l'écran. */
300 +.ka-menu {
301 + position: absolute; z-index: var(--z-dropdown);
302 + min-width: 180px;
303 + max-height: min(60vh, 420px); max-height: min(60dvh, 420px);
304 + overflow-y: auto; -webkit-overflow-scrolling: touch; overscroll-behavior: contain;
305 + background: var(--surface); border: 1.5px solid var(--ink);
306 + border-radius: var(--r-card); box-shadow: var(--shadow-off-mid);
307 +}
308 +.ka-menu a, .ka-menu button, .ka-menu label, .ka-menu [role="menuitem"], .ka-menu [role="option"] {
309 + display: flex; align-items: center; min-height: var(--touch);
310 + padding: 10px 14px; width: 100%; text-decoration: none;
311 +}
312 +/* Voile plein écran sous une modale / un panneau */
313 +.ka-overlay {
314 + position: fixed; inset: 0; z-index: var(--z-overlay);
315 + background: rgba(20, 24, 20, 0.45);
316 +}
modified frontend/src/pages/Stats.tsx +56 −19
@@ -1,29 +1,38 @@
1 1 // ==============================================================================
2 2 // Author: Simon-Pierre Boucher <contact@spboucher.ai>
3 3 // File: pages/Stats.tsx
4 −// Desc: Tableau de bord analytique — module Stats commun Groupe KA
5 −// (ka-ui/stats/SPEC.md §1) : bandeau KPI, sélecteur de période,
6 −// graphiques SVG (kacharts), répartition géographique, tableaux,
7 −// records, export PDF estampillé Groupe-KA. Données 100 % réelles
8 −// servies par /api/stats/dashboard (cache serveur 5 min).
4 +// Desc: Tableau de bord analytique — module Stats commun Groupe KA v2
5 +// (ka-ui/stats/SPEC.md §1) : bandeau KPI avec sparklines, sélecteur
6 +// de période, jauges de complétude, courbes/aires/barres + stats de
7 +// séries, multi-courbes (prix par ville), barres empilées (ajouts par
8 +// source), répartitions, distributions, géographie, heatmaps
9 +// calendrier + horaire, tableaux, records, export PDF (5 rapports).
10 +// Données 100 % réelles servies par /api/stats/dashboard (cache 5 min).
9 11 // ==============================================================================
10 12 import { useCallback, useEffect, useState } from "react";
11 13 import {
12 − BarChart, BreakItem, CalendarHeatmap, DataTable, Donut, EmptyBlock,
13 − Fraicheur, Kpi, KpiCard, LineChart, PdfButton, PeriodSelector, RecordCard,
14 − RecordFact, Serie, TableSpec,
14 + BarChart, BreakItem, CalendarHeatmap, DataTable, Distribution, Donut,
15 + EmptyBlock, Fraicheur, Gauge, GaugeCard, Histogram, HourCell, HourHeatmap,
16 + Kpi, KpiCard, LineChart, MultiLineChart, MultiSerie, PdfButton,
17 + PeriodSelector, RecordCard, RecordFact, Serie, StackedBarChart,
18 + StackedSerie, StatSummary, TableSpec,
15 19 } from "../ka/stats/kacharts";
16 20
17 −/* ---------- contrat /api/stats/dashboard (SPEC.md §2) ---------- */
21 +/* ---------- contrat /api/stats/dashboard (SPEC.md v2 §2) ---------- */
18 22 type Breakdown = { id: string; title: string; kind?: "donut" | "bar"; items: BreakItem[] };
19 23 type Dashboard = {
20 24 updated: string;
21 25 period: { from: string; to: string; label: string };
22 26 kpis?: Kpi[];
27 + gauges?: Gauge[];
23 28 series?: Serie[];
29 + multiseries?: MultiSerie[];
30 + stacked?: StackedSerie[];
24 31 breakdowns?: Breakdown[];
32 + distributions?: Distribution[];
25 33 geo?: { title: string; items: BreakItem[] };
26 34 heatmap?: { title: string; cells: { date: string; value: number }[] };
35 + hourly?: { title: string; cells: HourCell[] };
27 36 tables?: TableSpec[];
28 37 records?: RecordFact[];
29 38 };
@@ -66,10 +75,12 @@ export default function StatsPage() {
66 75
67 76 const donuts = (dash.breakdowns ?? []).filter((b) => b.kind === "donut");
68 77 const bars = (dash.breakdowns ?? []).filter((b) => b.kind !== "donut");
78 + // séries clés (volumes quotidiens) : stats min/max/moy/méd/σ dessous
79 + const withStats = new Set(["new_restos", "releves"]);
69 80
70 81 return (
71 82 <div className="container stats-page" style={{ opacity: loading ? 0.55 : 1, transition: "opacity 0.15s" }}>
72 − {/* ---- en-tête : titre + PDF + fraîcheur (SPEC §1.7-8) ---- */}
83 + {/* ---- en-tête : titre + PDF (5 rapports) + fraîcheur (SPEC §1.10-11) ---- */}
73 84 <div className="stats-head">
74 85 <div>
75 86 <span className="kicker">Statistiques · {dash.period.label}</span>
@@ -87,7 +98,7 @@ export default function StatsPage() {
87 98 </div>
88 99 </div>
89 100
90 − {/* ---- 1. bandeau KPI ---- */}
101 + {/* ---- 1. bandeau KPI (sparklines incluses) ---- */}
91 102 {dash.kpis?.length ? (
92 103 <div className="kpi-grid">
93 104 {dash.kpis.map((k) => <KpiCard key={k.id} k={k} />)}
@@ -104,27 +115,52 @@ export default function StatsPage() {
104 115 />
105 116 </div>
106 117
107 − {/* ---- 3. graphiques : courbes d'évolution ---- */}
118 + {/* ---- 3. jauges : couverture & complétude des fiches ---- */}
119 + {dash.gauges?.length ? (
120 + <section>
121 + <span className="kicker">Couverture & complétude</span>
122 + <div className="kpi-grid">
123 + {dash.gauges.map((g) => <GaugeCard key={g.id} g={g} />)}
124 + </div>
125 + </section>
126 + ) : null}
127 +
128 + {/* ---- 4. évolution : courbes / aires / barres + stats de séries ---- */}
108 129 <div className="stats-grid2">
109 − {(dash.series ?? []).map((s) => <LineChart key={s.id} serie={s} />)}
130 + {(dash.series ?? []).map((s) => (
131 + <div key={s.id}>
132 + <LineChart serie={s} />
133 + {withStats.has(s.id) && <StatSummary serie={s} />}
134 + </div>
135 + ))}
110 136 </div>
111 137
112 − {/* ---- 3b. répartitions : anneau + barres ---- */}
138 + {/* ---- 4b. multi-courbes (≤ 4 séries, motifs distincts) + empilées ---- */}
139 + {(dash.multiseries?.length || dash.stacked?.length) ? (
140 + <div className="stats-grid2">
141 + {(dash.multiseries ?? []).map((ms) => <MultiLineChart key={ms.id} ms={ms} />)}
142 + {(dash.stacked ?? []).map((st) => <StackedBarChart key={st.id} st={st} />)}
143 + </div>
144 + ) : null}
145 +
146 + {/* ---- 5. répartitions : anneaux + barres + distributions ---- */}
113 147 <div className="stats-grid2">
114 148 {donuts.map((b) => <Donut key={b.id} title={b.title} items={b.items} />)}
115 149 {bars.map((b) => <BarChart key={b.id} title={b.title} items={b.items} />)}
116 − {/* ---- 4. répartition géographique ---- */}
150 + {(dash.distributions ?? []).map((d) => <Histogram key={d.id} dist={d} />)}
151 + {/* ---- 6. répartition géographique ---- */}
117 152 {dash.geo ? <BarChart title={dash.geo.title} items={dash.geo.items} unit="restos" />
118 153 : <EmptyBlock title="Répartition géographique" />}
119 154 </div>
120 155
121 − {/* ---- 3c. calendrier de chaleur ---- */}
156 + {/* ---- 7. calendriers : chaleur 26 semaines + activité horaire 7×24 ---- */}
122 157 {dash.heatmap && <CalendarHeatmap title={dash.heatmap.title} cells={dash.heatmap.cells} />}
158 + {dash.hourly && <HourHeatmap title={dash.hourly.title} cells={dash.hourly.cells} />}
123 159
124 − {/* ---- 5. tableaux détaillés ---- */}
160 + {/* ---- 8. tableaux détaillés ---- */}
125 161 {(dash.tables ?? []).map((t) => <DataTable key={t.id} spec={t} />)}
126 162
127 − {/* ---- 6. records & faits marquants ---- */}
163 + {/* ---- 9. records & faits marquants ---- */}
128 164 {dash.records?.length ? (
129 165 <section>
130 166 <span className="kicker">Records & faits marquants</span>
@@ -137,7 +173,8 @@ export default function StatsPage() {
137 173 <div className="stats-foot">
138 174 Les prix appartiennent aux restaurants et à leurs plateformes ;
139 175 Resto-Ka les agrège pour la découverte et renvoie toujours à la source.
140 − Rapport PDF estampillé Groupe-KA disponible en haut de page.
176 + Rapports PDF estampillés Groupe-KA (complet, synthèse, tendances,
177 + répartitions, données) disponibles en haut de page.
141 178 </div>
142 179 </div>
143 180 );
modified restoka/kapdf.py +390 −76
@@ -1,10 +1,17 @@
1 1 # Auteur : Simon-Pierre Boucher — contact@spboucher.ai
2 −# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2).
2 +# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2). v2
3 3 # Consomme le JSON du contrat /api/stats/dashboard (voir SPEC.md) et produit
4 −# le rapport estampillé Groupe-KA : couverture, sommaire, KPI, graphiques
5 −# VECTORIELS (courbes/barres/anneaux), tableaux paginés, records, page de fin.
4 +# les rapports estampillés Groupe-KA. 5 modes :
5 +# complet — toutes les sections (KPI, jauges, séries + stats, multi-
6 +# séries, empilées, distributions, répartitions, géo,
7 +# heatmap horaire, tableaux, records)
8 +# synthese — couverture + KPI + records (2-3 pages)
9 +# tendances — KPI + toutes les séries temporelles + stats de séries
10 +# repartitions — breakdowns, distributions, géo, activité horaire
11 +# donnees — tous les tableaux en version longue (400 lignes max)
12 +# Graphiques VECTORIELS uniquement (primitives fpdf), accent de la marque.
6 13 # Usage :
7 −# from kapdf import GroupeKAReport
14 +# from kapdf import GroupeKAReport, REPORT_MODES, filename
8 15 # pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00",
9 16 # "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json,
10 17 # mode="complet").build()
@@ -26,6 +33,14 @@ GREEN = (28, 92, 65)
26 33 DANGER = (179, 66, 58)
27 34 WHITE = (255, 255, 255)
28 35
36 +REPORT_MODES = {
37 + "complet": "Rapport complet",
38 + "synthese": "Synthèse exécutive",
39 + "tendances": "Tendances & évolution",
40 + "repartitions": "Répartitions & géographie",
41 + "donnees": "Données détaillées",
42 +}
43 +
29 44 EMAILS = [
30 45 ("contact@groupe-ka.com", "Projets, partenariats & données"),
31 46 ("info@groupe-ka.com", "Médias & questions générales"),
@@ -52,7 +67,8 @@ def _fr(n) -> str:
52 67 _SUBST = {
53 68 "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",
54 69 "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',
55 − "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
70 + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",
71 + "×": "x", "·": ".", "σ": "sigma", "Δ": "delta",
56 72 }
57 73
58 74
@@ -75,12 +91,11 @@ class _PDF(FPDF):
75 91 self.accent = accent
76 92 self.period_label = period_label
77 93 self.cover_mode = False
78 − self.has_cover = False
79 94 self.set_margins(18, 20, 18)
80 95 self.set_auto_page_break(True, margin=22)
81 96
82 97 def header(self):
83 − if self.cover_mode or (self.has_cover and self.page_no() == 1):
98 + if self.cover_mode or self.page_no() == 1:
84 99 return
85 100 self.set_font("helvetica", "B", 8.5)
86 101 self.set_text_color(*INK)
@@ -96,10 +111,9 @@ class _PDF(FPDF):
96 111 self.set_y(20)
97 112
98 113 def footer(self):
99 − # la couverture (page 1) ne porte jamais le pied de page standard :
100 − # son footer se déclenche au add_page suivant, quand cover_mode est
101 − # déjà retombé — on la repère donc par son numéro de page.
102 − if self.cover_mode or (self.has_cover and self.page_no() == 1):
114 + # page 1 = couverture (le flag cover_mode est déjà retombé quand
115 + # add_page() clôt la page 1 → tester aussi le numéro de page)
116 + if self.cover_mode or self.page_no() == 1:
103 117 return
104 118 self.set_y(-15)
105 119 self.set_draw_color(*INK3)
@@ -116,7 +130,7 @@ class GroupeKAReport:
116 130 def __init__(self, site: dict, dashboard: dict, mode: str = "complet"):
117 131 self.site = site
118 132 self.d = dashboard
119 − self.mode = mode
133 + self.mode = mode if mode in REPORT_MODES else "complet"
120 134 self.accent = _hex(site.get("accent", "#d9f26b"))
121 135 period = dashboard.get("period", {}) or {}
122 136 self.period_label = period.get("label") or "toute la période"
@@ -131,6 +145,11 @@ class GroupeKAReport:
131 145 p.set_fill_color(*fill)
132 146 p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)
133 147
148 + def _shade(self, i, n=8):
149 + shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
150 + f = shades[i % len(shades)]
151 + return tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
152 +
134 153 def _kicker(self, text):
135 154 p = self.pdf
136 155 p.set_font("helvetica", "B", 8)
@@ -154,11 +173,18 @@ class GroupeKAReport:
154 173 self.toc.append((title, self.pdf.page_no()))
155 174 self.pdf.ln(11)
156 175
176 + def _chart_title(self, title):
177 + p = self.pdf
178 + p.set_font("helvetica", "B", 10)
179 + p.set_text_color(*INK)
180 + p.set_x(p.l_margin)
181 + p.cell(0, 6, title)
182 + p.ln(7)
183 +
157 184 # ---------- pages ----------
158 185 def _cover(self):
159 186 p = self.pdf
160 187 p.cover_mode = True
161 − p.has_cover = True
162 188 p.set_auto_page_break(False)
163 189 p.add_page()
164 190 p.set_fill_color(*PAPER)
@@ -166,12 +192,10 @@ class GroupeKAReport:
166 192 p.set_draw_color(*INK)
167 193 p.set_line_width(1.0)
168 194 p.rect(10, 10, 190, 277)
169 − # kicker
170 195 p.set_font("helvetica", "B", 10)
171 196 p.set_text_color(*GREEN)
172 197 p.set_xy(24, 34)
173 198 p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE")
174 − # wordmark : partie gauche + boîte encre/accent
175 199 wm = self.site.get("wordmark", "")
176 200 left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)
177 201 p.set_xy(24, 70)
@@ -189,7 +213,7 @@ class GroupeKAReport:
189 213 p.set_xy(24, 100)
190 214 p.set_font("helvetica", "", 13)
191 215 p.set_text_color(*INK2)
192 − p.multi_cell(150, 7, f"Rapport statistique — {wm}")
216 + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}")
193 217 now = datetime.now(ZoneInfo("America/Toronto"))
194 218 per = self.d.get("period", {}) or {}
195 219 p.set_xy(24, 125)
@@ -198,7 +222,7 @@ class GroupeKAReport:
198 222 ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),
199 223 ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),
200 224 ("Plateforme", "https://" + self.site.get("domain", "")),
201 − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"),
225 + ("Type de rapport", REPORT_MODES[self.mode]),
202 226 ]
203 227 y = 128
204 228 for k, v in rows:
@@ -210,7 +234,6 @@ class GroupeKAReport:
210 234 p.cell(0, 6, str(v))
211 235 p.set_font("helvetica", "", 10.5)
212 236 y += 8
213 − # bande encre au pied
214 237 p.set_fill_color(*INK)
215 238 p.rect(10, 262, 190, 25, style="F")
216 239 p.set_xy(24, 270)
@@ -235,7 +258,7 @@ class GroupeKAReport:
235 258 p = self.pdf
236 259 cols, gw, gh, gap = 3, 56, 26, 3
237 260 x0, y = p.l_margin, p.get_y()
238 − for i, k in enumerate(kpis[:9]):
261 + for i, k in enumerate(kpis[:12]):
239 262 x = x0 + (i % cols) * (gw + gap)
240 263 if i and i % cols == 0:
241 264 y += gh + gap
@@ -257,20 +280,81 @@ class GroupeKAReport:
257 280 p.set_font("helvetica", "B", 8)
258 281 p.set_text_color(*(GREEN if up else DANGER))
259 282 arrow = "+" if k["delta_pct"] >= 0 else ""
260 − p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(k['delta_pct']).replace('.', ',')} % vs période préc.")
283 + dv = round(float(k["delta_pct"]), 1)
284 + dv = int(dv) if float(dv).is_integer() else dv
285 + p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(dv).replace('.', ',')} % vs période préc.")
261 286 p.set_y(y + gh + 8)
262 287
263 − def _line_chart(self, s):
288 + def _gauges(self):
289 + gs = self.d.get("gauges") or []
290 + gs = [g for g in gs if isinstance(g.get("value"), (int, float)) and g.get("max")]
291 + if not gs:
292 + return
293 + self._section_title("Taux & couvertures")
294 + p = self.pdf
295 + cols, gw, gh, gap = 3, 56, 34, 3
296 + x0, y = p.l_margin, p.get_y()
297 + for i, g in enumerate(gs[:9]):
298 + x = x0 + (i % cols) * (gw + gap)
299 + if i and i % cols == 0:
300 + y += gh + gap
301 + if y > 240:
302 + p.add_page(); y = p.get_y()
303 + self._card(x, y, gw, gh)
304 + frac = max(0.0, min(1.0, g["value"] / g["max"]))
305 + cx, cy, r = x + gw / 2, y + 20, 14
306 + # arc de fond + arc de valeur (demi-cercle en petits segments)
307 + for pass_col, pass_frac, lw in (((225, 223, 217), 1.0, 2.6), (self.accent, frac, 2.6)):
308 + p.set_draw_color(*pass_col)
309 + p.set_line_width(lw)
310 + steps = max(2, int(60 * pass_frac))
311 + last = None
312 + for st in range(steps + 1):
313 + a = math.pi + math.pi * pass_frac * st / steps
314 + pt = (cx + r * math.cos(a), cy + r * math.sin(a))
315 + if last:
316 + p.line(last[0], last[1], pt[0], pt[1])
317 + last = pt
318 + p.set_font("helvetica", "B", 11)
319 + p.set_text_color(*INK)
320 + p.set_xy(x + 4, cy - 5)
321 + p.cell(gw - 8, 6, f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}", align="C")
322 + p.set_font("helvetica", "", 6.6)
323 + p.set_text_color(*INK3)
324 + p.set_xy(x + 4, cy + 1.5)
325 + p.cell(gw - 8, 4, f"{frac * 100:.0f} % de {_fr(g['max'])}", align="C")
326 + p.set_xy(x + 3, y + gh - 7)
327 + p.set_font("helvetica", "", 7)
328 + p.set_text_color(*INK2)
329 + p.multi_cell(gw - 6, 3.3, str(g.get("label", ""))[:60], align="C")
330 + p.set_y(y + gh + 8)
331 +
332 + def _serie_stats_row(self, s):
333 + """Ligne min/max/moyenne/médiane sous un graphique de série."""
334 + p = self.pdf
335 + vs = [pt["v"] for pt in (s.get("points") or []) if isinstance(pt.get("v"), (int, float))]
336 + if len(vs) < 2:
337 + return
338 + sv = sorted(vs)
339 + mean = sum(vs) / len(vs)
340 + med = sv[len(sv) // 2]
341 + sd = math.sqrt(sum((v - mean) ** 2 for v in vs) / len(vs))
342 + p.set_font("helvetica", "", 6.8)
343 + p.set_text_color(*INK3)
344 + p.cell(0, 4, f"min {_fr(sv[0])} · max {_fr(sv[-1])} · moyenne {_fr(round(mean, 2))} · médiane {_fr(med)} · écart-type {_fr(round(sd, 2))}")
345 + p.ln(5.5)
346 +
347 + def _line_chart(self, s, with_stats=False):
264 348 p = self.pdf
265 349 pts = s.get("points") or []
266 350 if len(pts) < 2:
267 351 return
352 + if s.get("kind") == "bar":
353 + self._vbars(s)
354 + return
268 355 if p.get_y() > 200:
269 356 p.add_page()
270 − p.set_font("helvetica", "B", 10)
271 − p.set_text_color(*INK)
272 − p.cell(0, 6, s.get("title", ""))
273 − p.ln(7)
357 + self._chart_title(s.get("title", ""))
274 358 x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
275 359 self._card(x0, y0, w, h, fill=WHITE)
276 360 cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
@@ -278,7 +362,6 @@ class GroupeKAReport:
278 362 vmax = max(vals) or 1
279 363 vmin = min(0, min(vals))
280 364 rng = (vmax - vmin) or 1
281 − # grille + graduations
282 365 p.set_font("helvetica", "", 6.3)
283 366 p.set_text_color(*INK3)
284 367 p.set_draw_color(200, 200, 195)
@@ -289,6 +372,20 @@ class GroupeKAReport:
289 372 p.set_xy(x0 + 1, gy - 1.6)
290 373 p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
291 374
375 + def xy(i, n, v):
376 + return (cx + cw * (i / (n - 1)), cy + ch - ch * ((v - vmin) / rng))
377 +
378 + # aire sous la courbe (kind=area) : petits trapèzes accent pâle
379 + if s.get("kind") == "area":
380 + fill = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * 0.18) for j in range(3))
381 + p.set_fill_color(*fill)
382 + p.set_draw_color(*fill)
383 + n = len(pts)
384 + for i in range(n - 1):
385 + x1, y1 = xy(i, n, pts[i]["v"])
386 + x2, y2 = xy(i + 1, n, pts[i + 1]["v"])
387 + p.polygon([(x1, y1), (x2, y2), (x2, cy + ch), (x1, cy + ch)], style="DF")
388 +
292 389 def draw(series, color, width, dash=None):
293 390 n = len(series)
294 391 p.set_draw_color(*color)
@@ -297,8 +394,7 @@ class GroupeKAReport:
297 394 p.set_dash_pattern(dash=1.2, gap=1.2)
298 395 last = None
299 396 for i, pt in enumerate(series):
300 − px = cx + cw * (i / (n - 1))
301 − py = cy + ch - ch * ((pt["v"] - vmin) / rng)
397 + px, py = xy(i, n, pt["v"])
302 398 if last:
303 399 p.line(last[0], last[1], px, py)
304 400 last = (px, py)
@@ -307,7 +403,6 @@ class GroupeKAReport:
307 403 if s.get("compare"):
308 404 draw(s["compare"], INK3, 0.35, dash=True)
309 405 draw(pts, self.accent, 0.7)
310 − # libellés d'axe X (premier / milieu / dernier)
311 406 p.set_text_color(*INK3)
312 407 for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):
313 408 p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
@@ -317,9 +412,166 @@ class GroupeKAReport:
317 412 p.set_font("helvetica", "", 6.8)
318 413 p.set_text_color(*INK3)
319 414 p.cell(0, 4, "— période courante (accent) · ---- période comparée")
320 − p.ln(6)
321 − else:
322 − p.ln(2)
415 + p.ln(5.5)
416 + if with_stats:
417 + self._serie_stats_row(s)
418 + p.ln(1.5)
419 +
420 + def _vbars(self, s):
421 + """Barres verticales : série kind=bar ou distribution (bins)."""
422 + p = self.pdf
423 + pts = s.get("points") or [{"t": b.get("label"), "v": b.get("value")} for b in (s.get("bins") or [])]
424 + pts = [pt for pt in pts if isinstance(pt.get("v"), (int, float))]
425 + if not pts:
426 + return
427 + if p.get_y() > 205:
428 + p.add_page()
429 + self._chart_title(s.get("title", ""))
430 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 48
431 + self._card(x0, y0, w, h, fill=WHITE)
432 + cx, cy, cw, ch = x0 + 12, y0 + 5, w - 20, h - 14
433 + vmax = max(pt["v"] for pt in pts) or 1
434 + p.set_font("helvetica", "", 6.3)
435 + p.set_text_color(*INK3)
436 + p.set_draw_color(200, 200, 195)
437 + p.set_line_width(0.15)
438 + for g in range(5):
439 + gy = cy + ch - ch * g / 4
440 + p.line(cx, gy, cx + cw, gy)
441 + p.set_xy(x0 + 1, gy - 1.6)
442 + p.cell(10, 3, _fr(vmax * g / 4), align="R")
443 + n = len(pts)
444 + bw = max(0.8, cw / n - 0.6)
445 + p.set_fill_color(*self.accent)
446 + p.set_draw_color(*INK)
447 + p.set_line_width(0.15)
448 + for i, pt in enumerate(pts):
449 + bh = ch * (pt["v"] / vmax)
450 + p.rect(cx + cw * i / n + 0.3, cy + ch - bh, bw, max(bh, 0.4 if pt["v"] > 0 else 0), style="DF")
451 + p.set_text_color(*INK3)
452 + for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):
453 + p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)
454 + p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")
455 + p.set_y(y0 + h + 5)
456 +
457 + def _multiline(self, ms):
458 + """Multi-séries (≤4) : accent plein / encre fin / accent pointillé /
459 + gris pointillé — l'identité passe par le motif, pas la couleur seule."""
460 + p = self.pdf
461 + series = [s for s in (ms.get("series") or []) if len(s.get("points") or []) > 1][:4]
462 + if not series:
463 + return
464 + if p.get_y() > 195:
465 + p.add_page()
466 + self._chart_title(ms.get("title", ""))
467 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
468 + self._card(x0, y0, w, h, fill=WHITE)
469 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
470 + vals = [pt["v"] for s in series for pt in s["points"]]
471 + vmax = max(vals) or 1
472 + vmin = min(0, min(vals))
473 + rng = (vmax - vmin) or 1
474 + p.set_font("helvetica", "", 6.3)
475 + p.set_text_color(*INK3)
476 + p.set_draw_color(200, 200, 195)
477 + p.set_line_width(0.15)
478 + for g in range(5):
479 + gy = cy + ch - ch * g / 4
480 + p.line(cx, gy, cx + cw, gy)
481 + p.set_xy(x0 + 1, gy - 1.6)
482 + p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")
483 + styles = [
484 + (self.accent, 0.7, None),
485 + (INK, 0.45, None),
486 + (self.accent, 0.55, True),
487 + (INK3, 0.5, True),
488 + ]
489 + for si, s in enumerate(series):
490 + col, lw, dash = styles[si]
491 + p.set_draw_color(*col)
492 + p.set_line_width(lw)
493 + if dash:
494 + p.set_dash_pattern(dash=1.4, gap=1.2)
495 + n = len(s["points"])
496 + last = None
497 + for i, pt in enumerate(s["points"]):
498 + px = cx + cw * (i / (n - 1))
499 + py = cy + ch - ch * ((pt["v"] - vmin) / rng)
500 + if last:
501 + p.line(last[0], last[1], px, py)
502 + last = (px, py)
503 + p.set_dash_pattern()
504 + ref = series[0]["points"]
505 + p.set_text_color(*INK3)
506 + for frac, idx in ((0, 0), (0.5, len(ref) // 2), (1, -1)):
507 + p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)
508 + p.cell(18, 3, str(ref[idx].get("t", ""))[:10], align="C")
509 + p.set_y(y0 + h + 4)
510 + p.set_font("helvetica", "", 6.8)
511 + p.set_text_color(*INK3)
512 + marks = ["—", "—", "----", "----"]
513 + leg = " · ".join(f"{marks[i]} {s.get('label', '')}" for i, s in enumerate(series))
514 + p.cell(0, 4, leg[:120])
515 + p.ln(6)
516 +
517 + def _stacked(self, st):
518 + p = self.pdf
519 + keys = (st.get("keys") or [])[:6]
520 + pts = st.get("points") or []
521 + if not keys or not pts:
522 + return
523 + if p.get_y() > 195:
524 + p.add_page()
525 + self._chart_title(st.get("title", ""))
526 + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52
527 + self._card(x0, y0, w, h, fill=WHITE)
528 + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16
529 + totals = [sum(v or 0 for v in pt.get("values", [])[: len(keys)]) for pt in pts]
530 + vmax = max(totals) or 1
531 + p.set_font("helvetica", "", 6.3)
532 + p.set_text_color(*INK3)
533 + p.set_draw_color(200, 200, 195)
534 + p.set_line_width(0.15)
535 + for g in range(5):
536 + gy = cy + ch - ch * g / 4
537 + p.line(cx, gy, cx + cw, gy)
538 + p.set_xy(x0 + 1, gy - 1.6)
539 + p.cell(10, 3, _fr(vmax * g / 4), align="R")
540 + n = len(pts)
541 + bw = max(0.8, cw / n - 0.6)
542 + p.set_draw_color(*WHITE)
543 + p.set_line_width(0.12)
544 + for i, pt in enumerate(pts):
545 + yacc = cy + ch
546 + for j, k in enumerate(keys):
547 + v = (pt.get("values") or [0] * len(keys))[j] if j < len(pt.get("values", [])) else 0
548 + if not v:
549 + continue
550 + bh = ch * (v / vmax)
551 + yacc -= bh
552 + p.set_fill_color(*self._shade(j))
553 + p.rect(cx + cw * i / n + 0.3, yacc, bw, max(bh - 0.15, 0.3), style="DF")
554 + p.set_text_color(*INK3)
555 + for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):
556 + p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)
557 + p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")
558 + p.set_y(y0 + h + 4)
559 + # légende
560 + p.set_font("helvetica", "", 6.8)
561 + lx = p.l_margin
562 + for j, k in enumerate(keys):
563 + p.set_fill_color(*self._shade(j))
564 + p.set_draw_color(*INK)
565 + p.set_line_width(0.2)
566 + p.rect(lx, p.get_y() + 0.6, 3, 3, style="DF")
567 + p.set_xy(lx + 4, p.get_y())
568 + p.set_text_color(*INK2)
569 + txt = str(k)[:22]
570 + p.cell(p.get_string_width(txt) + 3, 4, txt)
571 + lx = p.get_x() + 3
572 + if lx > 165:
573 + break
574 + p.ln(7)
323 575
324 576 def _bars(self, title, items, unit=""):
325 577 p = self.pdf
@@ -329,10 +581,8 @@ class GroupeKAReport:
329 581 need = 10 + len(items) * 7
330 582 if p.get_y() + need > 265:
331 583 p.add_page()
332 − p.set_font("helvetica", "B", 10)
333 − p.set_text_color(*INK)
334 − p.cell(0, 6, title)
335 − p.ln(8)
584 + self._chart_title(title)
585 + p.ln(1)
336 586 vmax = max(it["value"] for it in items) or 1
337 587 for it in items:
338 588 y = p.get_y()
@@ -340,19 +590,23 @@ class GroupeKAReport:
340 590 p.set_text_color(*INK)
341 591 p.set_x(p.l_margin)
342 592 p.cell(46, 5, str(it["label"])[:34])
343 − bw = 96 * (it["value"] / vmax)
593 + bw = 86 * (it["value"] / vmax)
344 594 p.set_fill_color(*self.accent)
345 595 p.set_draw_color(*INK)
346 596 p.set_line_width(0.25)
347 597 p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF")
348 − p.set_xy(p.l_margin + 148, y)
598 + p.set_xy(p.l_margin + 136, y)
349 599 p.set_font("helvetica", "B", 7.6)
350 − p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
600 + p.cell(24, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")
601 + if it.get("delta_pct") is not None:
602 + up = it["delta_pct"] >= 0
603 + p.set_font("helvetica", "B", 6.6)
604 + p.set_text_color(*(GREEN if up else DANGER))
605 + p.cell(14, 5, f"{'+' if up else ''}{str(round(it['delta_pct'], 1)).replace('.', ',')} %", align="R")
351 606 p.ln(6.4)
352 607 p.ln(3)
353 608
354 609 def _donut(self, b):
355 − # anneau vectoriel simple (arcs) + légende
356 610 p = self.pdf
357 611 items = [it for it in (b.get("items") or []) if it.get("value")][:8]
358 612 total = sum(it["value"] for it in items)
@@ -360,17 +614,13 @@ class GroupeKAReport:
360 614 return
361 615 if p.get_y() > 210:
362 616 p.add_page()
363 − p.set_font("helvetica", "B", 10)
364 − p.set_text_color(*INK)
365 − p.cell(0, 6, b.get("title", ""))
366 − p.ln(8)
617 + self._chart_title(b.get("title", ""))
618 + p.ln(1)
367 619 cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20
368 − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]
369 620 start = -90.0
370 621 for i, it in enumerate(items):
371 622 frac = it["value"] / total
372 − f = shades[i % len(shades)]
373 − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
623 + col = self._shade(i)
374 624 steps = max(2, int(72 * frac))
375 625 p.set_fill_color(*col)
376 626 p.set_draw_color(*col)
@@ -389,11 +639,9 @@ class GroupeKAReport:
389 639 p.set_line_width(0.4)
390 640 p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")
391 641 p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")
392 − # légende
393 642 ly = cy - 22
394 643 for i, it in enumerate(items):
395 − f = shades[i % len(shades)]
396 − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))
644 + col = self._shade(i)
397 645 p.set_fill_color(*col)
398 646 p.set_draw_color(*INK)
399 647 p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")
@@ -405,7 +653,39 @@ class GroupeKAReport:
405 653 ly += 5.6
406 654 p.set_y(max(cy + r, ly) + 6)
407 655
408 − def _table(self, t):
656 + def _hourly(self):
657 + hh = self.d.get("hourly") or {}
658 + cells = hh.get("cells") or []
659 + if not cells:
660 + return
661 + p = self.pdf
662 + if p.get_y() > 190:
663 + p.add_page()
664 + self._chart_title(hh.get("title", "Activité par jour et heure"))
665 + x0, y0 = p.l_margin, p.get_y()
666 + cw, chh, lx, ly = 6.4, 6.4, 12, 5
667 + vmax = max((c.get("value") or 0) for c in cells) or 1
668 + grid = {(c.get("dow"), c.get("hour")): c.get("value") or 0 for c in cells}
669 + dows = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"]
670 + p.set_font("helvetica", "", 5.8)
671 + p.set_text_color(*INK3)
672 + for h in (0, 6, 12, 18, 23):
673 + p.set_xy(x0 + lx + h * cw, y0)
674 + p.cell(cw, 3, f"{h}h", align="C")
675 + for d in range(7):
676 + p.set_xy(x0, y0 + ly + d * chh + 1.5)
677 + p.cell(lx - 1, 3, dows[d], align="R")
678 + for h in range(24):
679 + v = grid.get((d, h), 0)
680 + f = 0.1 + 0.9 * (v / vmax) if v else 0.0
681 + col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) if v else (235, 233, 228)
682 + p.set_fill_color(*col)
683 + p.set_draw_color(215, 213, 207)
684 + p.set_line_width(0.1)
685 + p.rect(x0 + lx + h * cw, y0 + ly + d * chh, cw - 0.5, chh - 0.5, style="DF")
686 + p.set_y(y0 + ly + 7 * chh + 5)
687 +
688 + def _table(self, t, max_rows=200):
409 689 p = self.pdf
410 690 cols = t.get("columns") or []
411 691 rows = t.get("rows") or []
@@ -422,7 +702,7 @@ class GroupeKAReport:
422 702 p.ln(6)
423 703 head()
424 704 p.set_text_color(*INK)
425 − for i, row in enumerate(rows[:200]):
705 + for i, row in enumerate(rows[:max_rows]):
426 706 if p.get_y() > 262:
427 707 p.add_page()
428 708 head()
@@ -433,10 +713,10 @@ class GroupeKAReport:
433 713 txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)
434 714 p.cell(w, 5.4, " " + txt[:34], fill=True)
435 715 p.ln(5.4)
436 − if len(rows) > 200:
716 + if len(rows) > max_rows:
437 717 p.set_font("helvetica", "", 7)
438 718 p.set_text_color(*INK3)
439 − p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées")
719 + p.cell(0, 5, f"… {len(rows) - max_rows} lignes supplémentaires non imprimées")
440 720 p.ln(6)
441 721
442 722 def _records(self):
@@ -445,7 +725,7 @@ class GroupeKAReport:
445 725 return
446 726 self._section_title("Records & faits marquants")
447 727 p = self.pdf
448 − for r in recs[:10]:
728 + for r in recs[:14]:
449 729 if p.get_y() > 258:
450 730 p.add_page()
451 731 y = p.get_y()
@@ -503,43 +783,76 @@ class GroupeKAReport:
503 783 "groupe-ka.com/conditions · /confidentialite · /loi-25.",
504 784 )
505 785
506 − def _toc_page(self):
507 − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en
508 − # page 2 en réservant la page lors du build (voir build()).
509 − pass
786 + # ---------- groupes de sections ----------
787 + def _all_series(self, with_stats=True):
788 + for s in self.d.get("series") or []:
789 + self._line_chart(s, with_stats=with_stats)
790 + for ms in self.d.get("multiseries") or []:
791 + self._multiline(ms)
792 + for st in self.d.get("stacked") or []:
793 + self._stacked(st)
794 +
795 + def _all_breakdowns(self):
796 + for b in self.d.get("breakdowns") or []:
797 + if b.get("kind") == "donut":
798 + self._donut(b)
799 + else:
800 + self._bars(b.get("title", ""), b.get("items"))
801 + for dist in self.d.get("distributions") or []:
802 + self._vbars(dist)
803 + geo = self.d.get("geo")
804 + if geo:
805 + self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
806 + self._hourly()
510 807
511 808 def build(self) -> bytes:
512 809 p = self.pdf
513 810 p.alias_nb_pages()
514 811 self._cover()
812 + with_toc = self.mode in ("complet", "donnees")
813 + toc_page_no = None
515 814 if self.mode == "synthese":
516 815 p.add_page()
517 816 self._kpis()
817 + self._gauges()
818 + self._records()
819 + self._final_page()
820 + elif self.mode == "tendances":
821 + p.add_page()
822 + self._kpis()
823 + self._section_title("Évolution & tendances")
824 + self._all_series(with_stats=True)
518 825 self._records()
519 826 self._final_page()
520 − else:
827 + elif self.mode == "repartitions":
828 + p.add_page()
829 + self._section_title("Répartitions, distributions & géographie")
830 + self._all_breakdowns()
831 + self._final_page()
832 + elif self.mode == "donnees":
833 + p.add_page()
834 + toc_page_no = p.page_no()
835 + for t in self.d.get("tables") or []:
836 + self._table(t, max_rows=400)
837 + self._final_page()
838 + else: # complet
521 839 p.add_page()
522 840 toc_page_no = p.page_no()
523 841 p.add_page()
524 842 self._kpis()
525 − for s in self.d.get("series") or []:
526 − if s.get("kind") == "bar":
527 − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", ""))
528 − else:
529 − self._line_chart(s)
530 − for b in self.d.get("breakdowns") or []:
531 − if b.get("kind") == "donut":
532 − self._donut(b)
533 − else:
534 − self._bars(b.get("title", ""), b.get("items"))
535 − geo = self.d.get("geo")
536 − if geo:
537 − self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))
843 + self._gauges()
844 + if (self.d.get("series") or self.d.get("multiseries") or self.d.get("stacked")):
845 + self._section_title("Évolution & tendances")
846 + self._all_series(with_stats=True)
847 + if (self.d.get("breakdowns") or self.d.get("distributions") or self.d.get("geo") or self.d.get("hourly")):
848 + self._section_title("Répartitions, distributions & géographie")
849 + self._all_breakdowns()
538 850 for t in self.d.get("tables") or []:
539 851 self._table(t)
540 852 self._records()
541 853 self._final_page()
542 − # sommaire écrit sur la page réservée (page 2)
854 + # sommaire écrit sur la page réservée
855 + if toc_page_no is not None:
543 856 last_page = p.page
544 857 p.page = toc_page_no
545 858 p.set_y(22)
@@ -558,6 +871,7 @@ class GroupeKAReport:
558 871 return bytes(p.output())
559 872
560 873
561 −def filename(platform_id: str, period: str) -> str:
874 +def filename(platform_id: str, period: str, mode: str = "complet") -> str:
562 875 today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")
563 − return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf"
876 + suffix = "" if mode in ("", "complet") else f"_{mode}"
877 + return f"groupe-ka_{platform_id}_stats_{period}{suffix}_{today}.pdf"
modified restoka/stats.py +382 −39
@@ -1,11 +1,14 @@
1 1 # ==============================================================================
2 2 # Author: Simon-Pierre Boucher <contact@spboucher.ai>
3 3 # File: restoka/stats.py
4 −# Desc: Tableau de bord analytique — contrat commun Groupe KA (ka-ui/stats/
5 −# SPEC.md §2). Agrège la DB réelle (restaurants, menus, item_price_log,
6 −# sync_log) : KPI avec deltas, séries quotidiennes, répartitions,
7 −# géographie, heatmap, tableaux et records. AUCUNE stat inventée :
8 −# une mesure indisponible est simplement absente du JSON.
4 +# Desc: Tableau de bord analytique — contrat commun Groupe KA v2 (ka-ui/
5 +# stats/SPEC.md §2). Agrège la DB réelle (restaurants, menus,
6 +# item_price_log, sync_log, details RACJ/Yelp/MAPAQ) : KPI avec deltas
7 +# et sparklines, jauges de complétude, séries quotidiennes, multi-
8 +# courbes (prix moyen par ville), barres empilées (ajouts par source),
9 +# répartitions, distributions, géographie, heatmaps calendrier +
10 +# horaire, tableaux et records. AUCUNE stat inventée : une mesure
11 +# indisponible est simplement absente du JSON.
9 12 # Cache mémoire 5 min par période.
10 13 # ==============================================================================
11 14 from __future__ import annotations
@@ -44,9 +47,20 @@ _TYPE_LABELS = {
44 47 "Boulangerie-pâtisserie", "casse-croute": "Casse-croûte",
45 48 "traiteur": "Traiteur", "creme-glacee": "Crème glacée",
46 49 }
47 −_PRICE_BUCKETS = [
48 − ("moins de 10 $", 0, 10), ("10 à 15 $", 10, 15), ("15 à 20 $", 15, 20),
49 − ("20 à 30 $", 20, 30), ("30 à 50 $", 30, 50), ("50 $ et plus", 50, 1e9),
50 +_CTX_LABELS = {"dine-in": "En salle", "takeout": "Pour emporter",
51 + "delivery": "Livraison"}
52 +_PRICE_BINS = [
53 + ("< 5 $", 0, 5), ("5-10 $", 5, 10), ("10-15 $", 10, 15),
54 + ("15-20 $", 15, 20), ("20-25 $", 20, 25), ("25-30 $", 25, 30),
55 + ("30-40 $", 30, 40), ("40-50 $", 40, 50), ("50 $ +", 50, 1e9),
56 +]
57 +_CAP_BINS = [
58 + ("1-50", 1, 50), ("50-100", 50, 100), ("100-200", 100, 200),
59 + ("200-300", 200, 300), ("300-500", 300, 500), ("500 +", 500, 1e9),
60 +]
61 +_YELP_BINS = [
62 + ("< 3", 0, 3), ("3 à 3,5", 3, 3.5), ("3,5 à 4", 3.5, 4),
63 + ("4 à 4,5", 4, 4.5), ("4,5 à 5", 4.5, 5.01),
50 64 ]
51 65
52 66 PERIOD_LABELS = {
@@ -99,15 +113,37 @@ def _delta(cur: float, prev: float) -> float | None:
99 113 return round(100.0 * (cur - prev) / prev, 1)
100 114
101 115
102 −def _kpi(id_, label, value, unit="", delta_pct=None, positive_is_up=True):
116 +def _kpi(id_, label, value, unit="", delta_pct=None, positive_is_up=True,
117 + spark=None):
103 118 k = {"id": id_, "label": label, "value": value, "unit": unit,
104 119 "delta_pct": delta_pct}
105 120 if delta_pct is not None:
106 121 up = delta_pct >= 0 if positive_is_up else delta_pct < 0
107 122 k["direction"] = "up" if up else "down"
123 + if spark and len(spark) >= 2:
124 + k["spark"] = spark
108 125 return k
109 126
110 127
128 +def _spark(pts: list[dict], n: int = 30) -> list[dict]:
129 + """Sous-échantillonne une série quotidienne pour la sparkline (≤ n pts)."""
130 + if len(pts) <= n:
131 + return pts
132 + step = max(1, len(pts) // n)
133 + out = pts[::step]
134 + if out[-1] is not pts[-1]:
135 + out.append(pts[-1])
136 + return out
137 +
138 +
139 +def _pct(part: int, total: int) -> float:
140 + return round(100.0 * part / total, 1) if total else 0.0
141 +
142 +
143 +def _fr(n: float, dec: int = 2) -> str:
144 + return f"{n:.{dec}f}".replace(".", ",")
145 +
146 +
111 147 def _daily(rows: list, f: date, t: date, cumulative: bool = False,
112 148 base: int = 0) -> list[dict]:
113 149 """Série quotidienne bouchée à zéro sur [f, t] à partir de {jour: n}."""
@@ -142,6 +178,17 @@ def _iter_menu_items(con):
142 178 yield r, it
143 179
144 180
181 +def _bin_counts(values: list[float], bins) -> list[dict]:
182 + counts = Counter()
183 + for v in values:
184 + for lbl, lo, hi in bins:
185 + if lo <= v < hi:
186 + counts[lbl] += 1
187 + break
188 + return [{"label": lbl, "value": counts[lbl]}
189 + for lbl, _, _ in bins if counts[lbl]]
190 +
191 +
145 192 def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
146 193 con = db.connect()
147 194 try:
@@ -177,6 +224,9 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
177 224 chains = con.execute(
178 225 f"SELECT COUNT(DISTINCT chain) n FROM restaurants WHERE {A}"
179 226 " AND chain IS NOT NULL").fetchone()["n"]
227 + cities = con.execute(
228 + f"SELECT COUNT(DISTINCT city) n FROM restaurants WHERE {A}"
229 + " AND city<>''").fetchone()["n"]
180 230
181 231 new_cur = con.execute(
182 232 f"SELECT COUNT(*) n FROM restaurants WHERE {A}"
@@ -194,20 +244,57 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
194 244 " AND status IN ('temporarily_closed','closed')"
195 245 " AND updated_at>=? AND updated_at<?", (pf_ts, pt_ts)).fetchone()["n"]
196 246
197 − kpis = [
198 − _kpi("total", "Restaurants référencés", total,
199 − delta_pct=_delta(stock_end, stock_start)),
200 − _kpi("with_menu", "Restos avec menu & prix", with_menu),
201 − _kpi("items", "Plats & prix suivis", items),
202 − _kpi("chains", "Chaînes suivies", chains),
203 − _kpi("new", "Nouveaux référencés (période)", new_cur,
204 − delta_pct=_delta(new_cur, new_prev)),
205 − _kpi("closed", "Fermetures détectées (période)", closed_cur,
206 − delta_pct=_delta(closed_cur, closed_prev),
207 − positive_is_up=False),
208 − ]
209 −
210 − # --------------------------------------------------------- séries ---
247 + releves_cur = con.execute(
248 + "SELECT COUNT(*) n FROM item_price_log WHERE ts>=? AND ts<?",
249 + (f_ts, t_ts)).fetchone()["n"]
250 + releves_prev = con.execute(
251 + "SELECT COUNT(*) n FROM item_price_log WHERE ts>=? AND ts<?",
252 + (pf_ts, pt_ts)).fetchone()["n"]
253 +
254 + # -------------------------------------------- complétude des fiches ---
255 + comp = con.execute(
256 + f"""SELECT
257 + SUM(lat IS NOT NULL AND lng IS NOT NULL) geo,
258 + SUM(phone<>'') tel,
259 + SUM(website<>'') web,
260 + SUM(hours IS NOT NULL AND hours<>'' AND hours<>'{{}}') hrs,
261 + SUM(price_range<>'') pr,
262 + SUM(images IS NOT NULL AND images<>'' AND images<>'[]') img
263 + FROM restaurants WHERE {A}""").fetchone()
264 +
265 + # ------------------------- enrichissements (details : RACJ/Yelp/MAPAQ)
266 + permis_n = 0
267 + caps: list[float] = []
268 + max_cap: tuple[str | None, float] = (None, 0.0)
269 + yelp_ratings: list[float] = []
270 + best_yelp: tuple[str | None, float, int] = (None, 0.0, 0)
271 + mapaq_n = 0
272 + for r in con.execute(
273 + f"SELECT name, city, details FROM restaurants WHERE {A}"
274 + " AND details IS NOT NULL AND details<>''"):
275 + try:
276 + det = json.loads(r["details"])
277 + except ValueError:
278 + continue
279 + pa = det.get("permis_alcool")
280 + if pa:
281 + permis_n += 1
282 + cap = pa.get("capacite")
283 + if isinstance(cap, (int, float)) and cap > 0:
284 + caps.append(float(cap))
285 + if cap > max_cap[1]:
286 + max_cap = (f"{r['name']} ({r['city']})", float(cap))
287 + y = det.get("yelp")
288 + if y and isinstance(y.get("rating"), (int, float)):
289 + yelp_ratings.append(float(y["rating"]))
290 + rc = int(y.get("review_count") or 0)
291 + if (y["rating"], rc) > (best_yelp[1], best_yelp[2]):
292 + best_yelp = (f"{r['name']} ({r['city']})",
293 + float(y["rating"]), rc)
294 + if det.get("mapaq"):
295 + mapaq_n += 1
296 +
297 + # -------------------------------------------- séries quotidiennes ---
211 298 new_by_day = [(r["d"], r["n"]) for r in con.execute(
212 299 "SELECT date(first_seen,'unixepoch','localtime') d, COUNT(*) n"
213 300 f" FROM restaurants WHERE {A} AND first_seen>=? AND first_seen<?"
@@ -222,17 +309,127 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
222 309 "SELECT COUNT(*) n FROM (SELECT MIN(ts) m0 FROM item_price_log"
223 310 " GROUP BY uid, price_context, item_key) WHERE m0<?",
224 311 (f_ts,)).fetchone()["n"]
312 + releves_by_day = [(r["d"], r["n"]) for r in con.execute(
313 + "SELECT date(ts,'unixepoch','localtime') d, COUNT(*) n"
314 + " FROM item_price_log WHERE ts>=? AND ts<? GROUP BY d",
315 + (f_ts, t_ts))]
316 + updated_by_day = [(r["d"], r["n"]) for r in con.execute(
317 + "SELECT date(updated_at,'unixepoch','localtime') d, COUNT(*) n"
318 + f" FROM restaurants WHERE {A} AND updated_at>=? AND updated_at<?"
319 + " GROUP BY d", (f_ts, t_ts))]
320 +
321 + stock_pts = _daily(new_by_day, f, t, cumulative=True,
322 + base=stock_start)
323 + new_pts = _daily(new_by_day, f, t)
324 + items_pts = _daily(items_first, f, t, cumulative=True,
325 + base=items_base)
326 + releves_pts = _daily(releves_by_day, f, t)
327 + updated_pts = _daily(updated_by_day, f, t)
225 328
329 + kpis = [
330 + _kpi("total", "Restaurants référencés", total,
331 + delta_pct=_delta(stock_end, stock_start),
332 + spark=_spark(stock_pts)),
333 + _kpi("with_menu", "Restos avec menu & prix", with_menu),
334 + _kpi("items", "Plats & prix suivis", items,
335 + spark=_spark(items_pts)),
336 + _kpi("releves", "Relevés de prix (période)", releves_cur,
337 + delta_pct=_delta(releves_cur, releves_prev),
338 + spark=_spark(releves_pts)),
339 + _kpi("chains", "Chaînes suivies", chains),
340 + _kpi("cities", "Villes couvertes", cities),
341 + _kpi("new", "Nouveaux référencés (période)", new_cur,
342 + delta_pct=_delta(new_cur, new_prev),
343 + spark=_spark(new_pts)),
344 + _kpi("closed", "Fermetures détectées (période)", closed_cur,
345 + delta_pct=_delta(closed_cur, closed_prev),
346 + positive_is_up=False),
347 + _kpi("permis", "Permis d'alcool reliés (RACJ)", permis_n),
348 + _kpi("yelp", "Notes Yelp reliées", len(yelp_ratings)),
349 + ]
350 +
351 + # ----------------------------------------------------------- jauges ---
352 + gauges = [
353 + {"id": "geo", "label": "Restos géolocalisés",
354 + "value": _pct(comp["geo"], total), "max": 100, "unit": "%"},
355 + {"id": "menu", "label": "Restos avec menu & prix",
356 + "value": _pct(with_menu, total), "max": 100, "unit": "%"},
357 + {"id": "tel", "label": "Fiches avec téléphone",
358 + "value": _pct(comp["tel"], total), "max": 100, "unit": "%"},
359 + {"id": "hours", "label": "Horaires structurés",
360 + "value": _pct(comp["hrs"], total), "max": 100, "unit": "%"},
361 + {"id": "web", "label": "Fiches avec site web",
362 + "value": _pct(comp["web"], total), "max": 100, "unit": "%"},
363 + {"id": "pr", "label": "Fourchette de prix estimée",
364 + "value": _pct(comp["pr"], total), "max": 100, "unit": "%"},
365 + ]
366 +
367 + # ----------------------------------------------------------- séries ---
226 368 series = [
227 369 {"id": "new_restos", "title": "Nouveaux restos référencés par jour",
228 − "unit": "restos", "kind": "line",
229 − "points": _daily(new_by_day, f, t)},
370 + "unit": "restos", "kind": "line", "points": new_pts},
230 371 {"id": "items_cum", "title": "Plats & prix suivis (cumul)",
231 − "unit": "plats", "kind": "line",
232 − "points": _daily(items_first, f, t, cumulative=True,
233 − base=items_base)},
372 + "unit": "plats", "kind": "area", "points": items_pts},
373 + {"id": "releves", "title": "Relevés de prix par jour",
374 + "unit": "relevés", "kind": "bar", "points": releves_pts},
375 + {"id": "updated", "title": "Fiches mises à jour par jour",
376 + "unit": "fiches", "kind": "bar", "points": updated_pts},
234 377 ]
235 378
379 + # -------------------------------- multi-courbes : prix moyen / ville ---
380 + # jours de la période où des relevés existent (grille commune)
381 + grid_days = [r["d"] for r in con.execute(
382 + "SELECT DISTINCT date(ts,'unixepoch','localtime') d"
383 + " FROM item_price_log WHERE ts>=? AND ts<? AND price>0"
384 + " ORDER BY d", (f_ts, t_ts))]
385 + multiseries = []
386 + if len(grid_days) >= 2:
387 + city_day: dict[str, dict[str, float]] = {}
388 + city_tot: Counter = Counter()
389 + for r in con.execute(
390 + "SELECT re.city c, date(l.ts,'unixepoch','localtime') d,"
391 + " AVG(l.price) a, COUNT(*) n FROM item_price_log l"
392 + " JOIN restaurants re ON re.uid=l.uid"
393 + " WHERE l.ts>=? AND l.ts<? AND l.price>0 AND re.city<>''"
394 + " GROUP BY c, d", (f_ts, t_ts)):
395 + city_day.setdefault(r["c"], {})[r["d"]] = round(r["a"], 2)
396 + city_tot[r["c"]] += r["n"]
397 + chosen = []
398 + for city, _n in city_tot.most_common():
399 + if all(d in city_day[city] for d in grid_days):
400 + chosen.append(city)
401 + if len(chosen) == 4:
402 + break
403 + if len(chosen) >= 2:
404 + multiseries.append({
405 + "id": "prix_villes",
406 + "title": "Prix moyen d'un plat relevé — grandes villes",
407 + "unit": "$",
408 + "series": [{"label": c, "points": [
409 + {"t": d, "v": city_day[c][d]} for d in grid_days]}
410 + for c in chosen]})
411 +
412 + # ------------------------------- empilé : éléments ajoutés / source ---
413 + src_added: dict[str, list] = {}
414 + for r in con.execute(
415 + "SELECT source s, date(ts,'unixepoch','localtime') d,"
416 + " SUM(added) n FROM sync_log WHERE ts>=? AND ts<?"
417 + " GROUP BY s, d", (f_ts, t_ts)):
418 + src_added.setdefault(r["s"], []).append((r["d"], r["n"] or 0))
419 + stacked = []
420 + if src_added:
421 + keys = sorted(src_added,
422 + key=lambda s: -sum(n for _, n in src_added[s]))[:6]
423 + per_key = {k: _daily(src_added[k], f, t) for k in keys}
424 + grid = per_key[keys[0]]
425 + stacked.append({
426 + "id": "ajouts_sources",
427 + "title": "Éléments ajoutés par source (journal de sync)",
428 + "unit": "ajouts", "keys": keys,
429 + "points": [{"t": grid[i]["t"],
430 + "values": [per_key[k][i]["v"] for k in keys]}
431 + for i in range(len(grid))]})
432 +
236 433 # ---------------------------------------------- répartitions (stock) ---
237 434 cuisine_counts: Counter = Counter()
238 435 for r in con.execute(
@@ -243,7 +440,6 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
243 440 {"label": _CUISINE_LABELS.get(c, c.capitalize()), "value": n}
244 441 for c, n in cuisine_counts.most_common(8)]
245 442
246 − price_counts = Counter()
247 443 max_item = (None, 0.0) # (desc, prix) — record réel
248 444 all_prices: list[float] = []
249 445 for r, it in _iter_menu_items(con):
@@ -251,14 +447,8 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
251 447 if not isinstance(p, (int, float)) or p <= 0:
252 448 continue
253 449 all_prices.append(float(p))
254 − for lbl, lo, hi in _PRICE_BUCKETS:
255 − if lo <= p < hi:
256 − price_counts[lbl] += 1
257 − break
258 450 if p > max_item[1]:
259 451 max_item = (f"{it.get('name')} — {r['chain'] or r['name']}", p)
260 − price_items = [{"label": lbl, "value": price_counts[lbl]}
261 − for lbl, _, _ in _PRICE_BUCKETS if price_counts[lbl]]
262 452
263 453 types = [{"label": _TYPE_LABELS.get(r["t"], r["t"] or "Autre"),
264 454 "value": r["n"]} for r in con.execute(
@@ -266,14 +456,47 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
266 456 f" WHERE {A} AND establishment_type<>'' GROUP BY t"
267 457 " ORDER BY n DESC")]
268 458
459 + ctx_items = [{"label": _CTX_LABELS.get(r["c"], r["c"]), "value": r["n"]}
460 + for r in con.execute(
461 + "SELECT m.price_context c, COUNT(*) n FROM menus m"
462 + " JOIN restaurants r ON r.uid=m.uid"
463 + " WHERE r.active=1 AND r.dup_of IS NULL"
464 + " GROUP BY c ORDER BY n DESC")]
465 +
466 + gamme_items = [{"label": r["g"], "value": r["n"]} for r in con.execute(
467 + f"SELECT price_range g, COUNT(*) n FROM restaurants WHERE {A}"
468 + " AND price_range<>'' GROUP BY g ORDER BY LENGTH(g)")]
469 +
269 470 breakdowns = [
270 471 {"id": "cuisines", "title": "Restos par type de cuisine (top 8)",
271 472 "kind": "donut", "items": top_cuisines},
272 − {"id": "prix", "title": "Plats par gamme de prix",
273 − "kind": "bar", "items": price_items},
473 + {"id": "contextes", "title": "Menus par contexte de prix",
474 + "kind": "donut", "items": ctx_items},
274 475 {"id": "types", "title": "Par type d'établissement",
275 476 "kind": "bar", "items": types},
276 477 ]
478 + if gamme_items:
479 + breakdowns.append(
480 + {"id": "gammes",
481 + "title": "Restos par fourchette de prix estimée",
482 + "kind": "bar", "items": gamme_items})
483 +
484 + # ---------------------------------------------------- distributions ---
485 + distributions = []
486 + if all_prices:
487 + distributions.append(
488 + {"id": "prix_plats", "title": "Distribution des prix de plats",
489 + "unit": "plats", "bins": _bin_counts(all_prices, _PRICE_BINS)})
490 + if caps:
491 + distributions.append(
492 + {"id": "capacites",
493 + "title": "Capacité des salles (permis d'alcool RACJ)",
494 + "unit": "restos", "bins": _bin_counts(caps, _CAP_BINS)})
495 + if yelp_ratings:
496 + distributions.append(
497 + {"id": "notes_yelp", "title": "Distribution des notes Yelp",
498 + "unit": "restos",
499 + "bins": _bin_counts(yelp_ratings, _YELP_BINS)})
277 500
278 501 # -------------------------------------------------------------- géo ---
279 502 geo = {"title": "Restos par région", "items": [
@@ -287,6 +510,18 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
287 510 f" FROM restaurants WHERE {A} GROUP BY d ORDER BY d")]
288 511 heatmap = {"title": "Nouveaux restos référencés", "cells": heat}
289 512
513 + # ------------------------------------------- heatmap horaire (7×24) ---
514 + hourly_cells = [
515 + {"dow": r["w"], "hour": r["h"], "value": r["n"]}
516 + for r in con.execute(
517 + "SELECT (CAST(strftime('%w',ts,'unixepoch','localtime')"
518 + " AS INTEGER)+6)%7 w,"
519 + " CAST(strftime('%H',ts,'unixepoch','localtime') AS INTEGER) h,"
520 + " COUNT(*) n FROM item_price_log WHERE ts>=? AND ts<?"
521 + " GROUP BY w, h", (f_ts, t_ts))]
522 + hourly = ({"title": "Relevés de prix par heure", "cells": hourly_cells}
523 + if hourly_cells else None)
524 +
290 525 # --------------------------------------------------------- tableaux ---
291 526 top_cities = [[r["city"], r["n"], r["wm"],
292 527 f"{100.0 * r['n'] / total:.1f} %".replace(".", ",")]
@@ -325,6 +560,61 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
325 560 if cr["prices"] else "—")
326 561 top_chains.append([name, cr["locs"], cr["items"] or "—", avg])
327 562
563 + # top établissements par nombre de plats au menu
564 + seen_uids: set[str] = set()
565 + top_places = []
566 + for r in con.execute(
567 + "SELECT r.uid, r.name, r.city, m.price_context c,"
568 + " m.item_count ic, m.sections FROM menus m"
569 + " JOIN restaurants r ON r.uid=m.uid"
570 + " WHERE r.active=1 AND r.dup_of IS NULL"
571 + " ORDER BY m.item_count DESC LIMIT 60"):
572 + if r["uid"] in seen_uids:
573 + continue
574 + seen_uids.add(r["uid"])
575 + prices = []
576 + try:
577 + secs = json.loads(r["sections"] or "[]")
578 + prices = [it["price"] for s in secs
579 + for it in s.get("items") or []
580 + if isinstance(it.get("price"), (int, float))
581 + and it["price"] > 0]
582 + except ValueError:
583 + pass
584 + avg = (f"{statistics.mean(prices):.2f} $".replace(".", ",")
585 + if prices else "—")
586 + top_places.append([r["name"], r["city"] or "—",
587 + _CTX_LABELS.get(r["c"], r["c"]),
588 + r["ic"] or 0, avg])
589 + if len(top_places) == 25:
590 + break
591 +
592 + # sources & connecteurs : couverture + dernier sync
593 + src_restos = {r["source"]: (r["n"], r["wm"]) for r in con.execute(
594 + f"SELECT source, COUNT(*) n, SUM(EXISTS (SELECT 1 FROM menus m"
595 + f" WHERE m.uid=restaurants.uid)) wm FROM restaurants WHERE {A}"
596 + " GROUP BY source")}
597 + src_last: dict[str, dict] = {}
598 + for r in con.execute(
599 + "SELECT source, ts, added, ok, message FROM sync_log"
600 + " ORDER BY ts"):
601 + src_last[r["source"]] = dict(r)
602 + src_added_period = {r["source"]: r["n"] or 0 for r in con.execute(
603 + "SELECT source, SUM(added) n FROM sync_log"
604 + " WHERE ts>=? AND ts<? GROUP BY source", (f_ts, t_ts))}
605 + sources_rows = []
606 + for s in sorted(set(src_restos) | set(src_last),
607 + key=lambda s: -(src_restos.get(s, (0, 0))[0])):
608 + n, wm = src_restos.get(s, (0, 0))
609 + last = src_last.get(s)
610 + when = (datetime.fromtimestamp(last["ts"], TZ)
611 + .strftime("%Y-%m-%d %H:%M") if last else "—")
612 + state = ("—" if not last else
613 + "ok" if last["ok"] and last["message"] == "ok"
614 + else ("alerte" if last["ok"] else "échec"))
615 + sources_rows.append([s, n, wm or 0,
616 + src_added_period.get(s, 0), when, state])
617 +
328 618 newest = [[r["name"], r["city"] or "—", r["region"] or "—",
329 619 _day(r["first_seen"])] for r in con.execute(
330 620 f"SELECT name, city, region, first_seen FROM restaurants"
@@ -350,6 +640,19 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
350 640 "Prix moyen"],
351 641 "rows": top_chains},
352 642 ]
643 + if top_places:
644 + tables.append(
645 + {"id": "etablissements",
646 + "title": "Top établissements par plats au menu",
647 + "columns": ["Restaurant", "Ville", "Contexte", "Plats",
648 + "Prix moyen"],
649 + "rows": top_places})
650 + if sources_rows:
651 + tables.append(
652 + {"id": "sources", "title": "Sources & connecteurs",
653 + "columns": ["Source", "Restos actifs", "Avec menu",
654 + "Ajoutés (période)", "Dernier sync", "État"],
655 + "rows": sources_rows})
353 656 if newest:
354 657 tables.append(
355 658 {"id": "nouveaux", "title": "Nouveaux restos de la période"
@@ -373,6 +676,15 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
373 676 records.append({"label": "Jour record de référencement",
374 677 "value": f"{rec_day['n']:,} restos".replace(",", " "),
375 678 "date": rec_day["d"]})
679 + big_menu = con.execute(
680 + "SELECT r.name, r.city, m.item_count ic FROM menus m"
681 + " JOIN restaurants r ON r.uid=m.uid"
682 + " WHERE r.active=1 AND r.dup_of IS NULL"
683 + " ORDER BY m.item_count DESC LIMIT 1").fetchone()
684 + if big_menu and big_menu["ic"]:
685 + records.append({"label": "Menu le plus étoffé",
686 + "value": f"{big_menu['name']} ({big_menu['city']})"
687 + f" — {big_menu['ic']} plats"})
376 688 big_chain = max(chain_rows.items(), key=lambda kv: kv[1]["items"],
377 689 default=None)
378 690 if big_chain and big_chain[1]["items"]:
@@ -405,12 +717,34 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
405 717 "value": f"{rec_price_day['n']:,} relevés"
406 718 .replace(",", " "),
407 719 "date": rec_price_day["d"]})
408 −
409 − return {
720 + if max_cap[0]:
721 + records.append({"label": "Plus grande salle (permis RACJ)",
722 + "value": f"{max_cap[0][:44]} — "
723 + f"{int(max_cap[1])} places"})
724 + if best_yelp[0]:
725 + records.append({"label": "Meilleure note Yelp reliée",
726 + "value": f"{best_yelp[0][:40]} — "
727 + f"{_fr(best_yelp[1], 1)}/5"
728 + f" ({best_yelp[2]} avis)"})
729 + if src_added:
730 + bs_name, bs_rows = max(src_added.items(),
731 + key=lambda kv: sum(n for _, n in kv[1]))
732 + bs_tot = sum(n for _, n in bs_rows)
733 + if bs_tot:
734 + records.append(
735 + {"label": "Source la plus productive (période)",
736 + "value": f"{bs_name} — {bs_tot:,} ajouts"
737 + .replace(",", " ")})
738 + if mapaq_n:
739 + records.append({"label": "Restos avec dossier MAPAQ relié",
740 + "value": f"{mapaq_n} établissements"})
741 +
742 + out = {
410 743 "updated": datetime.now(TZ).isoformat(timespec="seconds"),
411 744 "period": {"from": f.isoformat(), "to": t.isoformat(),
412 745 "label": label},
413 746 "kpis": kpis,
747 + "gauges": gauges,
414 748 "series": series,
415 749 "breakdowns": breakdowns,
416 750 "geo": geo,
@@ -418,6 +752,15 @@ def _build(period: str, dfrom: str | None, dto: str | None) -> dict:
418 752 "tables": tables,
419 753 "records": records,
420 754 }
755 + if multiseries:
756 + out["multiseries"] = multiseries
757 + if stacked:
758 + out["stacked"] = stacked
759 + if distributions:
760 + out["distributions"] = distributions
761 + if hourly:
762 + out["hourly"] = hourly
763 + return out
421 764 finally:
422 765 con.close()
423 766
modified restoka/web.py +6 −4
@@ -407,16 +407,18 @@ def stats_report(
407 407 to: str | None = Query(None),
408 408 mode: str = "complet",
409 409 ):
410 − """Rapport PDF estampillé Groupe-KA (complet ou synthèse 2 pages)."""
410 + """Rapport PDF estampillé Groupe-KA — 5 modes (SPEC v2 §3) :
411 + complet | synthese | tendances | repartitions | donnees.
412 + Un mode inconnu retombe sur complet (rétrocompatible v1)."""
411 413 from . import kapdf
412 414 from . import stats as kastats
413 − if mode not in ("complet", "synthese"):
414 − raise HTTPException(400, "mode invalide (complet|synthese)")
415 + if mode not in kapdf.REPORT_MODES:
416 + mode = "complet"
415 417 if period not in kastats.PERIOD_LABELS and not (from_ and to):
416 418 raise HTTPException(400, "période inconnue")
417 419 dash = kastats.dashboard(period, from_, to)
418 420 pdf = kapdf.GroupeKAReport(site=_SITE, dashboard=dash, mode=mode).build()
419 − fname = kapdf.filename("resto-ka", period)
421 + fname = kapdf.filename("resto-ka", period, mode)
420 422 return Response(content=pdf, media_type="application/pdf",
421 423 headers={"Content-Disposition":
422 424 f'attachment; filename="{fname}"'})
423 425