Stats v2 : /stats ultra complet (module commun Groupe KA v2) + 5 rapports PDF
- kit vendorisé mis au niveau v2 canonique (kacharts.tsx, kapdf.py, SPEC.md) - statsdash : 10 KPI avec sparklines + deltas honnêtes, 6 jauges de complétude, 4 séries quotidiennes (inventaire/nouveaux/retraits/prix), multi-courbes prix moyen top 4 marques, empilées nouveaux par source, 6 répartitions avec deltas (marques, carburant, vendeurs, boîte, carrosserie, année), distributions prix (5 000 $) et km (25 000 km), géo, heatmap calendrier + horaire 7×24, 5 tableaux (marques, modèles, villes, concessionnaires, sources & fraîcheur), 8-9 records — cache 5 min - /api/stats/report : 5 modes (complet, synthese, tendances, repartitions, donnees ; inconnu → complet), filename(platform, period, mode) - page /stats : jauges, VBar, multi-courbes, empilées, histogrammes, StatSummary, heatmap horaire, menu PdfButton 5 rapports Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
7 changed files +1,759 −337
modified
autoka/kapdf.py
+388 −70
@@ -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,8 +67,8 @@ def _fr(n) -> str: | ||
| 52 | 67 | _SUBST = { |
| 53 | 68 | "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-", |
| 54 | 69 | "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"', |
| 55 | − "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", | |
| 56 | − "≤": "<=", "≥": ">=", | |
| 70 | + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", | |
| 71 | + "×": "x", "·": ".", "σ": "sigma", "Δ": "delta", | |
| 57 | 72 | } |
| 58 | 73 | |
| 59 | 74 | |
@@ -96,6 +111,8 @@ class _PDF(FPDF): | ||
| 96 | 111 | self.set_y(20) |
| 97 | 112 | |
| 98 | 113 | def footer(self): |
| 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) | |
| 99 | 116 | if self.cover_mode or self.page_no() == 1: |
| 100 | 117 | return |
| 101 | 118 | self.set_y(-15) |
@@ -113,7 +130,7 @@ class GroupeKAReport: | ||
| 113 | 130 | def __init__(self, site: dict, dashboard: dict, mode: str = "complet"): |
| 114 | 131 | self.site = site |
| 115 | 132 | self.d = dashboard |
| 116 | − self.mode = mode | |
| 133 | + self.mode = mode if mode in REPORT_MODES else "complet" | |
| 117 | 134 | self.accent = _hex(site.get("accent", "#d9f26b")) |
| 118 | 135 | period = dashboard.get("period", {}) or {} |
| 119 | 136 | self.period_label = period.get("label") or "toute la période" |
@@ -128,6 +145,11 @@ class GroupeKAReport: | ||
| 128 | 145 | p.set_fill_color(*fill) |
| 129 | 146 | p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2) |
| 130 | 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 | + | |
| 131 | 153 | def _kicker(self, text): |
| 132 | 154 | p = self.pdf |
| 133 | 155 | p.set_font("helvetica", "B", 8) |
@@ -151,6 +173,14 @@ class GroupeKAReport: | ||
| 151 | 173 | self.toc.append((title, self.pdf.page_no())) |
| 152 | 174 | self.pdf.ln(11) |
| 153 | 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 | + | |
| 154 | 184 | # ---------- pages ---------- |
| 155 | 185 | def _cover(self): |
| 156 | 186 | p = self.pdf |
@@ -162,12 +192,10 @@ class GroupeKAReport: | ||
| 162 | 192 | p.set_draw_color(*INK) |
| 163 | 193 | p.set_line_width(1.0) |
| 164 | 194 | p.rect(10, 10, 190, 277) |
| 165 | − # kicker | |
| 166 | 195 | p.set_font("helvetica", "B", 10) |
| 167 | 196 | p.set_text_color(*GREEN) |
| 168 | 197 | p.set_xy(24, 34) |
| 169 | 198 | p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE") |
| 170 | − # wordmark : partie gauche + boîte encre/accent | |
| 171 | 199 | wm = self.site.get("wordmark", "") |
| 172 | 200 | left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None) |
| 173 | 201 | p.set_xy(24, 70) |
@@ -185,7 +213,7 @@ class GroupeKAReport: | ||
| 185 | 213 | p.set_xy(24, 100) |
| 186 | 214 | p.set_font("helvetica", "", 13) |
| 187 | 215 | p.set_text_color(*INK2) |
| 188 | − p.multi_cell(150, 7, f"Rapport statistique — {wm}") | |
| 216 | + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}") | |
| 189 | 217 | now = datetime.now(ZoneInfo("America/Toronto")) |
| 190 | 218 | per = self.d.get("period", {}) or {} |
| 191 | 219 | p.set_xy(24, 125) |
@@ -194,7 +222,7 @@ class GroupeKAReport: | ||
| 194 | 222 | ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")), |
| 195 | 223 | ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"), |
| 196 | 224 | ("Plateforme", "https://" + self.site.get("domain", "")), |
| 197 | − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"), | |
| 225 | + ("Type de rapport", REPORT_MODES[self.mode]), | |
| 198 | 226 | ] |
| 199 | 227 | y = 128 |
| 200 | 228 | for k, v in rows: |
@@ -206,7 +234,6 @@ class GroupeKAReport: | ||
| 206 | 234 | p.cell(0, 6, str(v)) |
| 207 | 235 | p.set_font("helvetica", "", 10.5) |
| 208 | 236 | y += 8 |
| 209 | − # bande encre au pied | |
| 210 | 237 | p.set_fill_color(*INK) |
| 211 | 238 | p.rect(10, 262, 190, 25, style="F") |
| 212 | 239 | p.set_xy(24, 270) |
@@ -231,7 +258,7 @@ class GroupeKAReport: | ||
| 231 | 258 | p = self.pdf |
| 232 | 259 | cols, gw, gh, gap = 3, 56, 26, 3 |
| 233 | 260 | x0, y = p.l_margin, p.get_y() |
| 234 | − for i, k in enumerate(kpis[:9]): | |
| 261 | + for i, k in enumerate(kpis[:12]): | |
| 235 | 262 | x = x0 + (i % cols) * (gw + gap) |
| 236 | 263 | if i and i % cols == 0: |
| 237 | 264 | y += gh + gap |
@@ -253,20 +280,81 @@ class GroupeKAReport: | ||
| 253 | 280 | p.set_font("helvetica", "B", 8) |
| 254 | 281 | p.set_text_color(*(GREEN if up else DANGER)) |
| 255 | 282 | arrow = "+" if k["delta_pct"] >= 0 else "" |
| 256 | − 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.") | |
| 257 | 286 | p.set_y(y + gh + 8) |
| 258 | 287 | |
| 259 | − 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): | |
| 260 | 348 | p = self.pdf |
| 261 | 349 | pts = s.get("points") or [] |
| 262 | 350 | if len(pts) < 2: |
| 263 | 351 | return |
| 352 | + if s.get("kind") == "bar": | |
| 353 | + self._vbars(s) | |
| 354 | + return | |
| 264 | 355 | if p.get_y() > 200: |
| 265 | 356 | p.add_page() |
| 266 | − p.set_font("helvetica", "B", 10) | |
| 267 | − p.set_text_color(*INK) | |
| 268 | − p.cell(0, 6, s.get("title", "")) | |
| 269 | − p.ln(7) | |
| 357 | + self._chart_title(s.get("title", "")) | |
| 270 | 358 | x0, y0, w, h = p.l_margin, p.get_y(), 174, 52 |
| 271 | 359 | self._card(x0, y0, w, h, fill=WHITE) |
| 272 | 360 | cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16 |
@@ -274,7 +362,6 @@ class GroupeKAReport: | ||
| 274 | 362 | vmax = max(vals) or 1 |
| 275 | 363 | vmin = min(0, min(vals)) |
| 276 | 364 | rng = (vmax - vmin) or 1 |
| 277 | − # grille + graduations | |
| 278 | 365 | p.set_font("helvetica", "", 6.3) |
| 279 | 366 | p.set_text_color(*INK3) |
| 280 | 367 | p.set_draw_color(200, 200, 195) |
@@ -285,6 +372,20 @@ class GroupeKAReport: | ||
| 285 | 372 | p.set_xy(x0 + 1, gy - 1.6) |
| 286 | 373 | p.cell(10, 3, _fr(vmin + rng * g / 4), align="R") |
| 287 | 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 | + | |
| 288 | 389 | def draw(series, color, width, dash=None): |
| 289 | 390 | n = len(series) |
| 290 | 391 | p.set_draw_color(*color) |
@@ -293,8 +394,7 @@ class GroupeKAReport: | ||
| 293 | 394 | p.set_dash_pattern(dash=1.2, gap=1.2) |
| 294 | 395 | last = None |
| 295 | 396 | for i, pt in enumerate(series): |
| 296 | − px = cx + cw * (i / (n - 1)) | |
| 297 | − py = cy + ch - ch * ((pt["v"] - vmin) / rng) | |
| 397 | + px, py = xy(i, n, pt["v"]) | |
| 298 | 398 | if last: |
| 299 | 399 | p.line(last[0], last[1], px, py) |
| 300 | 400 | last = (px, py) |
@@ -303,7 +403,6 @@ class GroupeKAReport: | ||
| 303 | 403 | if s.get("compare"): |
| 304 | 404 | draw(s["compare"], INK3, 0.35, dash=True) |
| 305 | 405 | draw(pts, self.accent, 0.7) |
| 306 | − # libellés d'axe X (premier / milieu / dernier) | |
| 307 | 406 | p.set_text_color(*INK3) |
| 308 | 407 | for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)): |
| 309 | 408 | p.set_xy(cx + cw * frac - 9, cy + ch + 1.5) |
@@ -313,9 +412,166 @@ class GroupeKAReport: | ||
| 313 | 412 | p.set_font("helvetica", "", 6.8) |
| 314 | 413 | p.set_text_color(*INK3) |
| 315 | 414 | p.cell(0, 4, "— période courante (accent) · ---- période comparée") |
| 316 | − p.ln(6) | |
| 317 | − else: | |
| 318 | − 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) | |
| 319 | 575 | |
| 320 | 576 | def _bars(self, title, items, unit=""): |
| 321 | 577 | p = self.pdf |
@@ -325,10 +581,8 @@ class GroupeKAReport: | ||
| 325 | 581 | need = 10 + len(items) * 7 |
| 326 | 582 | if p.get_y() + need > 265: |
| 327 | 583 | p.add_page() |
| 328 | − p.set_font("helvetica", "B", 10) | |
| 329 | − p.set_text_color(*INK) | |
| 330 | − p.cell(0, 6, title) | |
| 331 | − p.ln(8) | |
| 584 | + self._chart_title(title) | |
| 585 | + p.ln(1) | |
| 332 | 586 | vmax = max(it["value"] for it in items) or 1 |
| 333 | 587 | for it in items: |
| 334 | 588 | y = p.get_y() |
@@ -336,19 +590,23 @@ class GroupeKAReport: | ||
| 336 | 590 | p.set_text_color(*INK) |
| 337 | 591 | p.set_x(p.l_margin) |
| 338 | 592 | p.cell(46, 5, str(it["label"])[:34]) |
| 339 | − bw = 96 * (it["value"] / vmax) | |
| 593 | + bw = 86 * (it["value"] / vmax) | |
| 340 | 594 | p.set_fill_color(*self.accent) |
| 341 | 595 | p.set_draw_color(*INK) |
| 342 | 596 | p.set_line_width(0.25) |
| 343 | 597 | p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF") |
| 344 | − p.set_xy(p.l_margin + 148, y) | |
| 598 | + p.set_xy(p.l_margin + 136, y) | |
| 345 | 599 | p.set_font("helvetica", "B", 7.6) |
| 346 | − 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") | |
| 347 | 606 | p.ln(6.4) |
| 348 | 607 | p.ln(3) |
| 349 | 608 | |
| 350 | 609 | def _donut(self, b): |
| 351 | − # anneau vectoriel simple (arcs) + légende | |
| 352 | 610 | p = self.pdf |
| 353 | 611 | items = [it for it in (b.get("items") or []) if it.get("value")][:8] |
| 354 | 612 | total = sum(it["value"] for it in items) |
@@ -356,17 +614,13 @@ class GroupeKAReport: | ||
| 356 | 614 | return |
| 357 | 615 | if p.get_y() > 210: |
| 358 | 616 | p.add_page() |
| 359 | − p.set_font("helvetica", "B", 10) | |
| 360 | − p.set_text_color(*INK) | |
| 361 | − p.cell(0, 6, b.get("title", "")) | |
| 362 | − p.ln(8) | |
| 617 | + self._chart_title(b.get("title", "")) | |
| 618 | + p.ln(1) | |
| 363 | 619 | cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20 |
| 364 | − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10] | |
| 365 | 620 | start = -90.0 |
| 366 | 621 | for i, it in enumerate(items): |
| 367 | 622 | frac = it["value"] / total |
| 368 | − f = shades[i % len(shades)] | |
| 369 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 623 | + col = self._shade(i) | |
| 370 | 624 | steps = max(2, int(72 * frac)) |
| 371 | 625 | p.set_fill_color(*col) |
| 372 | 626 | p.set_draw_color(*col) |
@@ -385,11 +639,9 @@ class GroupeKAReport: | ||
| 385 | 639 | p.set_line_width(0.4) |
| 386 | 640 | p.ellipse(cx - 11, cy - 11, 22, 22, style="DF") |
| 387 | 641 | p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D") |
| 388 | − # légende | |
| 389 | 642 | ly = cy - 22 |
| 390 | 643 | for i, it in enumerate(items): |
| 391 | − f = shades[i % len(shades)] | |
| 392 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 644 | + col = self._shade(i) | |
| 393 | 645 | p.set_fill_color(*col) |
| 394 | 646 | p.set_draw_color(*INK) |
| 395 | 647 | p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF") |
@@ -401,7 +653,39 @@ class GroupeKAReport: | ||
| 401 | 653 | ly += 5.6 |
| 402 | 654 | p.set_y(max(cy + r, ly) + 6) |
| 403 | 655 | |
| 404 | − 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): | |
| 405 | 689 | p = self.pdf |
| 406 | 690 | cols = t.get("columns") or [] |
| 407 | 691 | rows = t.get("rows") or [] |
@@ -418,7 +702,7 @@ class GroupeKAReport: | ||
| 418 | 702 | p.ln(6) |
| 419 | 703 | head() |
| 420 | 704 | p.set_text_color(*INK) |
| 421 | − for i, row in enumerate(rows[:200]): | |
| 705 | + for i, row in enumerate(rows[:max_rows]): | |
| 422 | 706 | if p.get_y() > 262: |
| 423 | 707 | p.add_page() |
| 424 | 708 | head() |
@@ -429,10 +713,10 @@ class GroupeKAReport: | ||
| 429 | 713 | txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell) |
| 430 | 714 | p.cell(w, 5.4, " " + txt[:34], fill=True) |
| 431 | 715 | p.ln(5.4) |
| 432 | − if len(rows) > 200: | |
| 716 | + if len(rows) > max_rows: | |
| 433 | 717 | p.set_font("helvetica", "", 7) |
| 434 | 718 | p.set_text_color(*INK3) |
| 435 | − 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") | |
| 436 | 720 | p.ln(6) |
| 437 | 721 | |
| 438 | 722 | def _records(self): |
@@ -441,7 +725,7 @@ class GroupeKAReport: | ||
| 441 | 725 | return |
| 442 | 726 | self._section_title("Records & faits marquants") |
| 443 | 727 | p = self.pdf |
| 444 | − for r in recs[:10]: | |
| 728 | + for r in recs[:14]: | |
| 445 | 729 | if p.get_y() > 258: |
| 446 | 730 | p.add_page() |
| 447 | 731 | y = p.get_y() |
@@ -499,43 +783,76 @@ class GroupeKAReport: | ||
| 499 | 783 | "groupe-ka.com/conditions · /confidentialite · /loi-25.", |
| 500 | 784 | ) |
| 501 | 785 | |
| 502 | − def _toc_page(self): | |
| 503 | − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en | |
| 504 | − # page 2 en réservant la page lors du build (voir build()). | |
| 505 | − 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() | |
| 506 | 807 | |
| 507 | 808 | def build(self) -> bytes: |
| 508 | 809 | p = self.pdf |
| 509 | 810 | p.alias_nb_pages() |
| 510 | 811 | self._cover() |
| 812 | + with_toc = self.mode in ("complet", "donnees") | |
| 813 | + toc_page_no = None | |
| 511 | 814 | if self.mode == "synthese": |
| 512 | 815 | p.add_page() |
| 513 | 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) | |
| 514 | 825 | self._records() |
| 515 | 826 | self._final_page() |
| 516 | − 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 | |
| 517 | 839 | p.add_page() |
| 518 | 840 | toc_page_no = p.page_no() |
| 519 | 841 | p.add_page() |
| 520 | 842 | self._kpis() |
| 521 | − for s in self.d.get("series") or []: | |
| 522 | − if s.get("kind") == "bar": | |
| 523 | − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", "")) | |
| 524 | − else: | |
| 525 | − self._line_chart(s) | |
| 526 | − for b in self.d.get("breakdowns") or []: | |
| 527 | − if b.get("kind") == "donut": | |
| 528 | − self._donut(b) | |
| 529 | − else: | |
| 530 | − self._bars(b.get("title", ""), b.get("items")) | |
| 531 | − geo = self.d.get("geo") | |
| 532 | − if geo: | |
| 533 | − 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() | |
| 534 | 850 | for t in self.d.get("tables") or []: |
| 535 | 851 | self._table(t) |
| 536 | 852 | self._records() |
| 537 | 853 | self._final_page() |
| 538 | − # 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: | |
| 539 | 856 | last_page = p.page |
| 540 | 857 | p.page = toc_page_no |
| 541 | 858 | p.set_y(22) |
@@ -554,6 +871,7 @@ class GroupeKAReport: | ||
| 554 | 871 | return bytes(p.output()) |
| 555 | 872 | |
| 556 | 873 | |
| 557 | −def filename(platform_id: str, period: str) -> str: | |
| 874 | +def filename(platform_id: str, period: str, mode: str = "complet") -> str: | |
| 558 | 875 | today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d") |
| 559 | − 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
autoka/statsdash.py
+397 −75
@@ -2,25 +2,29 @@ | ||
| 2 | 2 | # Auto-Ka — Agrégateur de voitures usagées à vendre (province de Québec) |
| 3 | 3 | # Auteur : Simon-Pierre Boucher — contact@spboucher.ai |
| 4 | 4 | # statsdash.py : tableau de bord analytique — construit le JSON du contrat |
| 5 | −# commun Groupe KA (/api/stats/dashboard, voir ka/stats/SPEC.md) | |
| 6 | −# à partir des données réelles (vehicles, price_log). Sert aussi | |
| 7 | −# de source unique au rapport PDF (autoka/kapdf.py). | |
| 5 | +# commun Groupe KA v2 (/api/stats/dashboard, voir ka/stats/SPEC.md) | |
| 6 | +# à partir des données réelles (vehicles, price_log, sync_log). | |
| 7 | +# Sert aussi de source unique aux 5 rapports PDF (autoka/kapdf.py). | |
| 8 | 8 | # |
| 9 | 9 | # Principes : |
| 10 | −# - AUCUNE statistique inventée : tout vient de la base SQLite. | |
| 10 | +# - AUCUNE statistique inventée : tout vient de la base SQLite. Un champ sans | |
| 11 | +# donnée mesurable est simplement omis (le front affiche « Pas encore | |
| 12 | +# mesuré »). | |
| 11 | 13 | # - L'« inventaire à la date t » est reconstruit depuis le cycle de vie réel |
| 12 | 14 | # des annonces : first_seen (arrivée) et updated_at des annonces |
| 13 | −# désactivées (retrait). Les prix historiques par jour utilisent le | |
| 14 | −# dernier prix connu de chaque véhicule (approximation documentée). | |
| 15 | +# désactivées (retrait). Les prix/km historiques par jour utilisent le | |
| 16 | +# dernier prix/km connu de chaque véhicule (approximation documentée). | |
| 15 | 17 | # - Les séries sont bornées au début réel des données (12 août 2026) : |
| 16 | −# avant, rien n'était mesuré — on ne trace pas de faux zéros. | |
| 18 | +# avant, rien n'était mesuré — on ne trace pas de faux zéros. De même, | |
| 19 | +# les deltas vs période précédente ne sont émis que si la référence | |
| 20 | +# existait déjà (start > début des données). | |
| 17 | 21 | # - Cache serveur de 5 minutes par période. |
| 18 | 22 | # ----------------------------------------------------------------------------- |
| 19 | 23 | from __future__ import annotations |
| 20 | 24 | |
| 21 | 25 | import threading |
| 22 | 26 | import time |
| 23 | −from collections import Counter | |
| 27 | +from collections import Counter, defaultdict | |
| 24 | 28 | from datetime import date, datetime, timedelta |
| 25 | 29 | from zoneinfo import ZoneInfo |
| 26 | 30 | |
@@ -44,6 +48,10 @@ PERIOD_LABELS = { | ||
| 44 | 48 | } |
| 45 | 49 | PERIOD_DAYS = {"auj": 1, "7j": 7, "30j": 30, "3m": 90, "6m": 180, "12m": 365} |
| 46 | 50 | |
| 51 | +# Filtre « type de vendeur » : les annonces de particuliers (Kijiji) portent | |
| 52 | +# un dealer_name « Particulier (…) » — tout le reste vient de commerces. | |
| 53 | +PRIV = "dealer_name LIKE 'Particulier%'" | |
| 54 | + | |
| 47 | 55 | |
| 48 | 56 | # --- utilitaires --------------------------------------------------------------- |
| 49 | 57 | |
@@ -55,16 +63,26 @@ def _to_date(ts: float) -> date: | ||
| 55 | 63 | return datetime.fromtimestamp(ts, TZ).date() |
| 56 | 64 | |
| 57 | 65 | |
| 66 | +def _fr_int(n) -> str: | |
| 67 | + return f"{int(round(n)):,}".replace(",", " ") | |
| 68 | + | |
| 69 | + | |
| 58 | 70 | def _fr_money(p) -> str: |
| 59 | 71 | if p is None: |
| 60 | 72 | return "—" |
| 61 | − return f"{int(round(p)):,}".replace(",", " ") + " $" | |
| 73 | + return _fr_int(p) + " $" | |
| 62 | 74 | |
| 63 | 75 | |
| 64 | 76 | def _fr_km(k) -> str: |
| 65 | 77 | if k is None: |
| 66 | 78 | return "—" |
| 67 | − return f"{int(round(k)):,}".replace(",", " ") + " km" | |
| 79 | + return _fr_int(k) + " km" | |
| 80 | + | |
| 81 | + | |
| 82 | +def _fr_pct(p) -> str: | |
| 83 | + if p is None: | |
| 84 | + return "—" | |
| 85 | + return ("+" if p >= 0 else "−") + f"{abs(p):.1f}".replace(".", ",") + " %" | |
| 68 | 86 | |
| 69 | 87 | |
| 70 | 88 | def _delta(cur, prev) -> tuple[float | None, str | None]: |
@@ -110,18 +128,20 @@ def _resolve_period(period: str, from_: str | None, to: str | None): | ||
| 110 | 128 | |
| 111 | 129 | # --- reconstruction de l'inventaire par jour ------------------------------------ |
| 112 | 130 | |
| 113 | −def _lifecycle_rows(con) -> list[tuple[float, float | None, float | None]]: | |
| 114 | − """(arrivée, retrait|None, prix courant|None) pour chaque annonce auto.""" | |
| 131 | +def _lifecycle_rows(con): | |
| 132 | + """(arrivée, retrait|None, prix, km, marque) pour chaque annonce auto.""" | |
| 115 | 133 | return [ |
| 116 | − (r["first_seen"], r["updated_at"] if not r["active"] else None, r["price"]) | |
| 134 | + (r["first_seen"], r["updated_at"] if not r["active"] else None, | |
| 135 | + r["price"], r["mileage_km"], r["make"]) | |
| 117 | 136 | for r in con.execute( |
| 118 | − "SELECT first_seen, active, updated_at, price FROM vehicles" | |
| 119 | − " WHERE kind='auto' AND first_seen IS NOT NULL") | |
| 137 | + "SELECT first_seen, active, updated_at, price, mileage_km, make" | |
| 138 | + " FROM vehicles WHERE kind='auto' AND first_seen IS NOT NULL") | |
| 120 | 139 | ] |
| 121 | 140 | |
| 122 | 141 | |
| 123 | 142 | def _daily_series(rows, start_ts: float, end_ts: float): |
| 124 | − """Par jour : inventaire actif, prix moyen de l'inventaire, nouveautés. | |
| 143 | + """Par jour : inventaire actif, prix/km moyens de l'inventaire, arrivées, | |
| 144 | + retraits. | |
| 125 | 145 | |
| 126 | 146 | Balayage d'événements (arrivées/retraits triés) — l'inventaire au soir du |
| 127 | 147 | jour J = annonces arrivées avant la fin de J et pas encore retirées. |
@@ -136,8 +156,9 @@ def _daily_series(rows, start_ts: float, end_ts: float): | ||
| 136 | 156 | adds = sorted(rows, key=lambda r: r[0]) |
| 137 | 157 | rems = sorted((r for r in rows if r[1] is not None), key=lambda r: r[1]) |
| 138 | 158 | new_by_day = Counter(_to_date(r[0]) for r in rows) |
| 139 | − ai = ri = count = n_price = 0 | |
| 140 | − sum_price = 0.0 | |
| 159 | + gone_by_day = Counter(_to_date(r[1]) for r in rows if r[1] is not None) | |
| 160 | + ai = ri = count = n_price = n_km = 0 | |
| 161 | + sum_price = sum_km = 0.0 | |
| 141 | 162 | out = [] |
| 142 | 163 | while d <= d_end: |
| 143 | 164 | cutoff = _day_start(d + timedelta(days=1)) |
@@ -146,18 +167,26 @@ def _daily_series(rows, start_ts: float, end_ts: float): | ||
| 146 | 167 | if adds[ai][2] is not None: |
| 147 | 168 | sum_price += adds[ai][2] |
| 148 | 169 | n_price += 1 |
| 170 | + if adds[ai][3] is not None: | |
| 171 | + sum_km += adds[ai][3] | |
| 172 | + n_km += 1 | |
| 149 | 173 | ai += 1 |
| 150 | 174 | while ri < len(rems) and rems[ri][1] < cutoff: |
| 151 | 175 | count -= 1 |
| 152 | 176 | if rems[ri][2] is not None: |
| 153 | 177 | sum_price -= rems[ri][2] |
| 154 | 178 | n_price -= 1 |
| 179 | + if rems[ri][3] is not None: | |
| 180 | + sum_km -= rems[ri][3] | |
| 181 | + n_km -= 1 | |
| 155 | 182 | ri += 1 |
| 156 | 183 | out.append({ |
| 157 | 184 | "t": d.isoformat(), |
| 158 | 185 | "inv": count, |
| 159 | 186 | "avg_price": round(sum_price / n_price) if n_price else None, |
| 187 | + "avg_km": round(sum_km / n_km) if n_km else None, | |
| 160 | 188 | "new": new_by_day.get(d, 0), |
| 189 | + "gone": gone_by_day.get(d, 0), | |
| 161 | 190 | }) |
| 162 | 191 | d += timedelta(days=1) |
| 163 | 192 | return out |
@@ -167,9 +196,33 @@ def _snapshot(con, t: float): | ||
| 167 | 196 | """Indicateurs de l'inventaire actif reconstitué à l'instant t.""" |
| 168 | 197 | return dict(con.execute( |
| 169 | 198 | """SELECT COUNT(*) n, AVG(price) avg_price, AVG(mileage_km) avg_km, |
| 170 | − AVG(year) avg_year, COUNT(DISTINCT dealer_name) dealers | |
| 199 | + AVG(year) avg_year, | |
| 200 | + COUNT(DISTINCT CASE WHEN NOT {priv} THEN dealer_name END) dealers, | |
| 201 | + SUM(CASE WHEN {priv} THEN 1 ELSE 0 END) private, | |
| 202 | + COUNT(DISTINCT source) sources | |
| 171 | 203 | FROM vehicles WHERE kind='auto' AND first_seen<=? |
| 172 | − AND (active=1 OR updated_at>?)""", (t, t)).fetchone()) | |
| 204 | + AND (active=1 OR updated_at>?)""".format(priv=PRIV), | |
| 205 | + (t, t)).fetchone()) | |
| 206 | + | |
| 207 | + | |
| 208 | +def _snapshot_counts(con, t: float, expr: str) -> dict[str, int]: | |
| 209 | + """Effectifs par catégorie de l'inventaire reconstitué à l'instant t.""" | |
| 210 | + return {r["lab"]: r["n"] for r in con.execute( | |
| 211 | + f"""SELECT {expr} lab, COUNT(*) n FROM vehicles | |
| 212 | + WHERE kind='auto' AND first_seen<=? AND (active=1 OR updated_at>?) | |
| 213 | + GROUP BY lab""", (t, t))} | |
| 214 | + | |
| 215 | + | |
| 216 | +def _price_drops(con, t0: float, t1: float) -> int: | |
| 217 | + """Baisses de prix observées dans price_log entre t0 et t1.""" | |
| 218 | + return con.execute( | |
| 219 | + """WITH pl AS ( | |
| 220 | + SELECT uid, ts, price, | |
| 221 | + LAG(price) OVER (PARTITION BY uid ORDER BY ts) prev_price | |
| 222 | + FROM price_log WHERE price IS NOT NULL) | |
| 223 | + SELECT COUNT(*) n FROM pl | |
| 224 | + WHERE ts>=? AND ts<? AND prev_price IS NOT NULL | |
| 225 | + AND prev_price > price""", (t0, t1)).fetchone()["n"] | |
| 173 | 226 | |
| 174 | 227 | |
| 175 | 228 | # --- construction du dashboard --------------------------------------------------- |
@@ -185,11 +238,12 @@ def _build(period: str, from_: str | None, to: str | None) -> dict: | ||
| 185 | 238 | # l'inventaire de référence n'existait pas encore (rien d'inventé). |
| 186 | 239 | data_start = con.execute( |
| 187 | 240 | "SELECT MIN(first_seen) m FROM vehicles WHERE kind='auto'").fetchone()["m"] |
| 188 | − if data_start is not None and start > data_start: | |
| 241 | + has_ref = data_start is not None and start > data_start | |
| 242 | + if has_ref: | |
| 189 | 243 | ref = _snapshot(con, start) |
| 190 | 244 | else: |
| 191 | − ref = {"n": None, "avg_price": None, "avg_km": None, | |
| 192 | − "avg_year": None, "dealers": None} | |
| 245 | + ref = {"n": None, "avg_price": None, "avg_km": None, "avg_year": None, | |
| 246 | + "dealers": None, "private": None, "sources": None} | |
| 193 | 247 | |
| 194 | 248 | def _count(sql, args): |
| 195 | 249 | return con.execute(sql, args).fetchone()["n"] |
@@ -202,37 +256,83 @@ def _build(period: str, from_: str | None, to: str | None) -> dict: | ||
| 202 | 256 | " AND active=0 AND updated_at>=? AND updated_at<?", (start, end)) |
| 203 | 257 | gone_prev = _count("SELECT COUNT(*) n FROM vehicles WHERE kind='auto'" |
| 204 | 258 | " AND active=0 AND updated_at>=? AND updated_at<?", (pstart, pend)) |
| 259 | + drops_cur = _price_drops(con, start, end) | |
| 260 | + drops_prev = _price_drops(con, pstart, pend) if has_ref else None | |
| 261 | + | |
| 262 | + # --- séries quotidiennes (avant les KPI : sparklines) ----------------------- | |
| 263 | + rows = _lifecycle_rows(con) | |
| 264 | + daily = _daily_series(rows, start, end) | |
| 265 | + prev_daily = _daily_series(rows, pstart, pend) | |
| 266 | + full_prev = len(prev_daily) == len(daily) and len(daily) > 1 | |
| 267 | + | |
| 268 | + def _spark(key): | |
| 269 | + pts = [{"t": p["t"], "v": p[key]} for p in daily if p[key] is not None] | |
| 270 | + return pts if len(pts) >= 2 else None | |
| 205 | 271 | |
| 206 | − def _kpi(id_, label_, value, unit="", prev=None): | |
| 272 | + def _kpi(id_, label_, value, unit="", prev=None, spark=None): | |
| 207 | 273 | pct, direction = _delta(value, prev) |
| 208 | − return {"id": id_, "label": label_, "value": value, "unit": unit, | |
| 209 | − "delta_pct": pct, "direction": direction} | |
| 274 | + k = {"id": id_, "label": label_, "value": value, "unit": unit, | |
| 275 | + "delta_pct": pct, "direction": direction} | |
| 276 | + if spark: | |
| 277 | + k["spark"] = spark | |
| 278 | + return k | |
| 210 | 279 | |
| 211 | 280 | kpis = [ |
| 212 | − _kpi("actifs", "Véhicules actifs", cur["n"], "", ref["n"]), | |
| 213 | − _kpi("nouveaux", "Nouveaux véhicules (période)", new_cur, "", new_prev), | |
| 214 | − _kpi("retires", "Vendus / retirés (période)", gone_cur, "", gone_prev), | |
| 281 | + _kpi("actifs", "Véhicules actifs", cur["n"], "", ref["n"], _spark("inv")), | |
| 282 | + _kpi("nouveaux", "Nouveaux véhicules (période)", new_cur, "", | |
| 283 | + new_prev if has_ref else None, _spark("new")), | |
| 284 | + _kpi("retires", "Vendus / retirés (période)", gone_cur, "", | |
| 285 | + gone_prev if has_ref else None, _spark("gone")), | |
| 215 | 286 | _kpi("prix", "Prix moyen (inventaire actif)", |
| 216 | 287 | round(cur["avg_price"]) if cur["avg_price"] else None, "$", |
| 217 | − round(ref["avg_price"]) if ref["avg_price"] else None), | |
| 288 | + round(ref["avg_price"]) if ref["avg_price"] else None, | |
| 289 | + _spark("avg_price")), | |
| 218 | 290 | _kpi("km", "Km moyen (inventaire actif)", |
| 219 | 291 | round(cur["avg_km"]) if cur["avg_km"] else None, "km", |
| 220 | − round(ref["avg_km"]) if ref["avg_km"] else None), | |
| 292 | + round(ref["avg_km"]) if ref["avg_km"] else None, _spark("avg_km")), | |
| 221 | 293 | # année moyenne : valeur pré-formatée (« 2021,1 » — pas de séparateur |
| 222 | 294 | # de milliers) ; un delta en % n'aurait aucun sens sur un millésime. |
| 223 | 295 | _kpi("annee", "Année-modèle moyenne", |
| 224 | 296 | f"{cur['avg_year']:.1f}".replace(".", ",") |
| 225 | 297 | if cur["avg_year"] else None, ""), |
| 226 | 298 | _kpi("dealers", "Concessionnaires actifs", cur["dealers"], "", ref["dealers"]), |
| 299 | + _kpi("particuliers", "Annonces de particuliers", cur["private"], "", | |
| 300 | + ref["private"]), | |
| 301 | + _kpi("baisses", "Baisses de prix (période)", drops_cur, "", drops_prev), | |
| 302 | + _kpi("sources", "Sources actives", cur["sources"], "", ref["sources"]), | |
| 227 | 303 | ] |
| 228 | 304 | kpis = [k for k in kpis if k["value"] is not None] |
| 229 | 305 | |
| 230 | − # --- séries quotidiennes --------------------------------------------------- | |
| 231 | − rows = _lifecycle_rows(con) | |
| 232 | − daily = _daily_series(rows, start, end) | |
| 233 | − prev_daily = _daily_series(rows, pstart, pend) | |
| 234 | − full_prev = len(prev_daily) == len(daily) and len(daily) > 1 | |
| 235 | − | |
| 306 | + # --- jauges : complétude des fiches de l'inventaire actif ------------------- | |
| 307 | + cov = con.execute( | |
| 308 | + """SELECT COUNT(*) n, | |
| 309 | + SUM(CASE WHEN images IS NOT NULL AND images<>'[]' | |
| 310 | + AND images<>'' THEN 1 ELSE 0 END) img, | |
| 311 | + SUM(CASE WHEN mileage_km IS NOT NULL THEN 1 ELSE 0 END) km, | |
| 312 | + SUM(CASE WHEN price IS NOT NULL THEN 1 ELSE 0 END) prix, | |
| 313 | + SUM(CASE WHEN vin<>'' THEN 1 ELSE 0 END) vin, | |
| 314 | + SUM(CASE WHEN carfax_url<>'' THEN 1 ELSE 0 END) carfax, | |
| 315 | + SUM(CASE WHEN lat IS NOT NULL THEN 1 ELSE 0 END) geo | |
| 316 | + FROM vehicles WHERE active=1 AND kind='auto'""").fetchone() | |
| 317 | + gauges = [] | |
| 318 | + if cov["n"]: | |
| 319 | + def _gauge(id_, label_, num, help_=None): | |
| 320 | + g = {"id": id_, "label": label_, | |
| 321 | + "value": round(100.0 * num / cov["n"], 1), "max": 100, "unit": "%"} | |
| 322 | + if help_: | |
| 323 | + g["help"] = help_ | |
| 324 | + return g | |
| 325 | + gauges = [ | |
| 326 | + _gauge("photos", "Fiches avec photos", cov["img"]), | |
| 327 | + _gauge("km", "Kilométrage renseigné", cov["km"]), | |
| 328 | + _gauge("prix", "Prix affiché", cov["prix"]), | |
| 329 | + _gauge("vin", "NIV (VIN) connu", cov["vin"]), | |
| 330 | + _gauge("geo", "Fiches géolocalisées", cov["geo"]), | |
| 331 | + _gauge("carfax", "Rapport Carfax lié", cov["carfax"], | |
| 332 | + "Part des annonces actives dont la source publie un lien Carfax"), | |
| 333 | + ] | |
| 334 | + | |
| 335 | + # --- séries d'évolution ------------------------------------------------------ | |
| 236 | 336 | series = [] |
| 237 | 337 | if daily: |
| 238 | 338 | series.append({ |
@@ -243,34 +343,110 @@ def _build(period: str, from_: str | None, to: str | None) -> dict: | ||
| 243 | 343 | }) |
| 244 | 344 | series.append({ |
| 245 | 345 | "id": "new", "title": "Nouveaux véhicules par jour", "unit": "véhicules", |
| 246 | − "kind": "line", "points": [{"t": p["t"], "v": p["new"]} for p in daily], | |
| 247 | − **({"compare": [{"t": p["t"], "v": p["new"]} for p in prev_daily]} | |
| 248 | − if full_prev else {}), | |
| 346 | + "kind": "bar", "points": [{"t": p["t"], "v": p["new"]} for p in daily], | |
| 347 | + }) | |
| 348 | + series.append({ | |
| 349 | + "id": "gone", "title": "Véhicules vendus / retirés par jour", | |
| 350 | + "unit": "véhicules", "kind": "bar", | |
| 351 | + "points": [{"t": p["t"], "v": p["gone"]} for p in daily], | |
| 249 | 352 | }) |
| 250 | 353 | price_pts = [{"t": p["t"], "v": p["avg_price"]} for p in daily |
| 251 | 354 | if p["avg_price"] is not None] |
| 252 | 355 | if price_pts: |
| 253 | 356 | series.append({ |
| 254 | 357 | "id": "avg_price", "title": "Prix moyen de l'inventaire par jour", |
| 255 | − "unit": "$", "kind": "line", "points": price_pts, | |
| 358 | + "unit": "$", "kind": "area", "points": price_pts, | |
| 359 | + }) | |
| 360 | + | |
| 361 | + # --- multi-courbes : prix moyen par grande marque ---------------------------- | |
| 362 | + multiseries = [] | |
| 363 | + top_makes = [r["make"] for r in con.execute( | |
| 364 | + "SELECT make FROM vehicles WHERE active=1 AND kind='auto' AND make<>''" | |
| 365 | + " GROUP BY make ORDER BY COUNT(*) DESC LIMIT 4")] | |
| 366 | + if top_makes and daily: | |
| 367 | + by_make_rows = defaultdict(list) | |
| 368 | + for r in rows: | |
| 369 | + if r[4] in top_makes: | |
| 370 | + by_make_rows[r[4]].append(r) | |
| 371 | + make_daily = {m: _daily_series(by_make_rows[m], start, end) | |
| 372 | + for m in top_makes} | |
| 373 | + # domaine commun : jours où chaque marque a un prix moyen mesuré | |
| 374 | + commons = None | |
| 375 | + for m in top_makes: | |
| 376 | + days_m = {p["t"] for p in make_daily[m] if p["avg_price"] is not None} | |
| 377 | + commons = days_m if commons is None else commons & days_m | |
| 378 | + commons = commons or set() | |
| 379 | + if len(commons) >= 2: | |
| 380 | + ms_series = [{ | |
| 381 | + "label": m, | |
| 382 | + "points": [{"t": p["t"], "v": p["avg_price"]} | |
| 383 | + for p in make_daily[m] if p["t"] in commons], | |
| 384 | + } for m in top_makes] | |
| 385 | + multiseries.append({ | |
| 386 | + "id": "prix_marques", | |
| 387 | + "title": "Prix moyen de l'inventaire — top 4 des marques", | |
| 388 | + "unit": "$", "series": ms_series, | |
| 256 | 389 | }) |
| 257 | 390 | |
| 258 | − # --- répartitions (inventaire actif) ---------------------------------------- | |
| 259 | − def _items(sql, args=()): | |
| 260 | − return [{"label": r[0] or "Non précisé", "value": r[1]} | |
| 261 | − for r in con.execute(sql, args).fetchall()] | |
| 262 | − | |
| 263 | − by_fuel = _items( | |
| 264 | − "SELECT CASE WHEN fuel IN ('', 'N.D.') THEN 'Non précisé' ELSE fuel END f," | |
| 265 | − " COUNT(*) FROM vehicles WHERE active=1 AND kind='auto'" | |
| 266 | − " GROUP BY f ORDER BY COUNT(*) DESC") | |
| 267 | − by_trans = _items( | |
| 268 | − "SELECT CASE WHEN transmission IN ('', 'NA', 'N.D.') THEN 'Non précisé'" | |
| 269 | − " ELSE transmission END t, COUNT(*) FROM vehicles" | |
| 270 | − " WHERE active=1 AND kind='auto' GROUP BY t ORDER BY COUNT(*) DESC LIMIT 8") | |
| 271 | − by_make = _items( | |
| 272 | − "SELECT make, COUNT(*) FROM vehicles WHERE active=1 AND kind='auto'" | |
| 273 | − " AND make<>'' GROUP BY make ORDER BY COUNT(*) DESC LIMIT 12") | |
| 391 | + # --- barres empilées : arrivées par source ------------------------------------ | |
| 392 | + stacked = [] | |
| 393 | + src_day = defaultdict(Counter) # jour -> source -> n | |
| 394 | + src_tot = Counter() | |
| 395 | + for r in con.execute( | |
| 396 | + "SELECT first_seen, source FROM vehicles WHERE kind='auto'" | |
| 397 | + " AND first_seen>=? AND first_seen<?", (start, end)): | |
| 398 | + d_ = _to_date(r["first_seen"]).isoformat() | |
| 399 | + src_day[d_][r["source"]] += 1 | |
| 400 | + src_tot[r["source"]] += 1 | |
| 401 | + if src_tot: | |
| 402 | + SRC_LABELS = {"otogo": "Otogo", "kijiji": "Kijiji", | |
| 403 | + "autotrader": "AutoTrader", "cargurus": "CarGurus", | |
| 404 | + "automobileendirect": "AutomobileEnDirect", | |
| 405 | + "hgregoire": "HGrégoire"} | |
| 406 | + tops = [s for s, _ in src_tot.most_common(4)] | |
| 407 | + keys = [SRC_LABELS.get(s, s) for s in tops] | |
| 408 | + others = len(src_tot) > len(tops) | |
| 409 | + if others: | |
| 410 | + keys.append("Autres") | |
| 411 | + pts = [] | |
| 412 | + for d_ in sorted(src_day): | |
| 413 | + vals = [src_day[d_].get(s, 0) for s in tops] | |
| 414 | + if others: | |
| 415 | + vals.append(sum(src_day[d_].values()) - sum(vals)) | |
| 416 | + pts.append({"t": d_, "values": vals}) | |
| 417 | + if len(pts) >= 2: | |
| 418 | + stacked.append({"id": "src", "title": "Nouveaux véhicules par source", | |
| 419 | + "unit": "véhicules", "keys": keys, "points": pts}) | |
| 420 | + | |
| 421 | + # --- répartitions (inventaire actif, deltas vs début de période) -------------- | |
| 422 | + FUEL_EXPR = ("CASE WHEN fuel IN ('', 'N.D.') THEN 'Non précisé'" | |
| 423 | + " ELSE fuel END") | |
| 424 | + TRANS_EXPR = ("CASE WHEN transmission IN ('', 'NA', 'N.D.')" | |
| 425 | + " THEN 'Non précisé' ELSE transmission END") | |
| 426 | + BODY_EXPR = "CASE WHEN body_type='' THEN 'Non précisé' ELSE body_type END" | |
| 427 | + SELLER_EXPR = (f"CASE WHEN {PRIV} THEN 'Particuliers'" | |
| 428 | + " ELSE 'Concessionnaires' END") | |
| 429 | + | |
| 430 | + def _items(expr, limit=None, where=""): | |
| 431 | + cur_rows = con.execute( | |
| 432 | + f"SELECT {expr} lab, COUNT(*) n FROM vehicles" | |
| 433 | + f" WHERE active=1 AND kind='auto'{where}" | |
| 434 | + f" GROUP BY lab ORDER BY n DESC" + (f" LIMIT {limit}" if limit else "") | |
| 435 | + ).fetchall() | |
| 436 | + prev_counts = _snapshot_counts(con, start, expr) if has_ref else {} | |
| 437 | + out = [] | |
| 438 | + for r in cur_rows: | |
| 439 | + pct, _ = _delta(r["n"], prev_counts.get(r["lab"])) | |
| 440 | + out.append({"label": r["lab"] or "Non précisé", "value": r["n"], | |
| 441 | + **({"delta_pct": pct} if pct is not None else {})}) | |
| 442 | + return out | |
| 443 | + | |
| 444 | + by_fuel = _items(FUEL_EXPR) | |
| 445 | + by_trans = _items(TRANS_EXPR, limit=8) | |
| 446 | + by_body = _items(BODY_EXPR, limit=10) | |
| 447 | + by_seller = _items(SELLER_EXPR) | |
| 448 | + by_make = _items("make", limit=12, where=" AND make<>''") | |
| 449 | + | |
| 274 | 450 | year_rows = con.execute( |
| 275 | 451 | "SELECT year, COUNT(*) n FROM vehicles WHERE active=1 AND kind='auto'" |
| 276 | 452 | " AND year IS NOT NULL GROUP BY year ORDER BY year").fetchall() |
@@ -287,28 +463,92 @@ def _build(period: str, from_: str | None, to: str | None) -> dict: | ||
| 287 | 463 | by_year.insert(0, {"label": f"≤ {cutoff - 1}", "value": older}) |
| 288 | 464 | |
| 289 | 465 | breakdowns = [ |
| 466 | + {"id": "make", "title": "Top 12 des marques", "kind": "donut", "items": by_make}, | |
| 290 | 467 | {"id": "fuel", "title": "Par carburant", "kind": "donut", "items": by_fuel}, |
| 468 | + {"id": "seller", "title": "Concessionnaires vs particuliers", | |
| 469 | + "kind": "donut", "items": by_seller}, | |
| 291 | 470 | {"id": "trans", "title": "Par boîte de vitesses", "kind": "bar", "items": by_trans}, |
| 292 | − {"id": "make", "title": "Top 12 des marques", "kind": "bar", "items": by_make}, | |
| 471 | + {"id": "body", "title": "Par carrosserie", "kind": "bar", "items": by_body}, | |
| 293 | 472 | {"id": "year", "title": "Par année-modèle", "kind": "bar", "items": by_year}, |
| 294 | 473 | ] |
| 295 | − breakdowns = [b for b in breakdowns if b["items"]] | |
| 296 | − | |
| 297 | − geo = {"title": "Par région", "items": _items( | |
| 298 | − "SELECT region, COUNT(*) FROM vehicles WHERE active=1 AND kind='auto'" | |
| 299 | − " AND region<>'' GROUP BY region ORDER BY COUNT(*) DESC")} | |
| 300 | − | |
| 474 | + breakdowns = [b for b in breakdowns if len(b["items"]) > 1] | |
| 475 | + | |
| 476 | + # --- distributions : prix et kilométrage -------------------------------------- | |
| 477 | + def _histo(col, width, cap, fmt): | |
| 478 | + rows_ = con.execute( | |
| 479 | + f"SELECT CAST({col}/{width} AS INTEGER) b, COUNT(*) n FROM vehicles" | |
| 480 | + f" WHERE active=1 AND kind='auto' AND {col} IS NOT NULL AND {col}>=0" | |
| 481 | + " GROUP BY b ORDER BY b").fetchall() | |
| 482 | + if not rows_: | |
| 483 | + return None | |
| 484 | + n_bins = cap // width | |
| 485 | + bins = [{"label": fmt(i), "value": 0} for i in range(n_bins)] | |
| 486 | + over = {"label": fmt(n_bins), "value": 0} | |
| 487 | + for r in rows_: | |
| 488 | + if r["b"] < n_bins: | |
| 489 | + bins[r["b"]]["value"] += r["n"] | |
| 490 | + else: | |
| 491 | + over["value"] += r["n"] | |
| 492 | + if over["value"]: | |
| 493 | + bins.append(over) | |
| 494 | + while bins and bins[0]["value"] == 0: | |
| 495 | + bins.pop(0) | |
| 496 | + return bins | |
| 497 | + | |
| 498 | + def _fmt_price_bin(i): | |
| 499 | + lo, hi = i * 5, i * 5 + 5 | |
| 500 | + return f"{lo}–{hi} k$" if hi <= 100 else "100 k$ +" | |
| 501 | + | |
| 502 | + def _fmt_km_bin(i): | |
| 503 | + lo, hi = i * 25, i * 25 + 25 | |
| 504 | + return f"{lo}–{hi} k km" if hi <= 300 else "300 k km +" | |
| 505 | + | |
| 506 | + distributions = [] | |
| 507 | + price_bins = _histo("price", 5000, 100000, _fmt_price_bin) | |
| 508 | + if price_bins: | |
| 509 | + distributions.append({ | |
| 510 | + "id": "prix", "title": "Distribution des prix (tranches de 5 000 $)", | |
| 511 | + "unit": "véhicules", "bins": price_bins}) | |
| 512 | + km_bins = _histo("mileage_km", 25000, 300000, _fmt_km_bin) | |
| 513 | + if km_bins: | |
| 514 | + distributions.append({ | |
| 515 | + "id": "km", "title": "Distribution du kilométrage (tranches de 25 000 km)", | |
| 516 | + "unit": "véhicules", "bins": km_bins}) | |
| 517 | + | |
| 518 | + # --- répartition géographique --------------------------------------------------- | |
| 519 | + geo = {"title": "Par région", "items": _items("region", where=" AND region<>''")} | |
| 520 | + | |
| 521 | + # --- calendrier + activité horaire ---------------------------------------------- | |
| 301 | 522 | heatmap = {"title": "Nouveaux véhicules par jour", |
| 302 | 523 | "cells": [{"date": p["t"], "value": p["new"]} for p in daily]} |
| 303 | 524 | |
| 525 | + hour_counter = Counter() | |
| 526 | + for r in con.execute( | |
| 527 | + "SELECT first_seen FROM vehicles WHERE kind='auto'" | |
| 528 | + " AND first_seen>=? AND first_seen<?", (start, end)): | |
| 529 | + dt = datetime.fromtimestamp(r["first_seen"], TZ) | |
| 530 | + hour_counter[(dt.weekday(), dt.hour)] += 1 | |
| 531 | + hourly = None | |
| 532 | + if hour_counter: | |
| 533 | + hourly = {"title": "Nouveaux véhicules détectés par heure (synchros)", | |
| 534 | + "cells": [{"dow": k[0], "hour": k[1], "value": v} | |
| 535 | + for k, v in sorted(hour_counter.items())]} | |
| 536 | + | |
| 304 | 537 | # --- tableaux détaillés (inventaire actif) ------------------------------------ |
| 305 | − def _table_rows(sql): | |
| 306 | − return [list(r) for r in con.execute(sql).fetchall()] | |
| 538 | + def _table_rows(sql, args=()): | |
| 539 | + return [list(r) for r in con.execute(sql, args).fetchall()] | |
| 540 | + | |
| 541 | + make_prev = _snapshot_counts(con, start, "make") if has_ref else {} | |
| 542 | + | |
| 543 | + def _mk_delta(make_, n): | |
| 544 | + pct, _ = _delta(n, make_prev.get(make_)) | |
| 545 | + return _fr_pct(pct) | |
| 307 | 546 | |
| 308 | 547 | tables = [ |
| 309 | 548 | {"id": "makes", "title": "Top marques — volume, prix et km moyens", |
| 310 | − "columns": ["Marque", "Véhicules", "Prix moyen", "Km moyen"], | |
| 311 | − "rows": [[m, n, _fr_money(p), _fr_km(k)] for m, n, p, k in _table_rows( | |
| 549 | + "columns": ["Marque", "Véhicules", "Prix moyen", "Km moyen", "Δ période"], | |
| 550 | + "rows": [[m, n, _fr_money(p), _fr_km(k), _mk_delta(m, n)] | |
| 551 | + for m, n, p, k in _table_rows( | |
| 312 | 552 | "SELECT make, COUNT(*), AVG(price), AVG(mileage_km) FROM vehicles" |
| 313 | 553 | " WHERE active=1 AND kind='auto' AND make<>''" |
| 314 | 554 | " GROUP BY make ORDER BY COUNT(*) DESC LIMIT 25")]}, |
@@ -318,21 +558,52 @@ def _build(period: str, from_: str | None, to: str | None) -> dict: | ||
| 318 | 558 | "SELECT make || ' ' || model, COUNT(*), AVG(price), AVG(mileage_km)" |
| 319 | 559 | " FROM vehicles WHERE active=1 AND kind='auto' AND make<>''" |
| 320 | 560 | " AND model<>'' GROUP BY make, model ORDER BY COUNT(*) DESC LIMIT 25")]}, |
| 561 | + {"id": "cities", "title": "Top villes — inventaire, prix et km moyens", | |
| 562 | + "columns": ["Ville", "Région", "Véhicules", "Prix moyen", "Km moyen"], | |
| 563 | + "rows": [[c, rg or "—", n, _fr_money(p), _fr_km(k)] | |
| 564 | + for c, rg, n, p, k in _table_rows( | |
| 565 | + "SELECT city, MAX(region), COUNT(*), AVG(price), AVG(mileage_km)" | |
| 566 | + " FROM vehicles WHERE active=1 AND kind='auto' AND city<>''" | |
| 567 | + " GROUP BY city ORDER BY COUNT(*) DESC LIMIT 25")]}, | |
| 321 | 568 | {"id": "dealers", "title": "Top concessionnaires — inventaire et prix moyen", |
| 322 | 569 | "columns": ["Concessionnaire", "Région", "Véhicules", "Prix moyen"], |
| 323 | 570 | "rows": [[d, rg or "—", n, _fr_money(p)] for d, rg, n, p in _table_rows( |
| 324 | 571 | "SELECT dealer_name, MAX(region), COUNT(*), AVG(price) FROM vehicles" |
| 325 | 572 | " WHERE active=1 AND kind='auto' AND dealer_name<>''" |
| 573 | + f" AND NOT {PRIV}" | |
| 326 | 574 | " GROUP BY dealer_name ORDER BY COUNT(*) DESC LIMIT 25")]}, |
| 327 | 575 | ] |
| 328 | 576 | |
| 577 | + # sources & fraîcheur : inventaire actif + arrivées de la période + dernière | |
| 578 | + # synchro réussie (sync_log = journal réel du pipeline d'ingestion) | |
| 579 | + last_sync = {r["source"]: r for r in con.execute( | |
| 580 | + """SELECT source, MAX(ts) ts, ok FROM sync_log GROUP BY source""")} | |
| 581 | + src_rows = _table_rows( | |
| 582 | + """SELECT source, COUNT(*), | |
| 583 | + SUM(CASE WHEN first_seen>=? AND first_seen<? THEN 1 ELSE 0 END) | |
| 584 | + FROM vehicles WHERE active=1 AND kind='auto' | |
| 585 | + GROUP BY source ORDER BY COUNT(*) DESC LIMIT 25""", (start, end)) | |
| 586 | + if src_rows: | |
| 587 | + rows_out = [] | |
| 588 | + for s, n, added in src_rows: | |
| 589 | + ls = last_sync.get(s) | |
| 590 | + when = (datetime.fromtimestamp(ls["ts"], TZ) | |
| 591 | + .strftime("%Y-%m-%d %H:%M") if ls else "—") | |
| 592 | + ok = ("OK" if ls and ls["ok"] else ("Erreur" if ls else "—")) | |
| 593 | + rows_out.append([s, n, added, when, ok]) | |
| 594 | + tables.append({ | |
| 595 | + "id": "sources", "title": "Sources — inventaire, ajouts et fraîcheur", | |
| 596 | + "columns": ["Source", "Véhicules actifs", "Ajouts (période)", | |
| 597 | + "Dernière synchro", "Statut"], | |
| 598 | + "rows": rows_out}) | |
| 599 | + | |
| 329 | 600 | # --- records & faits marquants ------------------------------------------------- |
| 330 | 601 | records = [] |
| 331 | 602 | if daily: |
| 332 | 603 | best = max(daily, key=lambda p: p["new"]) |
| 333 | 604 | if best["new"]: |
| 334 | 605 | records.append({"label": "Jour record d'arrivées", |
| 335 | − "value": f"{best['new']:,}".replace(",", " ") + " véhicules", | |
| 606 | + "value": _fr_int(best["new"]) + " véhicules", | |
| 336 | 607 | "date": best["t"]}) |
| 337 | 608 | fastest = con.execute( |
| 338 | 609 | """SELECT title, year, updated_at - first_seen dur, updated_at |
@@ -360,16 +631,56 @@ def _build(period: str, from_: str | None, to: str | None) -> dict: | ||
| 360 | 631 | "value": "−" + _fr_money(drop["baisse"]), |
| 361 | 632 | "date": _to_date(drop["ts"]).isoformat()}) |
| 362 | 633 | busiest = con.execute( |
| 363 | − """SELECT dealer_name, COUNT(*) n FROM vehicles | |
| 364 | − WHERE kind='auto' AND dealer_name<>'' AND first_seen>=? AND first_seen<? | |
| 365 | − GROUP BY dealer_name ORDER BY n DESC LIMIT 1""", (start, end)).fetchone() | |
| 634 | + f"""SELECT dealer_name, COUNT(*) n FROM vehicles | |
| 635 | + WHERE kind='auto' AND dealer_name<>'' AND NOT {PRIV} | |
| 636 | + AND first_seen>=? AND first_seen<? | |
| 637 | + GROUP BY dealer_name ORDER BY n DESC LIMIT 1""", | |
| 638 | + (start, end)).fetchone() | |
| 366 | 639 | if busiest and busiest["n"]: |
| 367 | 640 | records.append({"label": f"Concessionnaire le plus actif — {busiest['dealer_name']}", |
| 368 | − "value": f"{busiest['n']:,}".replace(",", " ") + " nouveautés", | |
| 641 | + "value": _fr_int(busiest["n"]) + " nouveautés", | |
| 642 | + "date": None}) | |
| 643 | + top_price = con.execute( | |
| 644 | + "SELECT title, price FROM vehicles WHERE active=1 AND kind='auto'" | |
| 645 | + " AND price IS NOT NULL ORDER BY price DESC LIMIT 1").fetchone() | |
| 646 | + if top_price: | |
| 647 | + records.append({"label": f"Véhicule le plus cher en vente — {top_price['title']}", | |
| 648 | + "value": _fr_money(top_price["price"]), "date": None}) | |
| 649 | + oldest = con.execute( | |
| 650 | + "SELECT title, year FROM vehicles WHERE active=1 AND kind='auto'" | |
| 651 | + " AND year IS NOT NULL ORDER BY year ASC LIMIT 1").fetchone() | |
| 652 | + if oldest: | |
| 653 | + records.append({"label": f"Doyen de l'inventaire — {oldest['title']}", | |
| 654 | + "value": f"année {oldest['year']}", "date": None}) | |
| 655 | + top_km = con.execute( | |
| 656 | + "SELECT title, mileage_km FROM vehicles WHERE active=1 AND kind='auto'" | |
| 657 | + " AND mileage_km IS NOT NULL ORDER BY mileage_km DESC LIMIT 1").fetchone() | |
| 658 | + if top_km: | |
| 659 | + records.append({"label": f"Odomètre le plus élevé — {top_km['title']}", | |
| 660 | + "value": _fr_km(top_km["mileage_km"]), "date": None}) | |
| 661 | + if has_ref and make_prev: | |
| 662 | + make_cur = {r["lab"]: r["n"] for r in con.execute( | |
| 663 | + "SELECT make lab, COUNT(*) n FROM vehicles WHERE active=1" | |
| 664 | + " AND kind='auto' AND make<>'' GROUP BY lab HAVING n>=100")} | |
| 665 | + gains = [(m, _delta(n, make_prev.get(m))[0]) for m, n in make_cur.items()] | |
| 666 | + gains = [(m, p) for m, p in gains if p is not None] | |
| 667 | + if gains: | |
| 668 | + m, p = max(gains, key=lambda x: x[1]) | |
| 669 | + if p > 0: | |
| 670 | + records.append({ | |
| 671 | + "label": f"Marque en plus forte hausse — {m}", | |
| 672 | + "value": _fr_pct(p) + " d'inventaire", "date": None}) | |
| 673 | + top_region = con.execute( | |
| 674 | + """SELECT region, COUNT(*) n FROM vehicles WHERE kind='auto' | |
| 675 | + AND region<>'' AND first_seen>=? AND first_seen<? | |
| 676 | + GROUP BY region ORDER BY n DESC LIMIT 1""", (start, end)).fetchone() | |
| 677 | + if top_region and top_region["n"]: | |
| 678 | + records.append({"label": f"Région la plus active — {top_region['region']}", | |
| 679 | + "value": _fr_int(top_region["n"]) + " nouveautés", | |
| 369 | 680 | "date": None}) |
| 370 | 681 | |
| 371 | 682 | con.close() |
| 372 | − return { | |
| 683 | + out = { | |
| 373 | 684 | "updated": datetime.now(TZ).isoformat(timespec="seconds"), |
| 374 | 685 | "period": {"from": f_iso, "to": t_iso, "label": label}, |
| 375 | 686 | "kpis": kpis, |
@@ -380,11 +691,22 @@ def _build(period: str, from_: str | None, to: str | None) -> dict: | ||
| 380 | 691 | "tables": tables, |
| 381 | 692 | "records": records, |
| 382 | 693 | } |
| 694 | + if gauges: | |
| 695 | + out["gauges"] = gauges | |
| 696 | + if multiseries: | |
| 697 | + out["multiseries"] = multiseries | |
| 698 | + if stacked: | |
| 699 | + out["stacked"] = stacked | |
| 700 | + if distributions: | |
| 701 | + out["distributions"] = distributions | |
| 702 | + if hourly: | |
| 703 | + out["hourly"] = hourly | |
| 704 | + return out | |
| 383 | 705 | |
| 384 | 706 | |
| 385 | 707 | def dashboard(period: str = "30j", from_: str | None = None, |
| 386 | 708 | to: str | None = None) -> dict: |
| 387 | − """Dashboard du contrat SPEC — mis en cache 5 minutes par période.""" | |
| 709 | + """Dashboard du contrat SPEC v2 — mis en cache 5 minutes par période.""" | |
| 388 | 710 | if period not in PERIOD_LABELS and not (from_ and to): |
| 389 | 711 | period = "30j" |
| 390 | 712 | key = (period, from_ or "", to or "") |
modified
autoka/web.py
+4 −3
@@ -349,19 +349,20 @@ def stats_report( | ||
| 349 | 349 | to: str | None = None, |
| 350 | 350 | mode: str = "complet", |
| 351 | 351 | ): |
| 352 | − """Rapport PDF estampillé Groupe-KA (complet ou synthèse 2 pages).""" | |
| 352 | + """Rapport PDF estampillé Groupe-KA — 5 modes (SPEC v2) : complet, | |
| 353 | + synthese, tendances, repartitions, donnees. Mode inconnu → complet.""" | |
| 353 | 354 | from fastapi.responses import Response |
| 354 | 355 | from . import kapdf, statsdash |
| 355 | 356 | try: |
| 356 | 357 | dash = statsdash.dashboard(period, from_, to) |
| 357 | 358 | except ValueError: |
| 358 | 359 | raise HTTPException(400, "Dates invalides (format attendu : YYYY-MM-DD)") |
| 359 | − mode = "synthese" if mode == "synthese" else "complet" | |
| 360 | + mode = mode if mode in kapdf.REPORT_MODES else "complet" | |
| 360 | 361 | pdf = kapdf.GroupeKAReport(site=KA_SITE, dashboard=dash, mode=mode).build() |
| 361 | 362 | return Response( |
| 362 | 363 | content=pdf, media_type="application/pdf", |
| 363 | 364 | headers={"Content-Disposition": |
| 364 | − f'attachment; filename="{kapdf.filename("auto-ka", period)}"'}) | |
| 365 | + f'attachment; filename="{kapdf.filename("auto-ka", period, mode)}"'}) | |
| 365 | 366 | |
| 366 | 367 | |
| 367 | 368 | @app.get("/api/stats/rapport.pdf") |
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
+394 −33
@@ -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); |
@@ -125,10 +181,11 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb | ||
| 125 | 181 | ); |
| 126 | 182 | })} |
| 127 | 183 | {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => ( |
| 128 | − <text key={i} x={X(i, pts.length)} y={H - 8} | |
| 129 | − textAnchor={i === 0 ? "start" : i === pts.length - 1 ? "end" : "middle"} | |
| 130 | − fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text> | |
| 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> | |
| 131 | 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 | + )} | |
| 132 | 189 | {!hide.cmp && serie.compare && serie.compare.length > 1 && ( |
| 133 | 190 | <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" /> |
| 134 | 191 | )} |
@@ -150,17 +207,211 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb | ||
| 150 | 207 | ); |
| 151 | 208 | } |
| 152 | 209 | |
| 153 | −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 }) { | |
| 154 | 211 | return ( |
| 155 | − <button type="button" onClick={onClick} aria-pressed={!off} | |
| 156 | − 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 }}> | |
| 157 | 214 | <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} /> |
| 158 | 215 | {label} |
| 159 | 216 | </button> |
| 160 | 217 | ); |
| 161 | 218 | } |
| 162 | 219 | |
| 163 | −/* ---------- 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 ---------- */ | |
| 164 | 415 | export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) { |
| 165 | 416 | const rows = (items ?? []).slice(0, 14); |
| 166 | 417 | if (!rows.length) return <EmptyBlock title={title} />; |
@@ -171,9 +422,16 @@ export function BarChart({ title, items, unit }: { title: string; items: BreakIt | ||
| 171 | 422 | <div style={{ marginTop: 12, display: "grid", gap: 9 }}> |
| 172 | 423 | {rows.map((r) => ( |
| 173 | 424 | <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}> |
| 174 | − <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}> | |
| 425 | + <div style={{ display: "flex", justifyContent: "space-between", gap: 8, fontSize: 12.5 }}> | |
| 175 | 426 | <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span> |
| 176 | − <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> | |
| 177 | 435 | </div> |
| 178 | 436 | <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}> |
| 179 | 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" }} /> |
@@ -226,6 +484,26 @@ export function Donut({ title, items }: { title: string; items: BreakItem[] }) { | ||
| 226 | 484 | ); |
| 227 | 485 | } |
| 228 | 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 | + | |
| 229 | 507 | /* ---------- Calendrier de chaleur ---------- */ |
| 230 | 508 | export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) { |
| 231 | 509 | if (!cells?.length) return <EmptyBlock title={title} />; |
@@ -263,6 +541,64 @@ export function CalendarHeatmap({ title, cells }: { title: string; cells: { date | ||
| 263 | 541 | ); |
| 264 | 542 | } |
| 265 | 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 | + | |
| 266 | 602 | /* ---------- Tableau : tri, recherche, pagination ---------- */ |
| 267 | 603 | export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) { |
| 268 | 604 | const [q, setQ] = useState(""); |
@@ -340,9 +676,19 @@ export function RecordCard({ r }: { r: RecordFact }) { | ||
| 340 | 676 | ); |
| 341 | 677 | } |
| 342 | 678 | |
| 343 | −/* ---------- Bouton PDF ---------- */ | |
| 679 | +/* ---------- Menu de rapports PDF (5 rapports) ---------- */ | |
| 344 | 680 | export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) { |
| 345 | − 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]); | |
| 346 | 692 | const url = (mode: string) => { |
| 347 | 693 | const p = new URLSearchParams({ period, mode }); |
| 348 | 694 | if (from) p.set("from", from); |
@@ -350,23 +696,38 @@ export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: | ||
| 350 | 696 | return `${endpoint}?${p}`; |
| 351 | 697 | }; |
| 352 | 698 | const dl = (mode: string) => { |
| 353 | − setBusy(true); | |
| 699 | + setBusy(mode); | |
| 700 | + setOpen(false); | |
| 354 | 701 | const a = document.createElement("a"); |
| 355 | 702 | a.href = url(mode); |
| 356 | 703 | a.download = ""; |
| 357 | 704 | document.body.appendChild(a); |
| 358 | 705 | a.click(); |
| 359 | 706 | a.remove(); |
| 360 | − setTimeout(() => setBusy(false), 2500); | |
| 707 | + setTimeout(() => setBusy(null), 3000); | |
| 361 | 708 | }; |
| 362 | 709 | return ( |
| 363 | − <span style={{ display: "inline-flex", gap: 8, flexWrap: "wrap" }}> | |
| 364 | − <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={busy}> | |
| 365 | − {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"} | |
| 366 | 713 | </button> |
| 367 | − <button type="button" className="btn btn-ghost" onClick={() => dl("synthese")} disabled={busy}> | |
| 368 | − 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 ▾ | |
| 369 | 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 | + )} | |
| 370 | 731 | </span> |
| 371 | 732 | ); |
| 372 | 733 | } |
modified
frontend/src/ka/stats/kapdf.py
+390 −72
@@ -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,8 +67,8 @@ def _fr(n) -> str: | ||
| 52 | 67 | _SUBST = { |
| 53 | 68 | "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-", |
| 54 | 69 | "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"', |
| 55 | − "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", | |
| 56 | − "≤": "<=", "≥": ">=", | |
| 70 | + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", | |
| 71 | + "×": "x", "·": ".", "σ": "sigma", "Δ": "delta", | |
| 57 | 72 | } |
| 58 | 73 | |
| 59 | 74 | |
@@ -80,7 +95,7 @@ class _PDF(FPDF): | ||
| 80 | 95 | self.set_auto_page_break(True, margin=22) |
| 81 | 96 | |
| 82 | 97 | def header(self): |
| 83 | − if self.cover_mode: | |
| 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,7 +111,9 @@ class _PDF(FPDF): | ||
| 96 | 111 | self.set_y(20) |
| 97 | 112 | |
| 98 | 113 | def footer(self): |
| 99 | − if self.cover_mode: | |
| 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: | |
| 100 | 117 | return |
| 101 | 118 | self.set_y(-15) |
| 102 | 119 | self.set_draw_color(*INK3) |
@@ -113,7 +130,7 @@ class GroupeKAReport: | ||
| 113 | 130 | def __init__(self, site: dict, dashboard: dict, mode: str = "complet"): |
| 114 | 131 | self.site = site |
| 115 | 132 | self.d = dashboard |
| 116 | − self.mode = mode | |
| 133 | + self.mode = mode if mode in REPORT_MODES else "complet" | |
| 117 | 134 | self.accent = _hex(site.get("accent", "#d9f26b")) |
| 118 | 135 | period = dashboard.get("period", {}) or {} |
| 119 | 136 | self.period_label = period.get("label") or "toute la période" |
@@ -128,6 +145,11 @@ class GroupeKAReport: | ||
| 128 | 145 | p.set_fill_color(*fill) |
| 129 | 146 | p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2) |
| 130 | 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 | + | |
| 131 | 153 | def _kicker(self, text): |
| 132 | 154 | p = self.pdf |
| 133 | 155 | p.set_font("helvetica", "B", 8) |
@@ -151,6 +173,14 @@ class GroupeKAReport: | ||
| 151 | 173 | self.toc.append((title, self.pdf.page_no())) |
| 152 | 174 | self.pdf.ln(11) |
| 153 | 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 | + | |
| 154 | 184 | # ---------- pages ---------- |
| 155 | 185 | def _cover(self): |
| 156 | 186 | p = self.pdf |
@@ -162,12 +192,10 @@ class GroupeKAReport: | ||
| 162 | 192 | p.set_draw_color(*INK) |
| 163 | 193 | p.set_line_width(1.0) |
| 164 | 194 | p.rect(10, 10, 190, 277) |
| 165 | − # kicker | |
| 166 | 195 | p.set_font("helvetica", "B", 10) |
| 167 | 196 | p.set_text_color(*GREEN) |
| 168 | 197 | p.set_xy(24, 34) |
| 169 | 198 | p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE") |
| 170 | − # wordmark : partie gauche + boîte encre/accent | |
| 171 | 199 | wm = self.site.get("wordmark", "") |
| 172 | 200 | left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None) |
| 173 | 201 | p.set_xy(24, 70) |
@@ -185,7 +213,7 @@ class GroupeKAReport: | ||
| 185 | 213 | p.set_xy(24, 100) |
| 186 | 214 | p.set_font("helvetica", "", 13) |
| 187 | 215 | p.set_text_color(*INK2) |
| 188 | − p.multi_cell(150, 7, f"Rapport statistique — {wm}") | |
| 216 | + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}") | |
| 189 | 217 | now = datetime.now(ZoneInfo("America/Toronto")) |
| 190 | 218 | per = self.d.get("period", {}) or {} |
| 191 | 219 | p.set_xy(24, 125) |
@@ -194,7 +222,7 @@ class GroupeKAReport: | ||
| 194 | 222 | ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")), |
| 195 | 223 | ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"), |
| 196 | 224 | ("Plateforme", "https://" + self.site.get("domain", "")), |
| 197 | − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"), | |
| 225 | + ("Type de rapport", REPORT_MODES[self.mode]), | |
| 198 | 226 | ] |
| 199 | 227 | y = 128 |
| 200 | 228 | for k, v in rows: |
@@ -206,7 +234,6 @@ class GroupeKAReport: | ||
| 206 | 234 | p.cell(0, 6, str(v)) |
| 207 | 235 | p.set_font("helvetica", "", 10.5) |
| 208 | 236 | y += 8 |
| 209 | − # bande encre au pied | |
| 210 | 237 | p.set_fill_color(*INK) |
| 211 | 238 | p.rect(10, 262, 190, 25, style="F") |
| 212 | 239 | p.set_xy(24, 270) |
@@ -231,7 +258,7 @@ class GroupeKAReport: | ||
| 231 | 258 | p = self.pdf |
| 232 | 259 | cols, gw, gh, gap = 3, 56, 26, 3 |
| 233 | 260 | x0, y = p.l_margin, p.get_y() |
| 234 | − for i, k in enumerate(kpis[:9]): | |
| 261 | + for i, k in enumerate(kpis[:12]): | |
| 235 | 262 | x = x0 + (i % cols) * (gw + gap) |
| 236 | 263 | if i and i % cols == 0: |
| 237 | 264 | y += gh + gap |
@@ -253,20 +280,81 @@ class GroupeKAReport: | ||
| 253 | 280 | p.set_font("helvetica", "B", 8) |
| 254 | 281 | p.set_text_color(*(GREEN if up else DANGER)) |
| 255 | 282 | arrow = "+" if k["delta_pct"] >= 0 else "" |
| 256 | − 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.") | |
| 257 | 286 | p.set_y(y + gh + 8) |
| 258 | 287 | |
| 259 | − 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): | |
| 260 | 348 | p = self.pdf |
| 261 | 349 | pts = s.get("points") or [] |
| 262 | 350 | if len(pts) < 2: |
| 263 | 351 | return |
| 352 | + if s.get("kind") == "bar": | |
| 353 | + self._vbars(s) | |
| 354 | + return | |
| 264 | 355 | if p.get_y() > 200: |
| 265 | 356 | p.add_page() |
| 266 | − p.set_font("helvetica", "B", 10) | |
| 267 | − p.set_text_color(*INK) | |
| 268 | − p.cell(0, 6, s.get("title", "")) | |
| 269 | − p.ln(7) | |
| 357 | + self._chart_title(s.get("title", "")) | |
| 270 | 358 | x0, y0, w, h = p.l_margin, p.get_y(), 174, 52 |
| 271 | 359 | self._card(x0, y0, w, h, fill=WHITE) |
| 272 | 360 | cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16 |
@@ -274,7 +362,6 @@ class GroupeKAReport: | ||
| 274 | 362 | vmax = max(vals) or 1 |
| 275 | 363 | vmin = min(0, min(vals)) |
| 276 | 364 | rng = (vmax - vmin) or 1 |
| 277 | − # grille + graduations | |
| 278 | 365 | p.set_font("helvetica", "", 6.3) |
| 279 | 366 | p.set_text_color(*INK3) |
| 280 | 367 | p.set_draw_color(200, 200, 195) |
@@ -285,6 +372,20 @@ class GroupeKAReport: | ||
| 285 | 372 | p.set_xy(x0 + 1, gy - 1.6) |
| 286 | 373 | p.cell(10, 3, _fr(vmin + rng * g / 4), align="R") |
| 287 | 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 | + | |
| 288 | 389 | def draw(series, color, width, dash=None): |
| 289 | 390 | n = len(series) |
| 290 | 391 | p.set_draw_color(*color) |
@@ -293,8 +394,7 @@ class GroupeKAReport: | ||
| 293 | 394 | p.set_dash_pattern(dash=1.2, gap=1.2) |
| 294 | 395 | last = None |
| 295 | 396 | for i, pt in enumerate(series): |
| 296 | − px = cx + cw * (i / (n - 1)) | |
| 297 | − py = cy + ch - ch * ((pt["v"] - vmin) / rng) | |
| 397 | + px, py = xy(i, n, pt["v"]) | |
| 298 | 398 | if last: |
| 299 | 399 | p.line(last[0], last[1], px, py) |
| 300 | 400 | last = (px, py) |
@@ -303,7 +403,6 @@ class GroupeKAReport: | ||
| 303 | 403 | if s.get("compare"): |
| 304 | 404 | draw(s["compare"], INK3, 0.35, dash=True) |
| 305 | 405 | draw(pts, self.accent, 0.7) |
| 306 | − # libellés d'axe X (premier / milieu / dernier) | |
| 307 | 406 | p.set_text_color(*INK3) |
| 308 | 407 | for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)): |
| 309 | 408 | p.set_xy(cx + cw * frac - 9, cy + ch + 1.5) |
@@ -313,9 +412,166 @@ class GroupeKAReport: | ||
| 313 | 412 | p.set_font("helvetica", "", 6.8) |
| 314 | 413 | p.set_text_color(*INK3) |
| 315 | 414 | p.cell(0, 4, "— période courante (accent) · ---- période comparée") |
| 316 | − p.ln(6) | |
| 317 | − else: | |
| 318 | − 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) | |
| 319 | 575 | |
| 320 | 576 | def _bars(self, title, items, unit=""): |
| 321 | 577 | p = self.pdf |
@@ -325,10 +581,8 @@ class GroupeKAReport: | ||
| 325 | 581 | need = 10 + len(items) * 7 |
| 326 | 582 | if p.get_y() + need > 265: |
| 327 | 583 | p.add_page() |
| 328 | − p.set_font("helvetica", "B", 10) | |
| 329 | − p.set_text_color(*INK) | |
| 330 | − p.cell(0, 6, title) | |
| 331 | − p.ln(8) | |
| 584 | + self._chart_title(title) | |
| 585 | + p.ln(1) | |
| 332 | 586 | vmax = max(it["value"] for it in items) or 1 |
| 333 | 587 | for it in items: |
| 334 | 588 | y = p.get_y() |
@@ -336,19 +590,23 @@ class GroupeKAReport: | ||
| 336 | 590 | p.set_text_color(*INK) |
| 337 | 591 | p.set_x(p.l_margin) |
| 338 | 592 | p.cell(46, 5, str(it["label"])[:34]) |
| 339 | − bw = 96 * (it["value"] / vmax) | |
| 593 | + bw = 86 * (it["value"] / vmax) | |
| 340 | 594 | p.set_fill_color(*self.accent) |
| 341 | 595 | p.set_draw_color(*INK) |
| 342 | 596 | p.set_line_width(0.25) |
| 343 | 597 | p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF") |
| 344 | − p.set_xy(p.l_margin + 148, y) | |
| 598 | + p.set_xy(p.l_margin + 136, y) | |
| 345 | 599 | p.set_font("helvetica", "B", 7.6) |
| 346 | − 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") | |
| 347 | 606 | p.ln(6.4) |
| 348 | 607 | p.ln(3) |
| 349 | 608 | |
| 350 | 609 | def _donut(self, b): |
| 351 | − # anneau vectoriel simple (arcs) + légende | |
| 352 | 610 | p = self.pdf |
| 353 | 611 | items = [it for it in (b.get("items") or []) if it.get("value")][:8] |
| 354 | 612 | total = sum(it["value"] for it in items) |
@@ -356,17 +614,13 @@ class GroupeKAReport: | ||
| 356 | 614 | return |
| 357 | 615 | if p.get_y() > 210: |
| 358 | 616 | p.add_page() |
| 359 | − p.set_font("helvetica", "B", 10) | |
| 360 | − p.set_text_color(*INK) | |
| 361 | − p.cell(0, 6, b.get("title", "")) | |
| 362 | − p.ln(8) | |
| 617 | + self._chart_title(b.get("title", "")) | |
| 618 | + p.ln(1) | |
| 363 | 619 | cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20 |
| 364 | − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10] | |
| 365 | 620 | start = -90.0 |
| 366 | 621 | for i, it in enumerate(items): |
| 367 | 622 | frac = it["value"] / total |
| 368 | − f = shades[i % len(shades)] | |
| 369 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 623 | + col = self._shade(i) | |
| 370 | 624 | steps = max(2, int(72 * frac)) |
| 371 | 625 | p.set_fill_color(*col) |
| 372 | 626 | p.set_draw_color(*col) |
@@ -385,11 +639,9 @@ class GroupeKAReport: | ||
| 385 | 639 | p.set_line_width(0.4) |
| 386 | 640 | p.ellipse(cx - 11, cy - 11, 22, 22, style="DF") |
| 387 | 641 | p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D") |
| 388 | − # légende | |
| 389 | 642 | ly = cy - 22 |
| 390 | 643 | for i, it in enumerate(items): |
| 391 | − f = shades[i % len(shades)] | |
| 392 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 644 | + col = self._shade(i) | |
| 393 | 645 | p.set_fill_color(*col) |
| 394 | 646 | p.set_draw_color(*INK) |
| 395 | 647 | p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF") |
@@ -401,7 +653,39 @@ class GroupeKAReport: | ||
| 401 | 653 | ly += 5.6 |
| 402 | 654 | p.set_y(max(cy + r, ly) + 6) |
| 403 | 655 | |
| 404 | − 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): | |
| 405 | 689 | p = self.pdf |
| 406 | 690 | cols = t.get("columns") or [] |
| 407 | 691 | rows = t.get("rows") or [] |
@@ -418,7 +702,7 @@ class GroupeKAReport: | ||
| 418 | 702 | p.ln(6) |
| 419 | 703 | head() |
| 420 | 704 | p.set_text_color(*INK) |
| 421 | − for i, row in enumerate(rows[:200]): | |
| 705 | + for i, row in enumerate(rows[:max_rows]): | |
| 422 | 706 | if p.get_y() > 262: |
| 423 | 707 | p.add_page() |
| 424 | 708 | head() |
@@ -429,10 +713,10 @@ class GroupeKAReport: | ||
| 429 | 713 | txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell) |
| 430 | 714 | p.cell(w, 5.4, " " + txt[:34], fill=True) |
| 431 | 715 | p.ln(5.4) |
| 432 | − if len(rows) > 200: | |
| 716 | + if len(rows) > max_rows: | |
| 433 | 717 | p.set_font("helvetica", "", 7) |
| 434 | 718 | p.set_text_color(*INK3) |
| 435 | − 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") | |
| 436 | 720 | p.ln(6) |
| 437 | 721 | |
| 438 | 722 | def _records(self): |
@@ -441,7 +725,7 @@ class GroupeKAReport: | ||
| 441 | 725 | return |
| 442 | 726 | self._section_title("Records & faits marquants") |
| 443 | 727 | p = self.pdf |
| 444 | − for r in recs[:10]: | |
| 728 | + for r in recs[:14]: | |
| 445 | 729 | if p.get_y() > 258: |
| 446 | 730 | p.add_page() |
| 447 | 731 | y = p.get_y() |
@@ -499,43 +783,76 @@ class GroupeKAReport: | ||
| 499 | 783 | "groupe-ka.com/conditions · /confidentialite · /loi-25.", |
| 500 | 784 | ) |
| 501 | 785 | |
| 502 | − def _toc_page(self): | |
| 503 | − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en | |
| 504 | − # page 2 en réservant la page lors du build (voir build()). | |
| 505 | − 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() | |
| 506 | 807 | |
| 507 | 808 | def build(self) -> bytes: |
| 508 | 809 | p = self.pdf |
| 509 | 810 | p.alias_nb_pages() |
| 510 | 811 | self._cover() |
| 812 | + with_toc = self.mode in ("complet", "donnees") | |
| 813 | + toc_page_no = None | |
| 511 | 814 | if self.mode == "synthese": |
| 512 | 815 | p.add_page() |
| 513 | 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) | |
| 514 | 825 | self._records() |
| 515 | 826 | self._final_page() |
| 516 | − 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 | |
| 517 | 839 | p.add_page() |
| 518 | 840 | toc_page_no = p.page_no() |
| 519 | 841 | p.add_page() |
| 520 | 842 | self._kpis() |
| 521 | − for s in self.d.get("series") or []: | |
| 522 | − if s.get("kind") == "bar": | |
| 523 | − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", "")) | |
| 524 | − else: | |
| 525 | − self._line_chart(s) | |
| 526 | − for b in self.d.get("breakdowns") or []: | |
| 527 | − if b.get("kind") == "donut": | |
| 528 | − self._donut(b) | |
| 529 | − else: | |
| 530 | − self._bars(b.get("title", ""), b.get("items")) | |
| 531 | − geo = self.d.get("geo") | |
| 532 | − if geo: | |
| 533 | − 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() | |
| 534 | 850 | for t in self.d.get("tables") or []: |
| 535 | 851 | self._table(t) |
| 536 | 852 | self._records() |
| 537 | 853 | self._final_page() |
| 538 | − # 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: | |
| 539 | 856 | last_page = p.page |
| 540 | 857 | p.page = toc_page_no |
| 541 | 858 | p.set_y(22) |
@@ -554,6 +871,7 @@ class GroupeKAReport: | ||
| 554 | 871 | return bytes(p.output()) |
| 555 | 872 | |
| 556 | 873 | |
| 557 | −def filename(platform_id: str, period: str) -> str: | |
| 874 | +def filename(platform_id: str, period: str, mode: str = "complet") -> str: | |
| 558 | 875 | today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d") |
| 559 | − 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/pages/Stats.tsx
+58 −18
@@ -2,30 +2,42 @@ | ||
| 2 | 2 | // Auto-Ka — Agrégateur de voitures usagées à vendre (province de Québec) |
| 3 | 3 | // Auteur : Simon-Pierre Boucher — contact@spboucher.ai |
| 4 | 4 | // Stats.tsx : tableau de bord analytique du marché — module Stats commun |
| 5 | −// Groupe KA (contrat ka/stats/SPEC.md) : KPI + deltas, sélecteur | |
| 6 | −// de période, courbes/anneaux/barres/heatmap, répartition | |
| 7 | −// géographique, tableaux détaillés, records et export PDF. | |
| 5 | +// Groupe KA v2 (contrat ka/stats/SPEC.md) : KPI + sparklines, | |
| 6 | +// jauges de complétude, courbes/aires/barres, multi-courbes, | |
| 7 | +// barres empilées, répartitions avec deltas, distributions, | |
| 8 | +// géographie, heatmaps calendrier + horaire, tableaux détaillés, | |
| 9 | +// records et menu d'export PDF (5 rapports). | |
| 8 | 10 | // ----------------------------------------------------------------------------- |
| 9 | 11 | import { useCallback, useEffect, useState } from "react"; |
| 10 | 12 | import type { CSSProperties } from "react"; |
| 11 | 13 | import { |
| 12 | 14 | BarChart, CalendarHeatmap, DataTable, Donut, EmptyBlock, Fraicheur, |
| 13 | − KpiCard, LineChart, PdfButton, PeriodSelector, RecordCard, | |
| 15 | + GaugeCard, Histogram, HourHeatmap, KpiCard, LineChart, MultiLineChart, | |
| 16 | + PdfButton, PeriodSelector, RecordCard, StackedBarChart, StatSummary, | |
| 17 | + VBarChart, | |
| 18 | +} from "../ka/stats/kacharts"; | |
| 19 | +import type { | |
| 20 | + Distribution, Gauge, HourCell, Kpi, MultiSerie, RecordFact, Serie, | |
| 21 | + StackedSerie, TableSpec, | |
| 14 | 22 | } from "../ka/stats/kacharts"; |
| 15 | −import type { Kpi, RecordFact, Serie, TableSpec } from "../ka/stats/kacharts"; | |
| 16 | 23 | |
| 17 | 24 | interface Breakdown { |
| 18 | 25 | id: string; title: string; kind: "donut" | "bar"; |
| 19 | − items: { label: string; value: number }[]; | |
| 26 | + items: { label: string; value: number; delta_pct?: number | null }[]; | |
| 20 | 27 | } |
| 21 | 28 | interface Dashboard { |
| 22 | 29 | updated: string; |
| 23 | 30 | period: { from: string; to: string; label: string }; |
| 24 | 31 | kpis: Kpi[]; |
| 32 | + gauges?: Gauge[]; | |
| 25 | 33 | series: Serie[]; |
| 34 | + multiseries?: MultiSerie[]; | |
| 35 | + stacked?: StackedSerie[]; | |
| 26 | 36 | breakdowns: Breakdown[]; |
| 37 | + distributions?: Distribution[]; | |
| 27 | 38 | geo?: { title: string; items: { label: string; value: number }[] }; |
| 28 | 39 | heatmap?: { title: string; cells: { date: string; value: number }[] }; |
| 40 | + hourly?: { title: string; cells: HourCell[] }; | |
| 29 | 41 | tables: TableSpec[]; |
| 30 | 42 | records: RecordFact[]; |
| 31 | 43 | } |
@@ -35,6 +47,9 @@ const grid = (min: number): CSSProperties => ({ | ||
| 35 | 47 | gridTemplateColumns: `repeat(auto-fit, minmax(min(${min}px, 100%), 1fr))`, |
| 36 | 48 | }); |
| 37 | 49 | |
| 50 | +/* Séries dont la tendance mérite le résumé statistique sous la courbe. */ | |
| 51 | +const WITH_STATS = new Set(["inv", "avg_price"]); | |
| 52 | + | |
| 38 | 53 | export default function StatsPage() { |
| 39 | 54 | const [period, setPeriod] = useState("30j"); |
| 40 | 55 | const [custom, setCustom] = useState<{ from: string; to: string }>({ from: "", to: "" }); |
@@ -78,15 +93,15 @@ export default function StatsPage() { | ||
| 78 | 93 | |
| 79 | 94 | return ( |
| 80 | 95 | <div className="container page" style={{ display: "grid", gap: 22 }}> |
| 81 | − {/* --- 1. entête : titre + PDF + fraîcheur ------------------------------ */} | |
| 96 | + {/* --- entête : titre + export PDF (5 rapports) + fraîcheur ------------- */} | |
| 82 | 97 | <div className="stats-head"> |
| 83 | 98 | <div> |
| 84 | 99 | <span className="kicker">Statistiques · {dash.period.label}</span> |
| 85 | 100 | <h1>Le marché de l'occasion, en chiffres</h1> |
| 86 | 101 | <p className="lead" style={{ marginBottom: 10 }}> |
| 87 | 102 | Tableau de bord calculé sur les données réelles d'Auto-Ka — |
| 88 | − inventaire des concessionnaires du Québec, du {dash.period.from} au{" "} | |
| 89 | − {dash.period.to}. | |
| 103 | + inventaire des concessionnaires et particuliers du Québec, du{" "} | |
| 104 | + {dash.period.from} au {dash.period.to}. | |
| 90 | 105 | </p> |
| 91 | 106 | <Fraicheur updated={dash.updated} onRefresh={load} /> |
| 92 | 107 | </div> |
@@ -97,7 +112,7 @@ export default function StatsPage() { | ||
| 97 | 112 | </div> |
| 98 | 113 | </div> |
| 99 | 114 | |
| 100 | − {/* --- 2. sélecteur de période global ----------------------------------- */} | |
| 115 | + {/* --- sélecteur de période global -------------------------------------- */} | |
| 101 | 116 | <div className="card" style={{ padding: "12px 16px" }}> |
| 102 | 117 | <PeriodSelector |
| 103 | 118 | value={useCustom ? "" : period} |
@@ -114,7 +129,7 @@ export default function StatsPage() { | ||
| 114 | 129 | )} |
| 115 | 130 | |
| 116 | 131 | <div style={{ display: "grid", gap: 22, opacity: loading ? 0.55 : 1, transition: "opacity 0.2s" }}> |
| 117 | − {/* --- 3. bandeau KPI -------------------------------------------------- */} | |
| 132 | + {/* --- 1. bandeau KPI (avec sparklines) -------------------------------- */} | |
| 118 | 133 | {dash.kpis.length ? ( |
| 119 | 134 | <div style={grid(210)}> |
| 120 | 135 | {dash.kpis.map((k) => <KpiCard key={k.id} k={k} />)} |
@@ -123,33 +138,58 @@ export default function StatsPage() { | ||
| 123 | 138 | <EmptyBlock title="Indicateurs clés" /> |
| 124 | 139 | )} |
| 125 | 140 | |
| 126 | − {/* --- 4. courbes d'évolution ------------------------------------------ */} | |
| 141 | + {/* --- 2. jauges : complétude des fiches -------------------------------- */} | |
| 142 | + {dash.gauges?.length ? ( | |
| 143 | + <section> | |
| 144 | + <h2 style={{ marginBottom: 12 }}>Complétude des fiches</h2> | |
| 145 | + <div style={grid(180)}> | |
| 146 | + {dash.gauges.map((g) => <GaugeCard key={g.id} g={g} />)} | |
| 147 | + </div> | |
| 148 | + </section> | |
| 149 | + ) : null} | |
| 150 | + | |
| 151 | + {/* --- 3. évolution : courbes/aires, barres, multi-courbes, empilées ---- */} | |
| 127 | 152 | {dash.series.length ? ( |
| 128 | − dash.series.map((s) => <LineChart key={s.id} serie={s} />) | |
| 153 | + dash.series.map((s) => ( | |
| 154 | + <div key={s.id} style={{ display: "grid", gap: 10 }}> | |
| 155 | + {s.kind === "bar" ? <VBarChart serie={s} /> : <LineChart serie={s} />} | |
| 156 | + {WITH_STATS.has(s.id) && <StatSummary serie={s} />} | |
| 157 | + </div> | |
| 158 | + )) | |
| 129 | 159 | ) : ( |
| 130 | 160 | <EmptyBlock title="Évolution quotidienne" /> |
| 131 | 161 | )} |
| 162 | + {(dash.multiseries ?? []).map((ms) => <MultiLineChart key={ms.id} ms={ms} />)} | |
| 163 | + {(dash.stacked ?? []).map((st) => <StackedBarChart key={st.id} st={st} />)} | |
| 132 | 164 | |
| 133 | − {/* --- 5. répartitions : anneau + barres ------------------------------- */} | |
| 165 | + {/* --- 4. répartitions : anneaux, barres, distributions ------------------ */} | |
| 134 | 166 | <div style={grid(340)}> |
| 135 | 167 | {donuts.map((b) => <Donut key={b.id} title={b.title} items={b.items} />)} |
| 136 | 168 | {bars.map((b) => <BarChart key={b.id} title={b.title} items={b.items} />)} |
| 137 | 169 | </div> |
| 170 | + {dash.distributions?.length ? ( | |
| 171 | + <div style={grid(340)}> | |
| 172 | + {dash.distributions.map((d) => <Histogram key={d.id} dist={d} />)} | |
| 173 | + </div> | |
| 174 | + ) : null} | |
| 138 | 175 | |
| 139 | − {/* --- 6. répartition géographique -------------------------------------- */} | |
| 176 | + {/* --- 5. répartition géographique --------------------------------------- */} | |
| 140 | 177 | {dash.geo?.items?.length |
| 141 | 178 | ? <BarChart title={dash.geo.title} items={dash.geo.items} unit="véhicules" /> |
| 142 | 179 | : <EmptyBlock title="Par région" />} |
| 143 | 180 | |
| 144 | − {/* --- 7. calendrier de chaleur ------------------------------------------ */} | |
| 181 | + {/* --- 6. calendriers : quotidien + horaire ------------------------------- */} | |
| 145 | 182 | {dash.heatmap?.cells?.length |
| 146 | 183 | ? <CalendarHeatmap title={dash.heatmap.title} cells={dash.heatmap.cells} /> |
| 147 | 184 | : <EmptyBlock title="Activité quotidienne" />} |
| 185 | + {dash.hourly?.cells?.length | |
| 186 | + ? <HourHeatmap title={dash.hourly.title} cells={dash.hourly.cells} /> | |
| 187 | + : null} | |
| 148 | 188 | |
| 149 | − {/* --- 8. tableaux détaillés --------------------------------------------- */} | |
| 189 | + {/* --- 7. tableaux détaillés ---------------------------------------------- */} | |
| 150 | 190 | {dash.tables.map((t) => <DataTable key={t.id} spec={t} />)} |
| 151 | 191 | |
| 152 | − {/* --- 9. records & faits marquants --------------------------------------- */} | |
| 192 | + {/* --- 8. records & faits marquants ----------------------------------------- */} | |
| 153 | 193 | {dash.records.length > 0 && ( |
| 154 | 194 | <section> |
| 155 | 195 | <h2 style={{ marginBottom: 12 }}>Records & faits marquants</h2> |
| 156 | 196 | |