KA Agent v2 (widget) : plein écran à l'ouverture (desktop+mobile), fond gelé + calage visualViewport (clavier mobile stable), rendu Markdown complet en streaming (titres, listes, tableaux, code, liens nommés)
10 changed files +2,507 −434
modified
creaka/kapdf.py
+389 −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,7 +67,8 @@ def _fr(n) -> str: | ||
| 52 | 67 | _SUBST = { |
| 53 | 68 | "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-", |
| 54 | 69 | "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"', |
| 55 | − "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", | |
| 70 | + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", | |
| 71 | + "×": "x", "·": ".", "σ": "sigma", "Δ": "delta", | |
| 56 | 72 | } |
| 57 | 73 | |
| 58 | 74 | |
@@ -79,7 +95,7 @@ class _PDF(FPDF): | ||
| 79 | 95 | self.set_auto_page_break(True, margin=22) |
| 80 | 96 | |
| 81 | 97 | def header(self): |
| 82 | − if self.cover_mode or self.page_no() == 1: # jamais sur la couverture | |
| 98 | + if self.cover_mode or self.page_no() == 1: | |
| 83 | 99 | return |
| 84 | 100 | self.set_font("helvetica", "B", 8.5) |
| 85 | 101 | self.set_text_color(*INK) |
@@ -95,8 +111,8 @@ class _PDF(FPDF): | ||
| 95 | 111 | self.set_y(20) |
| 96 | 112 | |
| 97 | 113 | def footer(self): |
| 98 | − # le pied de la couverture se rend APRÈS la remise à zéro de cover_mode | |
| 99 | − # (add_page suivant) : on exclut donc aussi explicitement la page 1 | |
| 114 | + # page 1 = couverture (le flag cover_mode est déjà retombé quand | |
| 115 | + # add_page() clôt la page 1 → tester aussi le numéro de page) | |
| 100 | 116 | if self.cover_mode or self.page_no() == 1: |
| 101 | 117 | return |
| 102 | 118 | self.set_y(-15) |
@@ -114,7 +130,7 @@ class GroupeKAReport: | ||
| 114 | 130 | def __init__(self, site: dict, dashboard: dict, mode: str = "complet"): |
| 115 | 131 | self.site = site |
| 116 | 132 | self.d = dashboard |
| 117 | − self.mode = mode | |
| 133 | + self.mode = mode if mode in REPORT_MODES else "complet" | |
| 118 | 134 | self.accent = _hex(site.get("accent", "#d9f26b")) |
| 119 | 135 | period = dashboard.get("period", {}) or {} |
| 120 | 136 | self.period_label = period.get("label") or "toute la période" |
@@ -129,6 +145,11 @@ class GroupeKAReport: | ||
| 129 | 145 | p.set_fill_color(*fill) |
| 130 | 146 | p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2) |
| 131 | 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 | + | |
| 132 | 153 | def _kicker(self, text): |
| 133 | 154 | p = self.pdf |
| 134 | 155 | p.set_font("helvetica", "B", 8) |
@@ -152,6 +173,14 @@ class GroupeKAReport: | ||
| 152 | 173 | self.toc.append((title, self.pdf.page_no())) |
| 153 | 174 | self.pdf.ln(11) |
| 154 | 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 | + | |
| 155 | 184 | # ---------- pages ---------- |
| 156 | 185 | def _cover(self): |
| 157 | 186 | p = self.pdf |
@@ -163,12 +192,10 @@ class GroupeKAReport: | ||
| 163 | 192 | p.set_draw_color(*INK) |
| 164 | 193 | p.set_line_width(1.0) |
| 165 | 194 | p.rect(10, 10, 190, 277) |
| 166 | − # kicker | |
| 167 | 195 | p.set_font("helvetica", "B", 10) |
| 168 | 196 | p.set_text_color(*GREEN) |
| 169 | 197 | p.set_xy(24, 34) |
| 170 | 198 | p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE") |
| 171 | − # wordmark : partie gauche + boîte encre/accent | |
| 172 | 199 | wm = self.site.get("wordmark", "") |
| 173 | 200 | left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None) |
| 174 | 201 | p.set_xy(24, 70) |
@@ -186,7 +213,7 @@ class GroupeKAReport: | ||
| 186 | 213 | p.set_xy(24, 100) |
| 187 | 214 | p.set_font("helvetica", "", 13) |
| 188 | 215 | p.set_text_color(*INK2) |
| 189 | − p.multi_cell(150, 7, f"Rapport statistique — {wm}") | |
| 216 | + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}") | |
| 190 | 217 | now = datetime.now(ZoneInfo("America/Toronto")) |
| 191 | 218 | per = self.d.get("period", {}) or {} |
| 192 | 219 | p.set_xy(24, 125) |
@@ -195,7 +222,7 @@ class GroupeKAReport: | ||
| 195 | 222 | ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")), |
| 196 | 223 | ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"), |
| 197 | 224 | ("Plateforme", "https://" + self.site.get("domain", "")), |
| 198 | − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"), | |
| 225 | + ("Type de rapport", REPORT_MODES[self.mode]), | |
| 199 | 226 | ] |
| 200 | 227 | y = 128 |
| 201 | 228 | for k, v in rows: |
@@ -207,7 +234,6 @@ class GroupeKAReport: | ||
| 207 | 234 | p.cell(0, 6, str(v)) |
| 208 | 235 | p.set_font("helvetica", "", 10.5) |
| 209 | 236 | y += 8 |
| 210 | − # bande encre au pied | |
| 211 | 237 | p.set_fill_color(*INK) |
| 212 | 238 | p.rect(10, 262, 190, 25, style="F") |
| 213 | 239 | p.set_xy(24, 270) |
@@ -232,7 +258,7 @@ class GroupeKAReport: | ||
| 232 | 258 | p = self.pdf |
| 233 | 259 | cols, gw, gh, gap = 3, 56, 26, 3 |
| 234 | 260 | x0, y = p.l_margin, p.get_y() |
| 235 | − for i, k in enumerate(kpis[:9]): | |
| 261 | + for i, k in enumerate(kpis[:12]): | |
| 236 | 262 | x = x0 + (i % cols) * (gw + gap) |
| 237 | 263 | if i and i % cols == 0: |
| 238 | 264 | y += gh + gap |
@@ -254,20 +280,81 @@ class GroupeKAReport: | ||
| 254 | 280 | p.set_font("helvetica", "B", 8) |
| 255 | 281 | p.set_text_color(*(GREEN if up else DANGER)) |
| 256 | 282 | arrow = "+" if k["delta_pct"] >= 0 else "" |
| 257 | − 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.") | |
| 286 | + p.set_y(y + gh + 8) | |
| 287 | + | |
| 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") | |
| 258 | 330 | p.set_y(y + gh + 8) |
| 259 | 331 | |
| 260 | − def _line_chart(self, s): | |
| 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): | |
| 261 | 348 | p = self.pdf |
| 262 | 349 | pts = s.get("points") or [] |
| 263 | 350 | if len(pts) < 2: |
| 264 | 351 | return |
| 352 | + if s.get("kind") == "bar": | |
| 353 | + self._vbars(s) | |
| 354 | + return | |
| 265 | 355 | if p.get_y() > 200: |
| 266 | 356 | p.add_page() |
| 267 | − p.set_font("helvetica", "B", 10) | |
| 268 | − p.set_text_color(*INK) | |
| 269 | − p.cell(0, 6, s.get("title", "")) | |
| 270 | − p.ln(7) | |
| 357 | + self._chart_title(s.get("title", "")) | |
| 271 | 358 | x0, y0, w, h = p.l_margin, p.get_y(), 174, 52 |
| 272 | 359 | self._card(x0, y0, w, h, fill=WHITE) |
| 273 | 360 | cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16 |
@@ -275,7 +362,6 @@ class GroupeKAReport: | ||
| 275 | 362 | vmax = max(vals) or 1 |
| 276 | 363 | vmin = min(0, min(vals)) |
| 277 | 364 | rng = (vmax - vmin) or 1 |
| 278 | − # grille + graduations | |
| 279 | 365 | p.set_font("helvetica", "", 6.3) |
| 280 | 366 | p.set_text_color(*INK3) |
| 281 | 367 | p.set_draw_color(200, 200, 195) |
@@ -286,6 +372,20 @@ class GroupeKAReport: | ||
| 286 | 372 | p.set_xy(x0 + 1, gy - 1.6) |
| 287 | 373 | p.cell(10, 3, _fr(vmin + rng * g / 4), align="R") |
| 288 | 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 | + | |
| 289 | 389 | def draw(series, color, width, dash=None): |
| 290 | 390 | n = len(series) |
| 291 | 391 | p.set_draw_color(*color) |
@@ -294,8 +394,7 @@ class GroupeKAReport: | ||
| 294 | 394 | p.set_dash_pattern(dash=1.2, gap=1.2) |
| 295 | 395 | last = None |
| 296 | 396 | for i, pt in enumerate(series): |
| 297 | − px = cx + cw * (i / (n - 1)) | |
| 298 | − py = cy + ch - ch * ((pt["v"] - vmin) / rng) | |
| 397 | + px, py = xy(i, n, pt["v"]) | |
| 299 | 398 | if last: |
| 300 | 399 | p.line(last[0], last[1], px, py) |
| 301 | 400 | last = (px, py) |
@@ -304,7 +403,6 @@ class GroupeKAReport: | ||
| 304 | 403 | if s.get("compare"): |
| 305 | 404 | draw(s["compare"], INK3, 0.35, dash=True) |
| 306 | 405 | draw(pts, self.accent, 0.7) |
| 307 | − # libellés d'axe X (premier / milieu / dernier) | |
| 308 | 406 | p.set_text_color(*INK3) |
| 309 | 407 | for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)): |
| 310 | 408 | p.set_xy(cx + cw * frac - 9, cy + ch + 1.5) |
@@ -314,9 +412,166 @@ class GroupeKAReport: | ||
| 314 | 412 | p.set_font("helvetica", "", 6.8) |
| 315 | 413 | p.set_text_color(*INK3) |
| 316 | 414 | p.cell(0, 4, "— période courante (accent) · ---- période comparée") |
| 317 | − p.ln(6) | |
| 318 | − else: | |
| 319 | − 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) | |
| 320 | 575 | |
| 321 | 576 | def _bars(self, title, items, unit=""): |
| 322 | 577 | p = self.pdf |
@@ -326,10 +581,8 @@ class GroupeKAReport: | ||
| 326 | 581 | need = 10 + len(items) * 7 |
| 327 | 582 | if p.get_y() + need > 265: |
| 328 | 583 | p.add_page() |
| 329 | − p.set_font("helvetica", "B", 10) | |
| 330 | − p.set_text_color(*INK) | |
| 331 | − p.cell(0, 6, title) | |
| 332 | − p.ln(8) | |
| 584 | + self._chart_title(title) | |
| 585 | + p.ln(1) | |
| 333 | 586 | vmax = max(it["value"] for it in items) or 1 |
| 334 | 587 | for it in items: |
| 335 | 588 | y = p.get_y() |
@@ -337,19 +590,23 @@ class GroupeKAReport: | ||
| 337 | 590 | p.set_text_color(*INK) |
| 338 | 591 | p.set_x(p.l_margin) |
| 339 | 592 | p.cell(46, 5, str(it["label"])[:34]) |
| 340 | − bw = 96 * (it["value"] / vmax) | |
| 593 | + bw = 86 * (it["value"] / vmax) | |
| 341 | 594 | p.set_fill_color(*self.accent) |
| 342 | 595 | p.set_draw_color(*INK) |
| 343 | 596 | p.set_line_width(0.25) |
| 344 | 597 | p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF") |
| 345 | − p.set_xy(p.l_margin + 148, y) | |
| 598 | + p.set_xy(p.l_margin + 136, y) | |
| 346 | 599 | p.set_font("helvetica", "B", 7.6) |
| 347 | − 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") | |
| 348 | 606 | p.ln(6.4) |
| 349 | 607 | p.ln(3) |
| 350 | 608 | |
| 351 | 609 | def _donut(self, b): |
| 352 | − # anneau vectoriel simple (arcs) + légende | |
| 353 | 610 | p = self.pdf |
| 354 | 611 | items = [it for it in (b.get("items") or []) if it.get("value")][:8] |
| 355 | 612 | total = sum(it["value"] for it in items) |
@@ -357,17 +614,13 @@ class GroupeKAReport: | ||
| 357 | 614 | return |
| 358 | 615 | if p.get_y() > 210: |
| 359 | 616 | p.add_page() |
| 360 | − p.set_font("helvetica", "B", 10) | |
| 361 | − p.set_text_color(*INK) | |
| 362 | − p.cell(0, 6, b.get("title", "")) | |
| 363 | − p.ln(8) | |
| 617 | + self._chart_title(b.get("title", "")) | |
| 618 | + p.ln(1) | |
| 364 | 619 | cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20 |
| 365 | − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10] | |
| 366 | 620 | start = -90.0 |
| 367 | 621 | for i, it in enumerate(items): |
| 368 | 622 | frac = it["value"] / total |
| 369 | − f = shades[i % len(shades)] | |
| 370 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 623 | + col = self._shade(i) | |
| 371 | 624 | steps = max(2, int(72 * frac)) |
| 372 | 625 | p.set_fill_color(*col) |
| 373 | 626 | p.set_draw_color(*col) |
@@ -386,11 +639,9 @@ class GroupeKAReport: | ||
| 386 | 639 | p.set_line_width(0.4) |
| 387 | 640 | p.ellipse(cx - 11, cy - 11, 22, 22, style="DF") |
| 388 | 641 | p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D") |
| 389 | − # légende | |
| 390 | 642 | ly = cy - 22 |
| 391 | 643 | for i, it in enumerate(items): |
| 392 | − f = shades[i % len(shades)] | |
| 393 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 644 | + col = self._shade(i) | |
| 394 | 645 | p.set_fill_color(*col) |
| 395 | 646 | p.set_draw_color(*INK) |
| 396 | 647 | p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF") |
@@ -402,7 +653,39 @@ class GroupeKAReport: | ||
| 402 | 653 | ly += 5.6 |
| 403 | 654 | p.set_y(max(cy + r, ly) + 6) |
| 404 | 655 | |
| 405 | − 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): | |
| 406 | 689 | p = self.pdf |
| 407 | 690 | cols = t.get("columns") or [] |
| 408 | 691 | rows = t.get("rows") or [] |
@@ -419,7 +702,7 @@ class GroupeKAReport: | ||
| 419 | 702 | p.ln(6) |
| 420 | 703 | head() |
| 421 | 704 | p.set_text_color(*INK) |
| 422 | − for i, row in enumerate(rows[:200]): | |
| 705 | + for i, row in enumerate(rows[:max_rows]): | |
| 423 | 706 | if p.get_y() > 262: |
| 424 | 707 | p.add_page() |
| 425 | 708 | head() |
@@ -430,10 +713,10 @@ class GroupeKAReport: | ||
| 430 | 713 | txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell) |
| 431 | 714 | p.cell(w, 5.4, " " + txt[:34], fill=True) |
| 432 | 715 | p.ln(5.4) |
| 433 | − if len(rows) > 200: | |
| 716 | + if len(rows) > max_rows: | |
| 434 | 717 | p.set_font("helvetica", "", 7) |
| 435 | 718 | p.set_text_color(*INK3) |
| 436 | − 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") | |
| 437 | 720 | p.ln(6) |
| 438 | 721 | |
| 439 | 722 | def _records(self): |
@@ -442,7 +725,7 @@ class GroupeKAReport: | ||
| 442 | 725 | return |
| 443 | 726 | self._section_title("Records & faits marquants") |
| 444 | 727 | p = self.pdf |
| 445 | − for r in recs[:10]: | |
| 728 | + for r in recs[:14]: | |
| 446 | 729 | if p.get_y() > 258: |
| 447 | 730 | p.add_page() |
| 448 | 731 | y = p.get_y() |
@@ -500,43 +783,76 @@ class GroupeKAReport: | ||
| 500 | 783 | "groupe-ka.com/conditions · /confidentialite · /loi-25.", |
| 501 | 784 | ) |
| 502 | 785 | |
| 503 | − def _toc_page(self): | |
| 504 | − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en | |
| 505 | − # page 2 en réservant la page lors du build (voir build()). | |
| 506 | − 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() | |
| 507 | 807 | |
| 508 | 808 | def build(self) -> bytes: |
| 509 | 809 | p = self.pdf |
| 510 | 810 | p.alias_nb_pages() |
| 511 | 811 | self._cover() |
| 812 | + with_toc = self.mode in ("complet", "donnees") | |
| 813 | + toc_page_no = None | |
| 512 | 814 | if self.mode == "synthese": |
| 513 | 815 | p.add_page() |
| 514 | 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) | |
| 515 | 825 | self._records() |
| 516 | 826 | self._final_page() |
| 517 | − 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 | |
| 518 | 839 | p.add_page() |
| 519 | 840 | toc_page_no = p.page_no() |
| 520 | 841 | p.add_page() |
| 521 | 842 | self._kpis() |
| 522 | − for s in self.d.get("series") or []: | |
| 523 | − if s.get("kind") == "bar": | |
| 524 | − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", "")) | |
| 525 | − else: | |
| 526 | − self._line_chart(s) | |
| 527 | − for b in self.d.get("breakdowns") or []: | |
| 528 | − if b.get("kind") == "donut": | |
| 529 | − self._donut(b) | |
| 530 | − else: | |
| 531 | − self._bars(b.get("title", ""), b.get("items")) | |
| 532 | − geo = self.d.get("geo") | |
| 533 | − if geo: | |
| 534 | − 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() | |
| 535 | 850 | for t in self.d.get("tables") or []: |
| 536 | 851 | self._table(t) |
| 537 | 852 | self._records() |
| 538 | 853 | self._final_page() |
| 539 | − # 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: | |
| 540 | 856 | last_page = p.page |
| 541 | 857 | p.page = toc_page_no |
| 542 | 858 | p.set_y(22) |
@@ -555,6 +871,7 @@ class GroupeKAReport: | ||
| 555 | 871 | return bytes(p.output()) |
| 556 | 872 | |
| 557 | 873 | |
| 558 | −def filename(platform_id: str, period: str) -> str: | |
| 874 | +def filename(platform_id: str, period: str, mode: str = "complet") -> str: | |
| 559 | 875 | today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d") |
| 560 | − 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
creaka/stats.py
+346 −46
@@ -2,9 +2,13 @@ | ||
| 2 | 2 | # Author: Simon-Pierre Boucher <contact@spboucher.ai> |
| 3 | 3 | # File: creaka/stats.py |
| 4 | 4 | # Desc: Tableau de bord analytique /api/stats/dashboard (contrat ka-stats |
| 5 | −# SPEC.md) + rapport PDF Groupe-KA (/api/stats/report via kapdf.py). | |
| 6 | −# AUCUNE stat inventée : tout est calculé depuis creators/accounts/ | |
| 7 | −# sync_log (first_seen converti en date locale, cache 5 min / période). | |
| 5 | +# SPEC.md v2) + rapport PDF Groupe-KA (/api/stats/report via kapdf.py, | |
| 6 | +# 5 modes). AUCUNE stat inventée : tout est calculé depuis creators/ | |
| 7 | +# accounts/sync_log (first_seen converti en date locale, cache 5 min). | |
| 8 | +# v2 : sparklines KPI, jauges de complétude, multi-courbes par | |
| 9 | +# plateforme, ajouts empilés par source, distributions (audiences, | |
| 10 | +# comptes/créateur, confiance), heatmap horaire 7×24, 5 tableaux, | |
| 11 | +# records enrichis. | |
| 8 | 12 | # ============================================================================== |
| 9 | 13 | from __future__ import annotations |
| 10 | 14 | |
@@ -35,7 +39,8 @@ PLAT_LBL = { | ||
| 35 | 39 | "facebook": "Facebook", "snapchat": "Snapchat", "substack": "Substack", |
| 36 | 40 | "patreon": "Patreon", "onlyfans": "OnlyFans", "linkedin": "LinkedIn", |
| 37 | 41 | "threads": "Threads", "podcast": "Balado", "site-web": "Site web", |
| 38 | − "autre": "Autre", | |
| 42 | + "spotify": "Spotify", "discord": "Discord", "fansly": "Fansly", | |
| 43 | + "mym": "MYM", "autre": "Autre", | |
| 39 | 44 | } |
| 40 | 45 | NICHE_LBL = { |
| 41 | 46 | "humour": "Humour", "mode": "Mode", "beaute": "Beauté", |
@@ -47,9 +52,22 @@ NICHE_LBL = { | ||
| 47 | 52 | "sante-mieux-etre": "Santé & mieux-être", "bouffe-resto": "Bouffe & resto", |
| 48 | 53 | "actualite-opinion": "Actualité & opinion", "autre": "Autre", |
| 49 | 54 | } |
| 55 | +TYPE_LBL = { | |
| 56 | + "youtubeur": "Youtubeur", "influenceur": "Influenceur", | |
| 57 | + "streamer": "Streamer", "podcasteur": "Podcasteur", | |
| 58 | + "humoriste": "Humoriste", "createur-tiktok": "Créateur TikTok", | |
| 59 | + "createur-ecrit": "Créateur écrit", "musicien": "Musicien", | |
| 60 | + "artiste": "Artiste", "autre": "Autre", | |
| 61 | +} | |
| 50 | 62 | # bornes réelles de normalize.audience_tier (§6.3) |
| 51 | 63 | TIER_LBL = [("nano", "Nano (< 10 k)"), ("micro", "Micro (10 k – 100 k)"), |
| 52 | 64 | ("macro", "Macro (100 k – 1 M)"), ("mega", "Méga (1 M et +)")] |
| 65 | +# tranches d'audience (distribution) — bornes en abonnés cumulés connus | |
| 66 | +REACH_BINS = [(0, 1_000, "< 1 k"), (1_000, 10_000, "1 k – 10 k"), | |
| 67 | + (10_000, 50_000, "10 k – 50 k"), (50_000, 100_000, "50 k – 100 k"), | |
| 68 | + (100_000, 500_000, "100 k – 500 k"), | |
| 69 | + (500_000, 1_000_000, "500 k – 1 M"), | |
| 70 | + (1_000_000, None, "1 M et +")] | |
| 53 | 71 | |
| 54 | 72 | |
| 55 | 73 | def site_info() -> dict: |
@@ -67,18 +85,25 @@ def site_info() -> dict: | ||
| 67 | 85 | |
| 68 | 86 | # --- utilitaires ----------------------------------------------------------------- |
| 69 | 87 | |
| 70 | −def _local_date(iso: str) -> date | None: | |
| 71 | − """ISO-8601 UTC (…Z) → date locale (America/Toronto).""" | |
| 88 | +def _local_dt(iso: str) -> datetime | None: | |
| 89 | + """ISO-8601 UTC (…Z) → datetime local (America/Toronto).""" | |
| 72 | 90 | if not iso: |
| 73 | 91 | return None |
| 74 | 92 | try: |
| 75 | 93 | dt = datetime.strptime(iso[:19], "%Y-%m-%dT%H:%M:%S") |
| 76 | − return dt.replace(tzinfo=timezone.utc).astimezone(TZ).date() | |
| 94 | + return dt.replace(tzinfo=timezone.utc).astimezone(TZ) | |
| 95 | + except ValueError: | |
| 96 | + return None | |
| 97 | + | |
| 98 | + | |
| 99 | +def _local_date(iso: str) -> date | None: | |
| 100 | + dt = _local_dt(iso) | |
| 101 | + if dt: | |
| 102 | + return dt.date() | |
| 103 | + try: | |
| 104 | + return date.fromisoformat((iso or "")[:10]) | |
| 77 | 105 | except ValueError: |
| 78 | − try: | |
| 79 | − return date.fromisoformat(iso[:10]) | |
| 80 | − except ValueError: | |
| 81 | − return None | |
| 106 | + return None | |
| 82 | 107 | |
| 83 | 108 | |
| 84 | 109 | def _parse_date(s: str) -> date | None: |
@@ -106,6 +131,14 @@ def _fr_int(n: int) -> str: | ||
| 106 | 131 | return f"{int(n):,}".replace(",", " ") |
| 107 | 132 | |
| 108 | 133 | |
| 134 | +def _spark(points: list[dict], keep: int = 20) -> list[dict]: | |
| 135 | + """Sous-échantillonne une série pour la mini-tendance des KPI (≤ keep pts).""" | |
| 136 | + if len(points) <= keep: | |
| 137 | + return points | |
| 138 | + step = (len(points) - 1) / (keep - 1) | |
| 139 | + return [points[round(i * step)] for i in range(keep)] | |
| 140 | + | |
| 141 | + | |
| 109 | 142 | # --- construction du tableau de bord ---------------------------------------------- |
| 110 | 143 | |
| 111 | 144 | def _resolve_period(period: str, d_from: str, d_to: str, |
@@ -130,10 +163,14 @@ def _resolve_period(period: str, d_from: str, d_to: str, | ||
| 130 | 163 | def _build(con: sqlite3.Connection, period: str, d_from: str, d_to: str) -> dict: |
| 131 | 164 | # fiches actives (mineurs & opt-out exclus, comme partout dans l'API) |
| 132 | 165 | creators = con.execute( |
| 133 | − "SELECT display_name, first_seen, niches, audience_tier, region, " | |
| 134 | − "total_reach, primary_platform FROM creators " | |
| 135 | − "WHERE status='active' AND is_minor=0").fetchall() | |
| 136 | − days_seen = [d for d in (_local_date(r["first_seen"]) for r in creators) if d] | |
| 166 | + "SELECT id, display_name, first_seen, niches, audience_tier, region, " | |
| 167 | + "city, bio, creator_type, total_reach, primary_platform, " | |
| 168 | + "json_extract(doc,'$.source') AS src, " | |
| 169 | + "json_extract(doc,'$.avatar_url') IS NOT NULL AS has_avatar " | |
| 170 | + "FROM creators WHERE status='active' AND is_minor=0").fetchall() | |
| 171 | + n_active = len(creators) | |
| 172 | + dts_seen = [_local_dt(r["first_seen"]) for r in creators] | |
| 173 | + days_seen = [d.date() for d in dts_seen if d] | |
| 137 | 174 | min_day = min(days_seen) if days_seen else None |
| 138 | 175 | p_from, p_to, p_label = _resolve_period(period, d_from, d_to, min_day) |
| 139 | 176 | span = (p_to - p_from).days + 1 |
@@ -151,97 +188,298 @@ def _build(con: sqlite3.Connection, period: str, d_from: str, d_to: str) -> dict | ||
| 151 | 188 | def total_until(d: date) -> int: |
| 152 | 189 | return sum(v for dd, v in adds_by_day.items() if dd <= d) |
| 153 | 190 | |
| 154 | − # comptes reliés par plateforme (comptes « à vérifier » exclus, §12.1) | |
| 191 | + # comptes reliés par plateforme (comptes « à vérifier » exclus, §12.1) + | |
| 192 | + # agrégats abonnés/vérifiés pour le tableau plateformes | |
| 155 | 193 | plat_rows = con.execute( |
| 156 | − "SELECT a.platform, COUNT(*) c FROM accounts a " | |
| 157 | − "JOIN creators c2 ON c2.id=a.creator_id " | |
| 194 | + "SELECT a.platform, COUNT(*) c, " | |
| 195 | + "SUM(CASE WHEN a.verified=1 THEN 1 ELSE 0 END) nverif, " | |
| 196 | + "SUM(COALESCE(a.followers,0)) fol, " | |
| 197 | + "COUNT(a.followers) nfol " | |
| 198 | + "FROM accounts a JOIN creators c2 ON c2.id=a.creator_id " | |
| 158 | 199 | "WHERE a.needs_review=0 AND c2.status='active' AND c2.is_minor=0 " |
| 159 | 200 | "GROUP BY a.platform ORDER BY c DESC").fetchall() |
| 160 | 201 | n_accounts = sum(r["c"] for r in plat_rows) |
| 202 | + n_verified = sum(r["nverif"] or 0 for r in plat_rows) | |
| 203 | + | |
| 204 | + # comptes par créateur (multi-plateforme, distribution, record) | |
| 205 | + acc_per_creator = con.execute( | |
| 206 | + "SELECT a.creator_id, c2.display_name, COUNT(DISTINCT a.platform) np " | |
| 207 | + "FROM accounts a JOIN creators c2 ON c2.id=a.creator_id " | |
| 208 | + "WHERE a.needs_review=0 AND c2.status='active' AND c2.is_minor=0 " | |
| 209 | + "GROUP BY a.creator_id").fetchall() | |
| 210 | + n_multi = sum(1 for r in acc_per_creator if r["np"] >= 2) | |
| 211 | + | |
| 212 | + # confiance des rattachements (distribution) | |
| 213 | + conf_rows = con.execute( | |
| 214 | + "SELECT a.confidence FROM accounts a JOIN creators c2 ON c2.id=a.creator_id " | |
| 215 | + "WHERE a.needs_review=0 AND c2.status='active' AND c2.is_minor=0").fetchall() | |
| 161 | 216 | |
| 162 | 217 | # niches (multivaluées) — global + ajouts sur la période |
| 163 | 218 | niche_total: dict[str, int] = {} |
| 164 | 219 | niche_period: dict[str, int] = {} |
| 165 | 220 | tier_total: dict[str, int] = {} |
| 221 | + tier_period: dict[str, int] = {} | |
| 222 | + type_total: dict[str, int] = {} | |
| 166 | 223 | region_total: dict[str, int] = {} |
| 167 | − for r in creators: | |
| 168 | − d = _local_date(r["first_seen"]) | |
| 224 | + city_total: dict[str, int] = {} | |
| 225 | + src_total: dict[str, int] = {} | |
| 226 | + # ajouts par jour et par source (empilé) + par plateforme principale | |
| 227 | + src_day: dict[tuple, int] = {} | |
| 228 | + plat_day: dict[tuple, int] = {} | |
| 229 | + reach_day: dict[date, int] = {} | |
| 230 | + hour_cells: dict[tuple, int] = {} | |
| 231 | + for r, dt_loc in zip(creators, dts_seen): | |
| 232 | + d = dt_loc.date() if dt_loc else None | |
| 233 | + in_p = bool(d and p_from <= d <= p_to) | |
| 169 | 234 | for n in (r["niches"] or "").split(","): |
| 170 | 235 | if not n: |
| 171 | 236 | continue |
| 172 | 237 | niche_total[n] = niche_total.get(n, 0) + 1 |
| 173 | − if d and p_from <= d <= p_to: | |
| 238 | + if in_p: | |
| 174 | 239 | niche_period[n] = niche_period.get(n, 0) + 1 |
| 175 | 240 | tier_total[r["audience_tier"]] = tier_total.get(r["audience_tier"], 0) + 1 |
| 241 | + if in_p: | |
| 242 | + tier_period[r["audience_tier"]] = tier_period.get(r["audience_tier"], 0) + 1 | |
| 243 | + if r["creator_type"]: | |
| 244 | + type_total[r["creator_type"]] = type_total.get(r["creator_type"], 0) + 1 | |
| 176 | 245 | if r["region"]: |
| 177 | 246 | region_total[r["region"]] = region_total.get(r["region"], 0) + 1 |
| 247 | + if r["city"]: | |
| 248 | + city_total[r["city"]] = city_total.get(r["city"], 0) + 1 | |
| 249 | + if r["src"]: | |
| 250 | + src_total[r["src"]] = src_total.get(r["src"], 0) + 1 | |
| 251 | + if d: | |
| 252 | + src_day[(d, r["src"])] = src_day.get((d, r["src"]), 0) + 1 | |
| 253 | + if d and r["primary_platform"]: | |
| 254 | + plat_day[(d, r["primary_platform"])] = \ | |
| 255 | + plat_day.get((d, r["primary_platform"]), 0) + 1 | |
| 256 | + if d and r["total_reach"]: | |
| 257 | + reach_day[d] = reach_day.get(d, 0) + r["total_reach"] | |
| 258 | + if dt_loc: | |
| 259 | + key = (dt_loc.weekday(), dt_loc.hour) # 0=lun … 6=dim (SPEC) | |
| 260 | + hour_cells[key] = hour_cells.get(key, 0) + 1 | |
| 178 | 261 | |
| 179 | 262 | # ---- KPI (deltas seulement quand ils sont réellement calculables) ---- |
| 180 | 263 | added_cur = added_between(p_from, p_to) |
| 181 | 264 | added_prev = added_between(prev_from, prev_to) |
| 182 | 265 | total_end = total_until(p_to) |
| 183 | 266 | total_start = total_until(prev_to) |
| 267 | + day_axis = [p_from + timedelta(days=i) for i in range(span)] | |
| 268 | + pts_added = [{"t": d.isoformat(), "v": adds_by_day.get(d, 0)} for d in day_axis] | |
| 269 | + running = total_until(p_from - timedelta(days=1)) | |
| 270 | + pts_cumul = [] | |
| 271 | + for d in day_axis: | |
| 272 | + running += adds_by_day.get(d, 0) | |
| 273 | + pts_cumul.append({"t": d.isoformat(), "v": running}) | |
| 274 | + reach = sum(r["total_reach"] for r in creators if r["total_reach"]) | |
| 275 | + | |
| 184 | 276 | kpis = [ |
| 185 | 277 | {"id": "creators", "label": "Créateurs au répertoire", "value": total_end, |
| 186 | − "unit": "", **_delta(total_end, total_start)}, | |
| 278 | + "unit": "", **_delta(total_end, total_start), "spark": _spark(pts_cumul)}, | |
| 187 | 279 | {"id": "accounts", "label": "Comptes publics reliés", "value": n_accounts, |
| 188 | 280 | "unit": "", "delta_pct": None}, |
| 281 | + {"id": "added", "label": "Créateurs ajoutés sur la période", | |
| 282 | + "value": added_cur, "unit": "", **_delta(added_cur, added_prev), | |
| 283 | + "spark": _spark(pts_added)}, | |
| 189 | 284 | {"id": "platforms", "label": "Plateformes couvertes", |
| 190 | 285 | "value": len(plat_rows), "unit": "", "delta_pct": None}, |
| 191 | − {"id": "added", "label": "Créateurs ajoutés sur la période", | |
| 192 | − "value": added_cur, "unit": "", **_delta(added_cur, added_prev)}, | |
| 286 | + {"id": "multi", "label": "Créateurs multi-plateformes", "value": n_multi, | |
| 287 | + "unit": "", "delta_pct": None}, | |
| 288 | + {"id": "verified", "label": "Comptes vérifiés (badge)", | |
| 289 | + "value": n_verified, "unit": "", "delta_pct": None}, | |
| 193 | 290 | {"id": "niches", "label": "Niches couvertes", "value": len(niche_total), |
| 194 | 291 | "unit": "", "delta_pct": None}, |
| 292 | + {"id": "regions", "label": "Régions représentées", | |
| 293 | + "value": len(region_total), "unit": "", "delta_pct": None}, | |
| 195 | 294 | ] |
| 196 | − reach = sum(r["total_reach"] for r in creators if r["total_reach"]) | |
| 197 | 295 | if reach: |
| 198 | 296 | kpis.append({"id": "reach", "label": "Portée cumulée connue", |
| 199 | 297 | "value": reach, "unit": "abonnés", "delta_pct": None}) |
| 298 | + if n_active: | |
| 299 | + kpis.append({"id": "acc_avg", "label": "Comptes reliés par créateur (moy.)", | |
| 300 | + "value": round(n_accounts / n_active, 2), "unit": "", | |
| 301 | + "delta_pct": None}) | |
| 302 | + | |
| 303 | + # ---- jauges : couvertures & complétude (calculées, pas estimées) ---- | |
| 304 | + def _cov(n: int) -> float: | |
| 305 | + return round(100.0 * n / n_active, 1) if n_active else 0.0 | |
| 306 | + n_bio = sum(1 for r in creators if r["bio"]) | |
| 307 | + n_loc = sum(1 for r in creators if r["region"] or r["city"]) | |
| 308 | + n_reach = sum(1 for r in creators if r["total_reach"]) | |
| 309 | + n_avatar = sum(1 for r in creators if r["has_avatar"]) | |
| 310 | + # complétude moyenne d'une fiche = moyenne des 4 champs clés remplis | |
| 311 | + completeness = round((_cov(n_bio) + _cov(n_loc) + _cov(n_reach) | |
| 312 | + + _cov(n_avatar)) / 4, 1) if n_active else 0.0 | |
| 313 | + gauges = [ | |
| 314 | + {"id": "multi", "label": "Créateurs multi-plateformes (2 comptes et +)", | |
| 315 | + "value": _cov(n_multi), "max": 100, "unit": "%"}, | |
| 316 | + {"id": "bio", "label": "Fiches avec biographie", "value": _cov(n_bio), | |
| 317 | + "max": 100, "unit": "%"}, | |
| 318 | + {"id": "loc", "label": "Fiches avec ville ou région déclarée", | |
| 319 | + "value": _cov(n_loc), "max": 100, "unit": "%"}, | |
| 320 | + {"id": "reach", "label": "Fiches avec audience connue", | |
| 321 | + "value": _cov(n_reach), "max": 100, "unit": "%"}, | |
| 322 | + {"id": "complete", "label": "Complétude moyenne des fiches " | |
| 323 | + "(bio, lieu, audience, photo)", "value": completeness, | |
| 324 | + "max": 100, "unit": "%"}, | |
| 325 | + ] | |
| 200 | 326 | |
| 201 | 327 | # ---- séries quotidiennes ---- |
| 202 | − day_axis = [p_from + timedelta(days=i) for i in range(span)] | |
| 203 | − pts_added = [{"t": d.isoformat(), "v": adds_by_day.get(d, 0)} for d in day_axis] | |
| 204 | 328 | cmp_added = [{"t": (prev_from + timedelta(days=i)).isoformat(), |
| 205 | 329 | "v": adds_by_day.get(prev_from + timedelta(days=i), 0)} |
| 206 | 330 | for i in range(span)] |
| 207 | − running, pts_cumul = 0, [] | |
| 208 | − before = total_until(p_from - timedelta(days=1)) | |
| 209 | − running = before | |
| 210 | − for d in day_axis: | |
| 211 | − running += adds_by_day.get(d, 0) | |
| 212 | − pts_cumul.append({"t": d.isoformat(), "v": running}) | |
| 213 | 331 | series = [ |
| 214 | 332 | {"id": "added", "title": "Créateurs ajoutés par jour", "unit": "créateurs", |
| 215 | 333 | "kind": "line", "points": pts_added, |
| 216 | 334 | **({"compare": cmp_added} if any(c["v"] for c in cmp_added) else {})}, |
| 217 | 335 | {"id": "cumul", "title": "Taille cumulative du répertoire", |
| 218 | − "unit": "créateurs", "kind": "line", "points": pts_cumul}, | |
| 336 | + "unit": "créateurs", "kind": "area", "points": pts_cumul}, | |
| 219 | 337 | ] |
| 338 | + # portée cumulée découverte (somme des audiences connues des fiches ajoutées) | |
| 339 | + if reach_day: | |
| 340 | + run_r = sum(v for dd, v in reach_day.items() if dd < p_from) | |
| 341 | + pts_reach = [] | |
| 342 | + for d in day_axis: | |
| 343 | + run_r += reach_day.get(d, 0) | |
| 344 | + pts_reach.append({"t": d.isoformat(), "v": run_r}) | |
| 345 | + if any(p["v"] for p in pts_reach): | |
| 346 | + series.append({"id": "reach_cumul", | |
| 347 | + "title": "Portée cumulée découverte (audiences connues)", | |
| 348 | + "unit": "abonnés", "kind": "area", "points": pts_reach}) | |
| 349 | + # journaux de sync : fiches ajoutées + mises à jour par les connecteurs | |
| 350 | + sync_day: dict[date, int] = {} | |
| 351 | + for r in con.execute("SELECT ts, COALESCE(added,0)+COALESCE(updated,0) n " | |
| 352 | + "FROM sync_log").fetchall(): | |
| 353 | + d = _local_date(r["ts"]) | |
| 354 | + if d: | |
| 355 | + sync_day[d] = sync_day.get(d, 0) + r["n"] | |
| 356 | + if sync_day: | |
| 357 | + pts_sync = [{"t": d.isoformat(), "v": sync_day.get(d, 0)} for d in day_axis] | |
| 358 | + if any(p["v"] for p in pts_sync): | |
| 359 | + series.append({"id": "sync", | |
| 360 | + "title": "Fiches ajoutées ou mises à jour par les " | |
| 361 | + "connecteurs (journaux de sync)", | |
| 362 | + "unit": "fiches", "kind": "bar", "points": pts_sync}) | |
| 363 | + | |
| 364 | + # ---- multi-courbes : croissance par plateforme principale (top 4) ---- | |
| 365 | + plat_totals: dict[str, int] = {} | |
| 366 | + for (d, pl), v in plat_day.items(): | |
| 367 | + plat_totals[pl] = plat_totals.get(pl, 0) + v | |
| 368 | + top_plats = [p for p, _ in sorted(plat_totals.items(), key=lambda x: -x[1])[:4]] | |
| 369 | + multiseries = [] | |
| 370 | + if top_plats: | |
| 371 | + mseries = [] | |
| 372 | + for pl in top_plats: | |
| 373 | + run = sum(v for (dd, p2), v in plat_day.items() | |
| 374 | + if p2 == pl and dd < p_from) | |
| 375 | + pts = [] | |
| 376 | + for d in day_axis: | |
| 377 | + run += plat_day.get((d, pl), 0) | |
| 378 | + pts.append({"t": d.isoformat(), "v": run}) | |
| 379 | + mseries.append({"label": PLAT_LBL.get(pl, pl), "points": pts}) | |
| 380 | + if any(pt["v"] for s in mseries for pt in s["points"]): | |
| 381 | + multiseries.append({ | |
| 382 | + "id": "plat_growth", | |
| 383 | + "title": "Croissance du répertoire par plateforme principale (top 4)", | |
| 384 | + "unit": "créateurs", "series": mseries}) | |
| 385 | + | |
| 386 | + # ---- empilé : ajouts par source de découverte (top 5 + autres) ---- | |
| 387 | + stacked = [] | |
| 388 | + if src_day: | |
| 389 | + top_src = [s for s, _ in sorted(src_total.items(), key=lambda x: -x[1])[:5]] | |
| 390 | + keys = top_src + ["Autres"] | |
| 391 | + pts = [] | |
| 392 | + for d in day_axis: | |
| 393 | + vals = [src_day.get((d, s), 0) for s in top_src] | |
| 394 | + other = sum(v for (dd, s), v in src_day.items() | |
| 395 | + if dd == d and s not in top_src) | |
| 396 | + pts.append({"t": d.isoformat(), "values": vals + [other]}) | |
| 397 | + if any(v for pt in pts for v in pt["values"]): | |
| 398 | + stacked.append({"id": "sources", | |
| 399 | + "title": "Créateurs ajoutés par source de découverte", | |
| 400 | + "unit": "créateurs", "keys": keys, "points": pts}) | |
| 401 | + | |
| 402 | + # ---- répartitions (deltas = croissance réelle du stock sur la période) ---- | |
| 403 | + def _growth(total: int, added: int) -> dict: | |
| 404 | + base = total - added | |
| 405 | + p = _pct(total, base) if added else None | |
| 406 | + if p is None: | |
| 407 | + return {} | |
| 408 | + return {"delta_pct": p} | |
| 220 | 409 | |
| 221 | − # ---- répartitions ---- | |
| 222 | 410 | breakdowns = [ |
| 223 | 411 | {"id": "platforms", "title": "Comptes reliés par plateforme", |
| 224 | 412 | "kind": "donut", |
| 225 | 413 | "items": [{"label": PLAT_LBL.get(r["platform"], r["platform"]), |
| 226 | 414 | "value": r["c"]} for r in plat_rows]}, |
| 227 | 415 | {"id": "tiers", "title": "Créateurs par taille d'audience", "kind": "bar", |
| 228 | − "items": [{"label": lbl, "value": tier_total.get(t, 0)} | |
| 416 | + "items": [{"label": lbl, "value": tier_total.get(t, 0), | |
| 417 | + **_growth(tier_total.get(t, 0), tier_period.get(t, 0))} | |
| 229 | 418 | for t, lbl in TIER_LBL if tier_total.get(t)]}, |
| 230 | 419 | {"id": "niches", "title": "Top niches", "kind": "bar", |
| 231 | − "items": [{"label": NICHE_LBL.get(n, n), "value": v} | |
| 420 | + "items": [{"label": NICHE_LBL.get(n, n), "value": v, | |
| 421 | + **_growth(v, niche_period.get(n, 0))} | |
| 232 | 422 | for n, v in sorted(niche_total.items(), key=lambda x: -x[1])[:12]]}, |
| 233 | 423 | ] |
| 234 | − | |
| 424 | + if type_total: | |
| 425 | + breakdowns.append( | |
| 426 | + {"id": "types", "title": "Par type de créateur", "kind": "bar", | |
| 427 | + "items": [{"label": TYPE_LBL.get(t, t), "value": v} | |
| 428 | + for t, v in sorted(type_total.items(), key=lambda x: -x[1])[:10]]}) | |
| 429 | + | |
| 430 | + # ---- distributions ---- | |
| 431 | + distributions = [] | |
| 432 | + reach_vals = [r["total_reach"] for r in creators if r["total_reach"]] | |
| 433 | + if reach_vals: | |
| 434 | + bins = [] | |
| 435 | + for lo, hi, lbl in REACH_BINS: | |
| 436 | + n = sum(1 for v in reach_vals if v >= lo and (hi is None or v < hi)) | |
| 437 | + bins.append({"label": lbl, "value": n}) | |
| 438 | + distributions.append({"id": "audiences", | |
| 439 | + "title": "Distribution des audiences connues " | |
| 440 | + "(abonnés cumulés)", | |
| 441 | + "unit": "créateurs", "bins": bins}) | |
| 442 | + if acc_per_creator: | |
| 443 | + counts: dict[str, int] = {} | |
| 444 | + for r in acc_per_creator: | |
| 445 | + k = "5 et +" if r["np"] >= 5 else str(r["np"]) | |
| 446 | + counts[k] = counts.get(k, 0) + 1 | |
| 447 | + order = ["1", "2", "3", "4", "5 et +"] | |
| 448 | + bins = [{"label": f"{k} compte{'s' if k != '1' else ''}", | |
| 449 | + "value": counts[k]} for k in order if counts.get(k)] | |
| 450 | + distributions.append({"id": "acc_per_creator", | |
| 451 | + "title": "Comptes reliés par créateur", | |
| 452 | + "unit": "créateurs", "bins": bins}) | |
| 453 | + if conf_rows: | |
| 454 | + conf_bins = [(0.0, 0.6, "< 60 %"), (0.6, 0.7, "60 – 70 %"), | |
| 455 | + (0.7, 0.8, "70 – 80 %"), (0.8, 0.9, "80 – 90 %"), | |
| 456 | + (0.9, 1.01, "90 – 100 %")] | |
| 457 | + bins = [] | |
| 458 | + for lo, hi, lbl in conf_bins: | |
| 459 | + n = sum(1 for r in conf_rows if lo <= (r["confidence"] or 0) < hi) | |
| 460 | + bins.append({"label": lbl, "value": n}) | |
| 461 | + if any(b["value"] for b in bins): | |
| 462 | + distributions.append({"id": "confidence", | |
| 463 | + "title": "Confiance du rattachement des comptes", | |
| 464 | + "unit": "comptes", "bins": bins}) | |
| 465 | + | |
| 466 | + # ---- géographie ---- | |
| 235 | 467 | geo = None |
| 236 | 468 | if region_total: |
| 237 | 469 | geo = {"title": "Par région déclarée (quand le créateur la rend publique)", |
| 238 | 470 | "items": [{"label": k, "value": v} for k, v in |
| 239 | 471 | sorted(region_total.items(), key=lambda x: -x[1])]} |
| 240 | 472 | |
| 241 | − # ---- heatmap : ajouts par jour, toute l'historique ---- | |
| 473 | + # ---- heatmaps : calendrier (ajouts/jour) + horaire 7×24 (découvertes) ---- | |
| 242 | 474 | heatmap = {"title": "Ajouts au répertoire", |
| 243 | 475 | "cells": [{"date": d.isoformat(), "value": v} |
| 244 | 476 | for d, v in sorted(adds_by_day.items())]} |
| 477 | + hourly = None | |
| 478 | + if hour_cells: | |
| 479 | + hourly = {"title": "Découvertes de créateurs par jour et heure " | |
| 480 | + "(toute l'historique)", | |
| 481 | + "cells": [{"dow": k[0], "hour": k[1], "value": v} | |
| 482 | + for k, v in sorted(hour_cells.items())]} | |
| 245 | 483 | |
| 246 | 484 | # ---- tableaux ---- |
| 247 | 485 | top = sorted((r for r in creators if r["total_reach"]), |
@@ -259,13 +497,44 @@ def _build(con: sqlite3.Connection, period: str, d_from: str, d_to: str) -> dict | ||
| 259 | 497 | ", ".join(NICHE_LBL.get(n, n) |
| 260 | 498 | for n in (r["niches"] or "").split(",")[:2] if n)] |
| 261 | 499 | for r in top]}) |
| 262 | − n_active = len(creators) | |
| 500 | + if plat_rows: | |
| 501 | + tables.append({ | |
| 502 | + "id": "platforms", "title": "Répartition par plateforme", | |
| 503 | + "columns": ["Plateforme", "Comptes reliés", "Vérifiés", | |
| 504 | + "Abonnés cumulés", "Audience moyenne / compte"], | |
| 505 | + "rows": [[PLAT_LBL.get(r["platform"], r["platform"]), r["c"], | |
| 506 | + r["nverif"] or 0, r["fol"] or 0, | |
| 507 | + int(round((r["fol"] or 0) / r["nfol"])) if r["nfol"] else "—"] | |
| 508 | + for r in plat_rows]}) | |
| 263 | 509 | tables.append({ |
| 264 | 510 | "id": "niches", "title": "Répartition par niche", |
| 265 | 511 | "columns": ["Niche", "Créateurs", "Ajoutés sur la période", "Part"], |
| 266 | 512 | "rows": [[NICHE_LBL.get(n, n), v, niche_period.get(n, 0), |
| 267 | 513 | f"{100 * v / max(1, n_active):.1f} %".replace(".", ",")] |
| 268 | 514 | for n, v in sorted(niche_total.items(), key=lambda x: -x[1])]}) |
| 515 | + # connecteurs & dernière synchro (journaux réels) | |
| 516 | + sync_rows = con.execute( | |
| 517 | + "SELECT source, COUNT(*) runs, SUM(COALESCE(added,0)) a, " | |
| 518 | + "SUM(COALESCE(updated,0)) u, SUM(COALESCE(errors,0)) e, MAX(ts) last " | |
| 519 | + "FROM sync_log GROUP BY source ORDER BY a DESC").fetchall() | |
| 520 | + if sync_rows: | |
| 521 | + def _fmt_ts(ts: str) -> str: | |
| 522 | + dt = _local_dt(ts) | |
| 523 | + return dt.strftime("%Y-%m-%d %H:%M") if dt else (ts or "")[:16] | |
| 524 | + tables.append({ | |
| 525 | + "id": "connectors", "title": "Connecteurs & dernière synchronisation", | |
| 526 | + "columns": ["Connecteur", "Synchros", "Fiches ajoutées", | |
| 527 | + "Mises à jour", "Erreurs", "Dernière synchro (HE)"], | |
| 528 | + "rows": [[r["source"], r["runs"], r["a"], r["u"], r["e"], | |
| 529 | + _fmt_ts(r["last"])] for r in sync_rows]}) | |
| 530 | + if city_total: | |
| 531 | + n_city = sum(city_total.values()) | |
| 532 | + tables.append({ | |
| 533 | + "id": "cities", "title": "Créateurs par ville déclarée", | |
| 534 | + "columns": ["Ville", "Créateurs", "Part des fiches localisées"], | |
| 535 | + "rows": [[c, v, | |
| 536 | + f"{100 * v / max(1, n_city):.1f} %".replace(".", ",")] | |
| 537 | + for c, v in sorted(city_total.items(), key=lambda x: -x[1])[:50]]}) | |
| 269 | 538 | |
| 270 | 539 | # ---- records & faits marquants (générés depuis les données) ---- |
| 271 | 540 | records = [] |
@@ -275,6 +544,14 @@ def _build(con: sqlite3.Connection, period: str, d_from: str, d_to: str) -> dict | ||
| 275 | 544 | records.append({"label": "Jour record d'ajouts (période)", |
| 276 | 545 | "value": f"{_fr_int(best[1])} créateurs", |
| 277 | 546 | "date": best[0].isoformat()}) |
| 547 | + records.append({"label": "Moyenne d'ajouts par jour (période)", | |
| 548 | + "value": f"{added_cur / span:.1f} créateurs".replace(".", ",")}) | |
| 549 | + if adds_by_day: | |
| 550 | + best_all = max(adds_by_day.items(), key=lambda x: x[1]) | |
| 551 | + if not in_period or best_all[0] not in in_period: | |
| 552 | + records.append({"label": "Jour record d'ajouts (toute l'historique)", | |
| 553 | + "value": f"{_fr_int(best_all[1])} créateurs", | |
| 554 | + "date": best_all[0].isoformat()}) | |
| 278 | 555 | if niche_period: |
| 279 | 556 | bn = max(niche_period.items(), key=lambda x: x[1]) |
| 280 | 557 | records.append({"label": "Niche la plus dynamique (ajouts sur la période)", |
@@ -287,31 +564,54 @@ def _build(con: sqlite3.Connection, period: str, d_from: str, d_to: str) -> dict | ||
| 287 | 564 | records.append({"label": "Plus grande portée connue", |
| 288 | 565 | "value": f"{top[0]['display_name']} — " |
| 289 | 566 | f"{_fr_int(top[0]['total_reach'])} abonnés"}) |
| 567 | + if acc_per_creator: | |
| 568 | + bm = max(acc_per_creator, key=lambda r: r["np"]) | |
| 569 | + if bm["np"] >= 2: | |
| 570 | + records.append({"label": "Créateur le plus multi-plateforme", | |
| 571 | + "value": f"{bm['display_name']} — {bm['np']} plateformes"}) | |
| 572 | + if src_total: | |
| 573 | + bs = max(src_total.items(), key=lambda x: x[1]) | |
| 574 | + records.append({"label": "Source de découverte la plus productive", | |
| 575 | + "value": f"{bs[0]} — {_fr_int(bs[1])} créateurs"}) | |
| 576 | + if region_total: | |
| 577 | + br = max(region_total.items(), key=lambda x: x[1]) | |
| 578 | + records.append({"label": "Région la plus représentée (déclarée)", | |
| 579 | + "value": f"{br[0]} — {_fr_int(br[1])} créateurs"}) | |
| 580 | + if min_day: | |
| 581 | + records.append({"label": "Première fiche au répertoire", | |
| 582 | + "value": "ouverture du répertoire", | |
| 583 | + "date": min_day.isoformat()}) | |
| 290 | 584 | last_sync = con.execute( |
| 291 | 585 | "SELECT ts FROM sync_log ORDER BY id DESC LIMIT 1").fetchone() |
| 292 | 586 | if last_sync and last_sync["ts"]: |
| 293 | − try: | |
| 294 | − dt = datetime.strptime(last_sync["ts"][:19], "%Y-%m-%dT%H:%M:%S") \ | |
| 295 | − .replace(tzinfo=timezone.utc).astimezone(TZ) | |
| 587 | + dt = _local_dt(last_sync["ts"]) | |
| 588 | + if dt: | |
| 296 | 589 | records.append({"label": "Dernière synchronisation des connecteurs", |
| 297 | 590 | "value": dt.strftime("%H:%M (heure de l'Est)"), |
| 298 | 591 | "date": dt.date().isoformat()}) |
| 299 | − except ValueError: | |
| 300 | − pass | |
| 301 | 592 | |
| 302 | 593 | out = { |
| 303 | 594 | "updated": datetime.now(TZ).isoformat(timespec="seconds"), |
| 304 | 595 | "period": {"from": p_from.isoformat(), "to": p_to.isoformat(), |
| 305 | 596 | "label": p_label}, |
| 306 | 597 | "kpis": kpis, |
| 598 | + "gauges": gauges, | |
| 307 | 599 | "series": series, |
| 308 | 600 | "breakdowns": breakdowns, |
| 309 | 601 | "heatmap": heatmap, |
| 310 | 602 | "tables": tables, |
| 311 | − "records": records, | |
| 603 | + "records": records[:12], | |
| 312 | 604 | } |
| 605 | + if multiseries: | |
| 606 | + out["multiseries"] = multiseries | |
| 607 | + if stacked: | |
| 608 | + out["stacked"] = stacked | |
| 609 | + if distributions: | |
| 610 | + out["distributions"] = distributions | |
| 313 | 611 | if geo: |
| 314 | 612 | out["geo"] = geo |
| 613 | + if hourly: | |
| 614 | + out["hourly"] = hourly | |
| 315 | 615 | return out |
| 316 | 616 | |
| 317 | 617 | |
modified
creaka/web.py
+6 −4
@@ -102,16 +102,18 @@ def stats_dashboard(period: str = "30j", | ||
| 102 | 102 | def stats_report(period: str = "30j", mode: str = "complet", |
| 103 | 103 | date_from: str = Query("", alias="from"), |
| 104 | 104 | date_to: str = Query("", alias="to")): |
| 105 | − """Rapport PDF estampillé Groupe-KA (complet ou synthèse 2 pages).""" | |
| 106 | − if mode not in ("complet", "synthese"): | |
| 107 | − raise HTTPException(400, "mode invalide (complet|synthese)") | |
| 105 | + """Rapport PDF estampillé Groupe-KA — 5 modes (contrat ka-stats SPEC §3) : | |
| 106 | + complet | synthese | tendances | repartitions | donnees. | |
| 107 | + Un mode inconnu retombe sur `complet` (rétrocompatible v1).""" | |
| 108 | + if mode not in kapdf.REPORT_MODES: | |
| 109 | + mode = "complet" | |
| 108 | 110 | if period not in _PERIODS_OK and not (date_from and date_to): |
| 109 | 111 | raise HTTPException(400, "période inconnue") |
| 110 | 112 | dash = stats_mod.dashboard(_db(), period=period, |
| 111 | 113 | date_from=date_from, date_to=date_to) |
| 112 | 114 | pdf = kapdf.GroupeKAReport(site=stats_mod.site_info(), |
| 113 | 115 | dashboard=dash, mode=mode).build() |
| 114 | − fname = kapdf.filename("crea-ka", period) | |
| 116 | + fname = kapdf.filename("crea-ka", period, mode) | |
| 115 | 117 | return Response(content=pdf, media_type="application/pdf", |
| 116 | 118 | headers={"Content-Disposition": |
| 117 | 119 | f'attachment; filename="{fname}"'}) |
modified
frontend/dist/index.html
+251 −24
@@ -810,11 +810,6 @@ select.f.active{background-color:var(--accent-soft);color:var(--ink);border-colo | ||
| 810 | 810 | .filters::-webkit-scrollbar{display:none} |
| 811 | 811 | select.f{flex:none;font-size:16px;padding:8px 30px 8px 13px} |
| 812 | 812 | } |
| 813 | −/* Anti-zoom iOS jusqu'au breakpoint tabbar (940 px) : champs >= 16 px | |
| 814 | − (filet global : tokens.css force aussi 16 px au doigt) */ | |
| 815 | −@media(max-width:940px){.search-input input,select.f{font-size:16px}} | |
| 816 | −/* Cible tactile >= 44 px du logo (112×26 rendus) : zone étendue invisible */ | |
| 817 | −@media(pointer:coarse){.brand{position:relative}.brand::after{content:"";position:absolute;inset:-8px}} | |
| 818 | 813 | |
| 819 | 814 | /* ===== grille créateurs ===== */ |
| 820 | 815 | .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:18px;padding:24px 0 10px} |
@@ -1093,6 +1088,36 @@ select.f.active{background-color:var(--accent-soft);color:var(--ink);border-colo | ||
| 1093 | 1088 | background:var(--surface-2);padding:20px} |
| 1094 | 1089 | .stats-sect{font-size:17px;text-transform:uppercase;margin:34px 0 14px} |
| 1095 | 1090 | |
| 1091 | +/* ===== page stats v2 : sparklines, jauges, histogrammes, heatmap horaire, menu PDF ===== */ | |
| 1092 | +.tile svg.spark{display:block;margin-top:9px;width:100%;height:28px} | |
| 1093 | +.gauges{display:grid;grid-template-columns:repeat(auto-fit,minmax(168px,1fr));gap:14px;margin-bottom:8px} | |
| 1094 | +.gauge{background:var(--surface);border:1.5px solid var(--ink);border-radius:var(--r-card); | |
| 1095 | + padding:16px 14px 13px;box-shadow:var(--shadow-off-soft);text-align:center} | |
| 1096 | +.gauge svg{width:124px;max-width:100%;height:auto;margin:0 auto;display:block} | |
| 1097 | +.gauge .g-v{font-family:var(--font-display);font-weight:700;font-size:21px;color:var(--ink);margin-top:-30px} | |
| 1098 | +.gauge .g-l{font-family:var(--font-mono);font-size:9px;font-weight:700;text-transform:uppercase; | |
| 1099 | + letter-spacing:.05em;color:var(--ink-3);margin-top:10px;line-height:1.55} | |
| 1100 | +.statsum{display:flex;gap:7px;flex-wrap:wrap;margin-top:10px} | |
| 1101 | +.statsum .chip b{font-family:var(--font-mono);margin-left:4px} | |
| 1102 | +.leg-swatch.ml1{border-top:3px solid var(--ink)} | |
| 1103 | +.leg-swatch.ml2{border-top:3px dashed var(--accent)} | |
| 1104 | +.leg-swatch.ml3{border-top:3px dotted var(--ink-3)} | |
| 1105 | +.hrow .d{flex:none;font-family:var(--font-mono);font-size:10px;font-weight:700;min-width:54px;text-align:right} | |
| 1106 | +.hrow .d.up{color:var(--green)}.hrow .d.down{color:var(--danger)} | |
| 1107 | +.hh svg{min-width:560px;width:100%;height:auto} | |
| 1108 | +.pdf-menu-wrap{position:relative;display:inline-flex;gap:8px;flex-wrap:wrap} | |
| 1109 | +.pdf-menu{position:absolute;right:0;top:calc(100% + 8px);z-index:70;background:var(--surface); | |
| 1110 | + border:1.5px solid var(--ink);border-radius:var(--r-card);box-shadow:var(--shadow-off); | |
| 1111 | + display:none;min-width:270px;padding:6px} | |
| 1112 | +.pdf-menu.open{display:block} | |
| 1113 | +.pdf-menu button{display:block;width:100%;text-align:left;border:0;background:none; | |
| 1114 | + padding:11px 13px;border-radius:9px;font-family:var(--font-display);font-weight:700; | |
| 1115 | + font-size:13px;color:var(--ink);min-height:44px} | |
| 1116 | +.pdf-menu button:hover{background:var(--accent-soft)} | |
| 1117 | +.pdf-menu small{display:block;font-family:var(--font-body);font-weight:400;font-size:11px; | |
| 1118 | + color:var(--ink-3);margin-top:2px} | |
| 1119 | +@media(max-width:760px){.pdf-menu{right:auto;left:0}} | |
| 1120 | + | |
| 1096 | 1121 | /* ===== retrait ===== */ |
| 1097 | 1122 | .optout-page{max-width:620px;margin:0 auto;padding:44px 0 70px} |
| 1098 | 1123 | .optout-page h1{font-size:clamp(26px,4vw,32px);margin:12px 0;text-transform:uppercase} |
@@ -1609,6 +1634,15 @@ const fmtPct=v=>(v>=0?"+":"")+v.toLocaleString("fr-CA",{maximumFractionDigits:1} | ||
| 1609 | 1634 | const emptyBlock=t=>`<div class="empty-block"><b style="font-family:var(--font-display);font-size:14px">${esc(t)}</b> |
| 1610 | 1635 | <p class="klabel" style="margin:6px 0 0">Pas encore mesuré — aucune donnée disponible pour cette période.</p></div>`; |
| 1611 | 1636 | |
| 1637 | +/* mini-tendance dans une carte KPI (série spark du contrat v2) */ | |
| 1638 | +function sparkSvg(spark,hero){ | |
| 1639 | + if(!spark||spark.length<2)return""; | |
| 1640 | + const W=120,H=28,vs=spark.map(p=>p.v); | |
| 1641 | + const mn=Math.min(...vs),mx=Math.max(...vs),rng=(mx-mn)||1; | |
| 1642 | + const pts=spark.map((p,i)=>`${(i/(spark.length-1)*W).toFixed(1)},${(H-2-(H-4)*((p.v-mn)/rng)).toFixed(1)}`).join(" "); | |
| 1643 | + return `<svg class="spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" aria-hidden="true"> | |
| 1644 | + <polyline points="${pts}" fill="none" stroke="${hero?"var(--accent-soft)":"var(--accent)"}" stroke-width="2"/></svg>`; | |
| 1645 | +} | |
| 1612 | 1646 | function kpiHtml(k,i){ |
| 1613 | 1647 | const v=k.value,hero=i===0; |
| 1614 | 1648 | const num=typeof v==="number"?(v>=1e6?fmt.format(v):fmtFull.format(v)):esc(v); |
@@ -1618,7 +1652,167 @@ function kpiHtml(k,i){ | ||
| 1618 | 1652 | delta=`<div class="tile-d ${up?"up":"down"}">${up?"▲":"▼"} ${fmtPct(k.delta_pct)} <span style="opacity:.6">vs période préc.</span></div>`;} |
| 1619 | 1653 | return `<div class="tile${hero?" hero-tile":""}"${typeof v==="number"?` title="${fmtFull.format(v)}"`:""}> |
| 1620 | 1654 | <div class="tile-v">${num}${k.unit?`<span style="font-size:.42em;opacity:.6"> ${esc(k.unit)}</span>`:""}</div> |
| 1621 | − <div class="tile-k">${esc(k.label)}</div>${delta}</div>`; | |
| 1655 | + <div class="tile-k">${esc(k.label)}</div>${delta}${sparkSvg(k.spark,hero)}</div>`; | |
| 1656 | +} | |
| 1657 | + | |
| 1658 | +/* --- jauge demi-arc (taux, couvertures, complétude) --- */ | |
| 1659 | +function gaugeHtml(g){ | |
| 1660 | + if(typeof g.value!=="number"||!g.max)return""; | |
| 1661 | + const frac=Math.max(0,Math.min(1,g.value/g.max)); | |
| 1662 | + const R=52,C=Math.PI*R; | |
| 1663 | + return `<div class="gauge" title="${esc(g.label)} — ${g.value.toLocaleString("fr-CA")}${g.unit?" "+esc(g.unit):""} (${Math.round(frac*100)} % de ${fmtFull.format(g.max)})"> | |
| 1664 | + <svg viewBox="0 0 120 68" role="img" aria-label="${esc(g.label)}"> | |
| 1665 | + <path d="M8 60 A${R} ${R} 0 0 1 112 60" fill="none" stroke="var(--line)" stroke-width="11" stroke-linecap="round"/> | |
| 1666 | + ${frac>0?`<path d="M8 60 A${R} ${R} 0 0 1 112 60" fill="none" stroke="var(--accent)" stroke-width="11" stroke-linecap="round" | |
| 1667 | + stroke-dasharray="${(frac*C).toFixed(1)} ${(C+20).toFixed(1)}"/>`:""} | |
| 1668 | + </svg> | |
| 1669 | + <div class="g-v">${g.value.toLocaleString("fr-CA",{maximumFractionDigits:1})}${g.unit?`<span style="font-size:.58em;opacity:.65"> ${esc(g.unit)}</span>`:""}</div> | |
| 1670 | + <div class="g-l">${esc(g.label)}</div></div>`; | |
| 1671 | +} | |
| 1672 | + | |
| 1673 | +/* --- statistiques d'une série : min / max / moyenne / médiane / écart-type --- */ | |
| 1674 | +function statSummary(s){ | |
| 1675 | + const vs=(s.points||[]).map(p=>p.v).filter(v=>typeof v==="number"); | |
| 1676 | + if(vs.length<2)return""; | |
| 1677 | + const sv=[...vs].sort((a,b)=>a-b),mean=vs.reduce((a,b)=>a+b,0)/vs.length; | |
| 1678 | + const med=sv[Math.floor(sv.length/2)]; | |
| 1679 | + const sd=Math.sqrt(vs.reduce((a,v)=>a+(v-mean)*(v-mean),0)/vs.length); | |
| 1680 | + const f=v=>fmtFull.format(Math.round(v*100)/100); | |
| 1681 | + return `<div class="statsum"><span class="chip">min<b>${f(sv[0])}</b></span> | |
| 1682 | + <span class="chip">max<b>${f(sv[sv.length-1])}</b></span> | |
| 1683 | + <span class="chip">moyenne<b>${f(mean)}</b></span> | |
| 1684 | + <span class="chip">médiane<b>${f(med)}</b></span> | |
| 1685 | + <span class="chip">écart-type σ<b>${f(sd)}</b></span></div>`; | |
| 1686 | +} | |
| 1687 | + | |
| 1688 | +/* --- barres verticales : série kind=bar (volumes/jour) & histogrammes (bins) --- */ | |
| 1689 | +function vbarsHtml(spec){ | |
| 1690 | + const pts=(spec.points||(spec.bins||[]).map(b=>({t:b.label,v:b.value}))) | |
| 1691 | + .filter(p=>typeof p.v==="number"); | |
| 1692 | + if(!pts.length||!pts.some(p=>p.v>0))return emptyBlock(spec.title); | |
| 1693 | + const W=720,H=250,PL=54,PR=12,PT=14,PB=40,cw=W-PL-PR,ch=H-PT-PB; | |
| 1694 | + const vmax=Math.max(...pts.map(p=>p.v),1); | |
| 1695 | + let grid=""; | |
| 1696 | + for(let k=0;k<5;k++){const y=PT+ch*k/4,v=vmax*(4-k)/4; | |
| 1697 | + grid+=`<line x1="${PL}" x2="${W-PR}" y1="${y.toFixed(1)}" y2="${y.toFixed(1)}" stroke="var(--line)"/> | |
| 1698 | + <text x="${PL-6}" y="${(y+3).toFixed(1)}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${fmtFull.format(Math.round(v))}</text>`;} | |
| 1699 | + const n=pts.length,bw=Math.max(2,cw/n-3); | |
| 1700 | + const bars=pts.map((p,i)=>{const bh=ch*p.v/vmax,x=PL+cw*i/n+1.5; | |
| 1701 | + return `<rect x="${x.toFixed(1)}" y="${(PT+ch-bh).toFixed(1)}" width="${bw.toFixed(1)}" height="${Math.max(bh,p.v>0?1:0).toFixed(1)}" | |
| 1702 | + fill="var(--accent)" stroke="var(--ink)" stroke-width="${n>40?0.4:1}"><title>${esc(p.t)} — ${fmtFull.format(p.v)}${spec.unit?" "+esc(spec.unit):""}</title></rect>`;}).join(""); | |
| 1703 | + const lblIdx=n<=10?pts.map((_,i)=>i):[0,Math.floor(n/2),n-1]; | |
| 1704 | + const xl=lblIdx.map(i=>`<text x="${(PL+cw*i/n+bw/2).toFixed(1)}" y="${H-8}" text-anchor="middle" | |
| 1705 | + font-size="${n<=10?10:10}" fill="var(--ink-3)" font-family="var(--font-mono)">${esc(String(pts[i].t))}</text>`).join(""); | |
| 1706 | + return `<div class="viz-card"><h2>${esc(spec.title)}</h2> | |
| 1707 | + ${spec.unit?`<div class="viz-sub">${esc(spec.unit)}</div>`:'<div style="height:10px"></div>'} | |
| 1708 | + <svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(spec.title)}">${grid}${bars}${xl}</svg></div>`; | |
| 1709 | +} | |
| 1710 | + | |
| 1711 | +/* --- multi-courbes (≤ 4) : identité par MOTIF de trait en plus de la couleur --- */ | |
| 1712 | +const ML_STYLES=[ | |
| 1713 | + {stroke:"var(--accent)",w:2.6,dash:"",cls:"",name:"trait plein accent"}, | |
| 1714 | + {stroke:"var(--ink)",w:2,dash:"",cls:"ml1",name:"trait plein encre"}, | |
| 1715 | + {stroke:"var(--accent)",w:2.2,dash:"7 4",cls:"ml2",name:"tirets accent"}, | |
| 1716 | + {stroke:"var(--ink-3)",w:2,dash:"2 3",cls:"ml3",name:"pointillé gris"}]; | |
| 1717 | +function multiFigure(ms,hide){ | |
| 1718 | + const series=(ms.series||[]).filter(s=>(s.points||[]).length>1).slice(0,4); | |
| 1719 | + if(!series.length)return emptyBlock(ms.title); | |
| 1720 | + const W=720,H=250,PL=54,PR=12,PT=14,PB=26,cw=W-PL-PR,ch=H-PT-PB; | |
| 1721 | + const shown=series.filter((_,i)=>!hide[i]); | |
| 1722 | + const all=(shown.length?shown:series).flatMap(s=>s.points.map(p=>p.v)); | |
| 1723 | + const vmax=Math.max(...all,1),vmin=Math.min(0,...all),rng=(vmax-vmin)||1; | |
| 1724 | + let grid=""; | |
| 1725 | + for(let k=0;k<5;k++){const y=PT+ch*k/4,v=vmax-(vmax-vmin)*k/4; | |
| 1726 | + grid+=`<line x1="${PL}" x2="${W-PR}" y1="${y.toFixed(1)}" y2="${y.toFixed(1)}" stroke="var(--line)"/> | |
| 1727 | + <text x="${PL-6}" y="${(y+3).toFixed(1)}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${fmtFull.format(Math.round(v))}</text>`;} | |
| 1728 | + const X=(i,n)=>PL+cw*i/((n-1)||1),Y=v=>PT+ch*(1-(v-vmin)/rng); | |
| 1729 | + const paths=series.map((s,si)=>{if(hide[si])return""; | |
| 1730 | + const st=ML_STYLES[si]; | |
| 1731 | + const d=s.points.map((p,i)=>`${i?"L":"M"}${X(i,s.points.length).toFixed(1)},${Y(p.v).toFixed(1)}`).join(""); | |
| 1732 | + return `<path d="${d}" fill="none" stroke="${st.stroke}" stroke-width="${st.w}"${st.dash?` stroke-dasharray="${st.dash}"`:""}/>`;}).join(""); | |
| 1733 | + const ref=series[0].points; | |
| 1734 | + const xl=[0,Math.floor(ref.length/2),ref.length-1].map(i=> | |
| 1735 | + `<text x="${X(i,ref.length).toFixed(1)}" y="${H-8}" text-anchor="middle" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${esc(ref[i].t)}</text>`).join(""); | |
| 1736 | + const leg=series.map((s,si)=>`<button type="button" class="leg-btn" data-mls="${si}" aria-pressed="${!hide[si]}" | |
| 1737 | + title="${ML_STYLES[si].name}"><span class="leg-swatch ${ML_STYLES[si].cls}"></span>${esc(s.label)}</button>`).join(""); | |
| 1738 | + return `<div class="viz-card"> | |
| 1739 | + <div style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px;align-items:center"> | |
| 1740 | + <h2>${esc(ms.title)}</h2><span class="lc-legend">${leg}</span></div> | |
| 1741 | + <svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(ms.title)}" style="margin-top:10px"> | |
| 1742 | + ${grid}${xl}${paths} | |
| 1743 | + <g class="lc-cursor" style="display:none"><line y1="${PT}" y2="${H-PB}" stroke="var(--ink)" stroke-dasharray="2 3"/></g> | |
| 1744 | + </svg><span class="chip lc-tip"> </span></div>`; | |
| 1745 | +} | |
| 1746 | +function mountMulti(el,ms){ | |
| 1747 | + const hide=ST.hide["ml:"+ms.id]||(ST.hide["ml:"+ms.id]={}); | |
| 1748 | + const series=(ms.series||[]).filter(s=>(s.points||[]).length>1).slice(0,4); | |
| 1749 | + const render=()=>{ | |
| 1750 | + el.innerHTML=multiFigure(ms,hide); | |
| 1751 | + el.querySelectorAll("[data-mls]").forEach(b=>b.addEventListener("click",()=>{ | |
| 1752 | + hide[b.dataset.mls]=!hide[b.dataset.mls];render();})); | |
| 1753 | + const svg=el.querySelector("svg");if(!svg||!series.length)return; | |
| 1754 | + const W=720,PL=54,PR=12,n=series[0].points.length; | |
| 1755 | + const cursor=el.querySelector(".lc-cursor"),tip=el.querySelector(".lc-tip"); | |
| 1756 | + const cl=cursor?cursor.querySelector("line"):null; | |
| 1757 | + svg.addEventListener("pointermove",e=>{ | |
| 1758 | + const r=svg.getBoundingClientRect(); | |
| 1759 | + const fx=(e.clientX-r.left)/r.width*W; | |
| 1760 | + let i=Math.round((fx-PL)/(W-PL-PR)*(n-1));i=Math.max(0,Math.min(n-1,i)); | |
| 1761 | + const x=(PL+(W-PL-PR)*i/((n-1)||1)).toFixed(1); | |
| 1762 | + if(cl){cl.setAttribute("x1",x);cl.setAttribute("x2",x);cursor.style.display="";} | |
| 1763 | + const vals=series.map((s,si)=>hide[si]?null:`${esc(s.label)} : <b> ${fmtFull.format((s.points[i]||{}).v??0)}</b>`).filter(Boolean).join(" · "); | |
| 1764 | + tip.innerHTML=`${esc(series[0].points[i].t)} — ${vals}${ms.unit?` <span style="color:var(--ink-3)">${esc(ms.unit)}</span>`:""}`; | |
| 1765 | + tip.style.visibility="visible";}); | |
| 1766 | + svg.addEventListener("pointerleave",()=>{if(cursor)cursor.style.display="none";tip.style.visibility="hidden"}); | |
| 1767 | + }; | |
| 1768 | + render(); | |
| 1769 | +} | |
| 1770 | + | |
| 1771 | +/* --- barres empilées (composition dans le temps, nuances d'accent) --- */ | |
| 1772 | +function stackedHtml(st){ | |
| 1773 | + const keys=(st.keys||[]).slice(0,6),pts=st.points||[]; | |
| 1774 | + if(!keys.length||!pts.length)return emptyBlock(st.title); | |
| 1775 | + const totals=pts.map(p=>(p.values||[]).slice(0,keys.length).reduce((a,b)=>a+(b||0),0)); | |
| 1776 | + if(!totals.some(t=>t>0))return emptyBlock(st.title); | |
| 1777 | + const W=720,H=250,PL=54,PR=12,PT=14,PB=26,cw=W-PL-PR,ch=H-PT-PB; | |
| 1778 | + const vmax=Math.max(...totals,1),shades=[1,.78,.58,.42,.3,.22]; | |
| 1779 | + let grid=""; | |
| 1780 | + for(let k=0;k<5;k++){const y=PT+ch*k/4,v=vmax*(4-k)/4; | |
| 1781 | + grid+=`<line x1="${PL}" x2="${W-PR}" y1="${y.toFixed(1)}" y2="${y.toFixed(1)}" stroke="var(--line)"/> | |
| 1782 | + <text x="${PL-6}" y="${(y+3).toFixed(1)}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${fmtFull.format(Math.round(v))}</text>`;} | |
| 1783 | + const n=pts.length,bw=Math.max(2,cw/n-3); | |
| 1784 | + const bars=pts.map((p,i)=>{let y=PT+ch;const x=PL+cw*i/n+1.5; | |
| 1785 | + return keys.map((k,j)=>{const v=(p.values||[])[j]||0;if(!v)return""; | |
| 1786 | + const bh=ch*v/vmax;y-=bh; | |
| 1787 | + return `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${bw.toFixed(1)}" height="${Math.max(bh-.4,.5).toFixed(1)}" | |
| 1788 | + fill="var(--accent)" fill-opacity="${shades[j%6]}" stroke="var(--paper)" stroke-width="0.4"> | |
| 1789 | + <title>${esc(p.t)} · ${esc(k)} — ${fmtFull.format(v)}${st.unit?" "+esc(st.unit):""} (total ${fmtFull.format(totals[i])})</title></rect>`;}).join("");}).join(""); | |
| 1790 | + const lblIdx=[0,Math.floor(n/2),n-1]; | |
| 1791 | + const xl=lblIdx.map(i=>`<text x="${(PL+cw*i/n+bw/2).toFixed(1)}" y="${H-8}" text-anchor="middle" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${esc(String(pts[i].t))}</text>`).join(""); | |
| 1792 | + const leg=keys.map((k,j)=>`<span class="leg-btn" style="min-height:auto"><span class="dsw" style="width:11px;height:11px;border-radius:3px;border:1px solid var(--ink);background:var(--accent);opacity:${shades[j%6]};display:inline-block"></span> ${esc(k)}</span>`).join(""); | |
| 1793 | + return `<div class="viz-card"> | |
| 1794 | + <div style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px;align-items:center"> | |
| 1795 | + <h2>${esc(st.title)}</h2><span class="lc-legend">${leg}</span></div> | |
| 1796 | + <svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(st.title)}" style="margin-top:10px">${grid}${bars}${xl}</svg></div>`; | |
| 1797 | +} | |
| 1798 | + | |
| 1799 | +/* --- heatmap horaire 7 × 24 (dow 0=lun … 6=dim) --- */ | |
| 1800 | +function hourHeatHtml(h){ | |
| 1801 | + const cells=h&&h.cells||[]; | |
| 1802 | + if(!cells.length)return emptyBlock(h?h.title:"Activité horaire"); | |
| 1803 | + const grid=new Map(cells.map(c=>[c.dow+":"+c.hour,c.value||0])); | |
| 1804 | + const max=Math.max(...cells.map(c=>c.value||0),1); | |
| 1805 | + const CS=22,LX=42,LY=18,DOWS=["Lun","Mar","Mer","Jeu","Ven","Sam","Dim"]; | |
| 1806 | + let out=""; | |
| 1807 | + [0,6,12,18,23].forEach(hh=>{out+=`<text x="${LX+hh*CS+CS/2}" y="12" text-anchor="middle" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${hh} h</text>`;}); | |
| 1808 | + for(let d=0;d<7;d++){ | |
| 1809 | + out+=`<text x="${LX-6}" y="${LY+d*CS+CS/2+3.5}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${DOWS[d]}</text>`; | |
| 1810 | + for(let hh=0;hh<24;hh++){const v=grid.get(d+":"+hh)||0; | |
| 1811 | + out+=`<rect x="${LX+hh*CS}" y="${LY+d*CS}" width="${CS-2.5}" height="${CS-2.5}" rx="3.5" | |
| 1812 | + fill="${v?"var(--accent)":"rgba(20,24,20,0.06)"}" fill-opacity="${v?(0.2+0.8*v/max).toFixed(2):1}" | |
| 1813 | + stroke="rgba(20,24,20,0.14)" stroke-width="0.5"><title>${DOWS[d]} ${hh} h — ${fmtFull.format(v)}</title></rect>`;}} | |
| 1814 | + return `<div class="viz-card hh"><h2>${esc(h.title)}</h2><div class="viz-sub">7 jours × 24 heures (heure de l'Est)</div> | |
| 1815 | + <div class="tbl-wrap"><svg viewBox="0 0 ${LX+24*CS} ${LY+7*CS}" role="img" aria-label="${esc(h.title)}">${out}</svg></div></div>`; | |
| 1622 | 1816 | } |
| 1623 | 1817 | |
| 1624 | 1818 | /* --- courbe SVG : infobulle (pointeur), légende cliquable, comparaison N-1 --- */ |
@@ -1651,14 +1845,16 @@ function lineFigure(s,hide){ | ||
| 1651 | 1845 | <svg viewBox="0 0 ${g.W} ${g.H}" role="img" aria-label="${esc(s.title)}" style="margin-top:10px"> |
| 1652 | 1846 | ${grid}${xl} |
| 1653 | 1847 | ${!hide.cmp&&s.compare&&s.compare.length>1?`<path d="${path(s.compare)}" fill="none" stroke="var(--ink-3)" stroke-width="1.4" stroke-dasharray="4 4"/>`:""} |
| 1848 | + ${!hide.cur&&s.kind==="area"?`<path d="${path(pts)} L${X(pts.length-1).toFixed(1)},${(H-PB).toFixed(1)} L${X(0).toFixed(1)},${(H-PB).toFixed(1)} Z" fill="var(--accent)" fill-opacity=".12" stroke="none"/>`:""} | |
| 1654 | 1849 | ${!hide.cur?`<path d="${path(pts)}" fill="none" stroke="var(--accent)" stroke-width="2.4"/>`:""} |
| 1655 | 1850 | <g class="lc-cursor" style="display:none"> |
| 1656 | 1851 | <line y1="${PT}" y2="${H-PB}" stroke="var(--ink)" stroke-dasharray="2 3"/> |
| 1657 | 1852 | <circle r="4" fill="var(--accent)" stroke="var(--ink)" stroke-width="1.5"/></g> |
| 1658 | − </svg><span class="chip lc-tip"> </span>`+ | |
| 1853 | + </svg><span class="chip lc-tip"> </span>`+statSummary(s)+ | |
| 1659 | 1854 | `</div>`; |
| 1660 | 1855 | } |
| 1661 | 1856 | function mountLine(el,s){ |
| 1857 | + if(s.kind==="bar"){el.innerHTML=vbarsHtml(s);return;} | |
| 1662 | 1858 | const hide=ST.hide[s.id]||(ST.hide[s.id]={cur:false,cmp:false}); |
| 1663 | 1859 | const render=()=>{ |
| 1664 | 1860 | el.innerHTML=lineFigure(s,hide); |
@@ -1712,10 +1908,10 @@ function barsHtml(title,items,sub){ | ||
| 1712 | 1908 | if(!rows.length)return emptyBlock(title); |
| 1713 | 1909 | const max=Math.max(...rows.map(r=>r.value),1); |
| 1714 | 1910 | return `<div class="viz-card"><h2>${esc(title)}</h2>${sub?`<div class="viz-sub">${esc(sub)}</div>`:`<div style="height:14px"></div>`} |
| 1715 | − ${rows.map(r=>`<div class="hrow" title="${esc(r.label)} — ${fmtFull.format(r.value)}"> | |
| 1911 | + ${rows.map(r=>`<div class="hrow" title="${esc(r.label)} — ${fmtFull.format(r.value)}${r.delta_pct!=null?` (${fmtPct(r.delta_pct)} sur la période)`:""}"> | |
| 1716 | 1912 | <span class="hrow-label">${esc(r.label)}</span> |
| 1717 | 1913 | <span class="hbar"><i style="width:${Math.max(2,Math.round(r.value/max*100))}%"></i></span> |
| 1718 | − <span class="n">${fmtFull.format(r.value)}</span></div>`).join("")}</div>`; | |
| 1914 | + <span class="n">${fmtFull.format(r.value)}</span>${r.delta_pct!=null?`<span class="d ${r.delta_pct>=0?"up":"down"}">${r.delta_pct>=0?"▲":"▼"} ${fmtPct(r.delta_pct)}</span>`:""}</div>`).join("")}</div>`; | |
| 1719 | 1915 | } |
| 1720 | 1916 | |
| 1721 | 1917 | /* --- calendrier de chaleur (26 dernières semaines) --- */ |
@@ -1796,22 +1992,43 @@ function bindPeriod(){ | ||
| 1796 | 1992 | const go=()=>{if(pf.value&&pt.value){ST.from=pf.value;ST.to=pt.value;loadStatsData();}}; |
| 1797 | 1993 | pf.addEventListener("change",go);pt.addEventListener("change",go); |
| 1798 | 1994 | } |
| 1995 | +/* --- menu PDF : 5 rapports (équivalent vanilla du PdfButton v2) --- */ | |
| 1996 | +const PDF_MODES=[ | |
| 1997 | + ["synthese","Synthèse exécutive","Couverture, KPI, jauges & records (2-3 p.)"], | |
| 1998 | + ["tendances","Tendances & évolution","Toutes les séries + min/max/moy/méd/σ"], | |
| 1999 | + ["repartitions","Répartitions & géographie","Anneaux, distributions, géo, activité horaire"], | |
| 2000 | + ["donnees","Données détaillées","Tous les tableaux en version longue (400 lignes)"]]; | |
| 2001 | +function pdfActionsHtml(){ | |
| 2002 | + return `<span class="pdf-actions pdf-menu-wrap"> | |
| 2003 | + <button type="button" class="btn btn-primary" data-pdf="complet">⬇ Rapport PDF complet</button> | |
| 2004 | + <button type="button" class="btn btn-ghost" id="pdf-more" aria-haspopup="true" aria-expanded="false">Autres rapports ▾</button> | |
| 2005 | + <div class="pdf-menu" id="pdf-menu" role="menu"> | |
| 2006 | + ${PDF_MODES.map(([m,l,d])=>`<button type="button" role="menuitem" data-pdf="${m}">${l}<small>${d}</small></button>`).join("")} | |
| 2007 | + </div></span>`; | |
| 2008 | +} | |
| 1799 | 2009 | function bindPdf(){ |
| 1800 | 2010 | const url=m=>{const p=new URLSearchParams({period:ST.period,mode:m}); |
| 1801 | 2011 | if(ST.from&&ST.to){p.set("from",ST.from);p.set("to",ST.to);} |
| 1802 | 2012 | return "/api/stats/report?"+p;}; |
| 1803 | − [["pdf-full","complet"],["pdf-syn","synthese"]].forEach(([id,m])=>{ | |
| 1804 | − const b=document.getElementById(id);if(!b)return; | |
| 2013 | + const menu=document.getElementById("pdf-menu"),more=document.getElementById("pdf-more"); | |
| 2014 | + if(more&&menu){ | |
| 2015 | + more.addEventListener("click",e=>{e.stopPropagation(); | |
| 2016 | + const open=menu.classList.toggle("open");more.setAttribute("aria-expanded",open); | |
| 2017 | + if(open)document.addEventListener("click",()=>{menu.classList.remove("open"); | |
| 2018 | + more.setAttribute("aria-expanded","false");},{once:true});});} | |
| 2019 | + document.querySelectorAll("[data-pdf]").forEach(b=>{ | |
| 1805 | 2020 | b.addEventListener("click",async()=>{ |
| 1806 | − const t=b.textContent;b.disabled=true;b.textContent="Génération…"; | |
| 1807 | − try{const r=await fetch(url(m));if(!r.ok)throw new Error(r.status); | |
| 2021 | + if(menu)menu.classList.remove("open"); | |
| 2022 | + const t=b.innerHTML;b.disabled=true; | |
| 2023 | + b.innerHTML=b.closest(".pdf-menu")?"Génération…":"⏳ Génération…"; | |
| 2024 | + try{const r=await fetch(url(b.dataset.pdf));if(!r.ok)throw new Error(r.status); | |
| 1808 | 2025 | const blob=await r.blob(); |
| 1809 | 2026 | const fn=((r.headers.get("Content-Disposition")||"").match(/filename="?([^";]+)/)||[])[1]||"rapport-crea-ka.pdf"; |
| 1810 | 2027 | const a=document.createElement("a");a.href=URL.createObjectURL(blob);a.download=fn; |
| 1811 | 2028 | document.body.appendChild(a);a.click();a.remove(); |
| 1812 | 2029 | setTimeout(()=>URL.revokeObjectURL(a.href),4000);} |
| 1813 | 2030 | catch(e){alert("Échec de la génération du PDF — réessayez.");} |
| 1814 | − b.disabled=false;b.textContent=t;});}); | |
| 2031 | + b.disabled=false;b.innerHTML=t;});}); | |
| 1815 | 2032 | } |
| 1816 | 2033 | |
| 1817 | 2034 | async function renderStats(){ |
@@ -1832,8 +2049,10 @@ async function loadStatsData(first){ | ||
| 1832 | 2049 | function renderStatsPage(){ |
| 1833 | 2050 | const d=ST.data; |
| 1834 | 2051 | const upd=new Date(d.updated).toLocaleString("fr-CA",{dateStyle:"medium",timeStyle:"short"}); |
| 1835 | − const donut=(d.breakdowns||[]).find(b=>b.kind==="donut"); | |
| 2052 | + const donuts=(d.breakdowns||[]).filter(b=>b.kind==="donut"); | |
| 1836 | 2053 | const barsB=(d.breakdowns||[]).filter(b=>b.kind!=="donut"); |
| 2054 | + const gauges=(d.gauges||[]).filter(g=>typeof g.value==="number"&&g.max); | |
| 2055 | + const hasEvo=(d.series||[]).length||(d.multiseries||[]).length||(d.stacked||[]).length; | |
| 1837 | 2056 | app.innerHTML=header()+` |
| 1838 | 2057 | <div class="container stats-page" id="stats-main"> |
| 1839 | 2058 | <div class="stats-head"> |
@@ -1841,32 +2060,40 @@ function renderStatsPage(){ | ||
| 1841 | 2060 | <h1 style="font-size:clamp(28px,4.6vw,46px);margin:12px 0 0;text-transform:uppercase">Les créateurs québécois <span class="hl">en chiffres.</span></h1> |
| 1842 | 2061 | <div class="fresh-row"><span>Mis à jour le ${esc(upd)}</span> |
| 1843 | 2062 | <button type="button" class="btn btn-ghost" id="st-refresh">↻ Rafraîchir</button></div></div> |
| 1844 | − <span class="pdf-actions"> | |
| 1845 | − <button type="button" class="btn btn-primary" id="pdf-full">⬇ Télécharger le rapport PDF</button> | |
| 1846 | − <button type="button" class="btn btn-ghost" id="pdf-syn">Synthèse (2 p.)</button></span> | |
| 2063 | + ${pdfActionsHtml()} | |
| 1847 | 2064 | </div> |
| 1848 | 2065 | <div class="tiles">${(d.kpis||[]).map(kpiHtml).join("")||emptyBlock("Indicateurs")}</div> |
| 1849 | 2066 | ${periodBar()} |
| 1850 | 2067 | <p class="klabel" style="margin:6px 0 0">Période analysée : ${esc(d.period.from)} → ${esc(d.period.to)}</p> |
| 2068 | + ${gauges.length?`<h2 class="stats-sect">Taux & couvertures</h2> | |
| 2069 | + <div class="gauges">${gauges.map(gaugeHtml).join("")}</div>`:""} | |
| 1851 | 2070 | <h2 class="stats-sect">Évolution</h2> |
| 1852 | − <div class="viz-grid">${(d.series||[]).map(s=>`<div class="lc" data-serie="${esc(s.id)}"></div>`).join("")||emptyBlock("Évolution")}</div> | |
| 1853 | − <h2 class="stats-sect">Répartitions</h2> | |
| 2071 | + ${hasEvo?`<div class="viz-grid"> | |
| 2072 | + ${(d.series||[]).map(s=>`<div class="lc" data-serie="${esc(s.id)}"></div>`).join("")} | |
| 2073 | + ${(d.multiseries||[]).map(m=>`<div class="lc" data-multi="${esc(m.id)}"></div>`).join("")} | |
| 2074 | + ${(d.stacked||[]).map(st=>stackedHtml(st)).join("")} | |
| 2075 | + </div>`:emptyBlock("Évolution")} | |
| 2076 | + <h2 class="stats-sect">Répartitions & distributions</h2> | |
| 1854 | 2077 | <div class="viz-grid two"> |
| 1855 | − ${donut?donutHtml(donut):""} | |
| 2078 | + ${donuts.map(donutHtml).join("")} | |
| 1856 | 2079 | ${barsB.map(b=>barsHtml(b.title,b.items)).join("")} |
| 1857 | − ${d.geo?barsHtml(d.geo.title,d.geo.items):""} | |
| 2080 | + ${(d.distributions||[]).map(vbarsHtml).join("")} | |
| 1858 | 2081 | </div> |
| 1859 | − ${d.heatmap?`<h2 class="stats-sect">Activité</h2>${heatmapHtml(d.heatmap)}`:""} | |
| 2082 | + ${d.geo?`<h2 class="stats-sect">Répartition géographique</h2> | |
| 2083 | + <div class="viz-grid two">${barsHtml(d.geo.title,d.geo.items)}</div>`:""} | |
| 2084 | + ${d.heatmap||d.hourly?`<h2 class="stats-sect">Activité</h2> | |
| 2085 | + ${d.heatmap?heatmapHtml(d.heatmap):""}${d.hourly?hourHeatHtml(d.hourly):""}`:""} | |
| 1860 | 2086 | ${(d.tables||[]).length?`<h2 class="stats-sect">Détails</h2><div style="display:grid;gap:22px">${(d.tables||[]).map(t=>`<div class="dt" data-table="${esc(t.id)}"></div>`).join("")}</div>`:""} |
| 1861 | 2087 | ${(d.records||[]).length?`<h2 class="stats-sect">Records & faits marquants</h2> |
| 1862 | 2088 | <div class="records-grid">${d.records.map(r=>`<div class="record"><span class="r-lbl">${esc(r.label)}</span> |
| 1863 | 2089 | <span style="text-align:right"><span class="r-val">${esc(r.value)}</span>${r.date?`<span class="klabel" style="display:block">${esc(r.date)}</span>`:""}</span></div>`).join("")}</div>`:""} |
| 1864 | 2090 | <p style="font-size:12px;color:var(--ink-3);margin-top:30px">Données réelles de l'annuaire (fiches actives, comptes vérifiés) — aucune statistique estimée ou inventée. |
| 1865 | − Rapport PDF estampillé Groupe-KA disponible en haut de page.</p> | |
| 2091 | + Rapports PDF estampillés Groupe-KA (5 formats) disponibles en haut de page.</p> | |
| 1866 | 2092 | </div>`+footer()+tabbar("stats"); |
| 1867 | 2093 | bindNav();bindPeriod();bindPdf(); |
| 1868 | 2094 | $("#st-refresh").addEventListener("click",()=>loadStatsData()); |
| 1869 | 2095 | (ST.data.series||[]).forEach(s=>{const el=document.querySelector(`.lc[data-serie="${s.id}"]`);if(el)mountLine(el,s);}); |
| 2096 | + (ST.data.multiseries||[]).forEach(m=>{const el=document.querySelector(`.lc[data-multi="${m.id}"]`);if(el)mountMulti(el,m);}); | |
| 1870 | 2097 | (ST.data.tables||[]).forEach(t=>{const el=document.querySelector(`.dt[data-table="${t.id}"]`);if(el)mountTable(el,t);}); |
| 1871 | 2098 | } |
| 1872 | 2099 | |
modified
frontend/dist/ka-agent.js
+177 −48
@@ -3,7 +3,11 @@ | ||
| 3 | 3 | * Groupe KA. Vanilla JS, zéro dépendance, injecté sur les 13 sites. |
| 4 | 4 | * <script>window.KA_AGENT={site:"lou-ka"}</script> |
| 5 | 5 | * <script src="/ka-agent.js" defer></script> |
| 6 | − * Bulle flottante en bas à droite → panneau de chat (bulle) → plein écran (⛶). | |
| 6 | + * v2 (2026-08-19) : ouverture directement PLEIN ÉCRAN (desktop et mobile, | |
| 7 | + * bouton ▭ pour réduire en fenêtre sur desktop) ; sur téléphone le panneau se | |
| 8 | + * cale sur window.visualViewport (le clavier ne fait plus grossir/défiler la | |
| 9 | + * page — fond verrouillé par body position:fixed) ; rendu MARKDOWN complet en | |
| 10 | + * streaming (titres, listes, tableaux, code, liens nommés, citations). | |
| 7 | 11 | * Flux SSE en direct depuis le backend central (texte token par token + |
| 8 | 12 | * indicateur d'outil). Historique conservé en localStorage (par site). |
| 9 | 13 | */ |
@@ -21,60 +25,147 @@ | ||
| 21 | 25 | border-radius:50%;border:2px solid var(--ink,#141814);background:var(--accent,#d9f26b); |
| 22 | 26 | color:var(--on-accent,#141814);font:700 17px/1 "Space Grotesk",system-ui,sans-serif; |
| 23 | 27 | cursor:pointer;box-shadow:4px 4px 0 rgba(20,24,20,.85);display:flex;align-items:center; |
| 24 | − justify-content:center;transition:transform .15s} | |
| 28 | + justify-content:center;transition:transform .15s;touch-action:manipulation} | |
| 25 | 29 | .kaa-btn:hover{transform:translate(-2px,-2px)} |
| 26 | − .kaa-panel{position:fixed;right:16px;bottom:calc(86px + env(safe-area-inset-bottom,0px));z-index:2147483001;width:min(392px,calc(100vw - 24px)); | |
| 27 | − height:min(580px,calc(100vh - 110px));height:min(580px,calc(100dvh - 110px));display:none;flex-direction:column;background:var(--paper,#f5f3ee); | |
| 28 | − border:2px solid var(--ink,#141814);border-radius:14px;box-shadow:8px 8px 0 rgba(20,24,20,.85); | |
| 29 | − overflow:hidden;font-family:Inter,system-ui,sans-serif} | |
| 30 | + .kaa-panel{position:fixed;z-index:2147483001;display:none;flex-direction:column;background:var(--paper,#f5f3ee); | |
| 31 | + overflow:hidden;font-family:Inter,system-ui,sans-serif;touch-action:manipulation} | |
| 30 | 32 | .kaa-panel.kaa-open{display:flex} |
| 31 | − .kaa-panel.kaa-full{right:0;bottom:0;width:100vw;height:100vh;height:100dvh;border-radius:0;border:0;box-shadow:none} | |
| 32 | − html.kaa-lock,html.kaa-lock body{overflow:hidden!important;overscroll-behavior:none} | |
| 33 | + .kaa-panel.kaa-full{left:0;top:0;right:0;bottom:0;width:100vw;height:100vh;height:100dvh;border:0;border-radius:0;box-shadow:none} | |
| 34 | + .kaa-panel:not(.kaa-full){right:16px;bottom:calc(86px + env(safe-area-inset-bottom,0px));width:min(392px,calc(100vw - 24px)); | |
| 35 | + height:min(580px,calc(100vh - 110px));height:min(580px,calc(100dvh - 110px)); | |
| 36 | + border:2px solid var(--ink,#141814);border-radius:14px;box-shadow:8px 8px 0 rgba(20,24,20,.85)} | |
| 37 | + html.kaa-lock,html.kaa-lock body{overflow:hidden!important;overscroll-behavior:none;touch-action:none} | |
| 33 | 38 | .kaa-head{display:flex;align-items:center;gap:9px;padding:11px 14px;background:var(--ink,#141814); |
| 34 | − color:var(--paper,#f5f3ee);flex:none} | |
| 39 | + color:var(--paper,#f5f3ee);flex:none;padding-top:max(11px,env(safe-area-inset-top,0px))} | |
| 35 | 40 | .kaa-head b{font:700 15px "Space Grotesk",system-ui,sans-serif;letter-spacing:-.02em} |
| 36 | 41 | .kaa-head .kaa-ka{display:inline-block;background:var(--accent,#d9f26b);color:var(--on-accent,#141814); |
| 37 | 42 | border-radius:6px;padding:1px 7px 2px;transform:rotate(-2deg);font-weight:700} |
| 38 | 43 | .kaa-head small{font:700 9.5px "JetBrains Mono",monospace;letter-spacing:.09em;text-transform:uppercase;opacity:.65} |
| 39 | 44 | .kaa-head .kaa-sp{flex:1} |
| 40 | 45 | .kaa-hbtn{width:34px;height:34px;border:1.5px solid rgba(245,243,238,.4);border-radius:8px;background:none; |
| 41 | − color:var(--paper,#f5f3ee);font-size:15px;cursor:pointer;line-height:1} | |
| 46 | + color:var(--paper,#f5f3ee);font-size:15px;cursor:pointer;line-height:1;flex:none} | |
| 42 | 47 | .kaa-hbtn:hover{border-color:var(--accent,#d9f26b);color:var(--accent,#d9f26b)} |
| 43 | 48 | .kaa-log{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:10px; |
| 44 | 49 | overscroll-behavior:contain;-webkit-overflow-scrolling:touch} |
| 45 | 50 | .kaa-msg{max-width:86%;padding:9px 13px;border:1.5px solid var(--ink,#141814);border-radius:12px; |
| 46 | − font-size:13.5px;line-height:1.5;white-space:pre-wrap;word-break:break-word} | |
| 51 | + font-size:13.5px;line-height:1.55;word-break:break-word} | |
| 52 | + .kaa-full .kaa-msg{max-width:min(86%,760px)} | |
| 53 | + .kaa-full .kaa-log{align-items:stretch} | |
| 47 | 54 | .kaa-msg.kaa-u{align-self:flex-end;background:var(--accent,#d9f26b);color:var(--on-accent,#141814); |
| 48 | − border-bottom-right-radius:4px} | |
| 55 | + border-bottom-right-radius:4px;white-space:pre-wrap} | |
| 49 | 56 | .kaa-msg.kaa-a{align-self:flex-start;background:#fff;border-bottom-left-radius:4px;box-shadow:3px 3px 0 rgba(20,24,20,.12)} |
| 50 | − .kaa-msg.kaa-a a{color:inherit;text-decoration:underline;text-underline-offset:3px} | |
| 51 | − .kaa-msg.kaa-a b{font-weight:700} | |
| 57 | + .kaa-msg.kaa-a a{color:inherit;text-decoration:underline;text-underline-offset:3px;font-weight:600} | |
| 58 | + .kaa-msg.kaa-a p{margin:.35em 0} | |
| 59 | + .kaa-msg.kaa-a p:first-child{margin-top:0} | |
| 60 | + .kaa-msg.kaa-a p:last-child{margin-bottom:0} | |
| 61 | + .kaa-msg.kaa-a h1,.kaa-msg.kaa-a h2,.kaa-msg.kaa-a h3,.kaa-msg.kaa-a h4{ | |
| 62 | + font:700 14px "Space Grotesk",system-ui,sans-serif;letter-spacing:-.01em;margin:.7em 0 .3em} | |
| 63 | + .kaa-msg.kaa-a h1:first-child,.kaa-msg.kaa-a h2:first-child,.kaa-msg.kaa-a h3:first-child,.kaa-msg.kaa-a h4:first-child{margin-top:.1em} | |
| 64 | + .kaa-msg.kaa-a h1{font-size:15.5px}.kaa-msg.kaa-a h2{font-size:14.5px} | |
| 65 | + .kaa-msg.kaa-a ul,.kaa-msg.kaa-a ol{margin:.35em 0;padding-left:1.35em} | |
| 66 | + .kaa-msg.kaa-a li{margin:.18em 0} | |
| 67 | + .kaa-msg.kaa-a code{font:600 12px "JetBrains Mono",monospace;background:var(--surface-2,#f0eee7); | |
| 68 | + border:1px solid rgba(20,24,20,.15);border-radius:5px;padding:.5px 4px} | |
| 69 | + .kaa-msg.kaa-a pre{margin:.45em 0;padding:9px 11px;background:var(--ink,#141814);color:var(--paper,#f5f3ee); | |
| 70 | + border-radius:9px;overflow-x:auto} | |
| 71 | + .kaa-msg.kaa-a pre code{background:none;border:0;color:inherit;padding:0;font-weight:400;font-size:11.5px;line-height:1.5} | |
| 72 | + .kaa-msg.kaa-a blockquote{margin:.45em 0;padding:.15em .8em;border-left:3px solid var(--accent,#d9f26b); | |
| 73 | + background:var(--surface-2,#faf9f5);color:var(--ink-2,#4d5551)} | |
| 74 | + .kaa-msg.kaa-a hr{border:0;border-top:1.5px dashed rgba(20,24,20,.3);margin:.6em 0} | |
| 75 | + .kaa-msg.kaa-a table{border-collapse:collapse;margin:.45em 0;font-size:12.5px;display:block;overflow-x:auto;max-width:100%} | |
| 76 | + .kaa-msg.kaa-a th,.kaa-msg.kaa-a td{border:1.5px solid var(--ink,#141814);padding:4px 9px;text-align:left;white-space:nowrap} | |
| 77 | + .kaa-msg.kaa-a th{background:var(--accent,#d9f26b);color:var(--on-accent,#141814); | |
| 78 | + font:700 11px "Space Grotesk",system-ui,sans-serif;letter-spacing:.02em} | |
| 79 | + .kaa-msg.kaa-a td{background:#fff} | |
| 52 | 80 | .kaa-tool{align-self:flex-start;font:700 10px "JetBrains Mono",monospace;letter-spacing:.07em; |
| 53 | 81 | text-transform:uppercase;color:var(--ink-2,#4d5551);padding:3px 10px;border:1.5px dashed var(--ink-2,#4d5551); |
| 54 | 82 | border-radius:999px;background:var(--surface-2,#faf9f5)} |
| 55 | 83 | .kaa-in{display:flex;gap:8px;padding:11px;border-top:2px solid var(--ink,#141814);background:#fff;flex:none; |
| 56 | 84 | padding-bottom:calc(11px + env(safe-area-inset-bottom,0))} |
| 85 | + .kaa-full .kaa-in{justify-content:center} | |
| 86 | + .kaa-full .kaa-in textarea{max-width:700px} | |
| 57 | 87 | .kaa-in textarea{flex:1;resize:none;min-height:44px;max-height:110px;padding:10px 12px;font:16px/1.4 Inter,system-ui,sans-serif; |
| 58 | 88 | border:1.5px solid var(--ink,#141814);border-radius:9px;background:var(--paper,#f5f3ee);outline:none} |
| 59 | 89 | .kaa-in button{min-width:52px;min-height:44px;border:1.5px solid var(--ink,#141814);border-radius:9px; |
| 60 | − background:var(--ink,#141814);color:var(--accent,#d9f26b);font:700 16px "Space Grotesk",system-ui;cursor:pointer} | |
| 90 | + background:var(--ink,#141814);color:var(--accent,#d9f26b);font:700 16px "Space Grotesk",system-ui;cursor:pointer;touch-action:manipulation} | |
| 61 | 91 | .kaa-in button:disabled{opacity:.45} |
| 62 | − .kaa-hello{font-size:12.5px;color:var(--ink-2,#4d5551);padding:4px 2px} | |
| 92 | + .kaa-hello{font-size:12.5px;color:var(--ink-2,#4d5551);padding:4px 2px;max-width:760px} | |
| 63 | 93 | .kaa-dots::after{content:"…";animation:kaa-b 1.2s infinite} |
| 64 | 94 | @keyframes kaa-b{0%{opacity:.2}50%{opacity:1}100%{opacity:.2}} |
| 65 | − @media (max-width:560px){.kaa-panel{right:8px;left:8px;width:auto}} | |
| 95 | + @media (max-width:640px){.kaa-x1{display:none}} | |
| 66 | 96 | `; |
| 67 | 97 | |
| 68 | − /* ---------- markdown minimal (gras, liens, puces) — texte échappé d'abord ---------- */ | |
| 98 | + /* ---------- markdown complet (rendu en streaming, texte échappé d'abord) ---------- */ | |
| 69 | 99 | function esc(s) { |
| 70 | 100 | return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); |
| 71 | 101 | } |
| 72 | − function md(s) { | |
| 73 | − return esc(s) | |
| 74 | − .replace(/\*\*([^*]+)\*\*/g, "<b>$1</b>") | |
| 75 | − .replace(/(https?:\/\/[^\s<)"']+)/g, function (u) { | |
| 76 | − return '<a href="' + u + '" target="_blank" rel="noopener noreferrer">' + u.replace(/^https?:\/\/(www\.)?/, "").slice(0, 40) + "</a>"; | |
| 77 | − }); | |
| 102 | + function inline(s) { | |
| 103 | + s = esc(s); | |
| 104 | + s = s.replace(/`([^`\n]+)`/g, "<code>$1</code>"); | |
| 105 | + s = s.replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, | |
| 106 | + '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'); | |
| 107 | + s = s.replace(/\*\*([^*\n]+)\*\*/g, "<b>$1</b>"); | |
| 108 | + s = s.replace(/(^|[^*\w])\*([^*\n]+)\*(?!\*)/g, "$1<i>$2</i>"); | |
| 109 | + s = s.replace(/(^|[^"'>=\w])(https?:\/\/[^\s<)"']+)/g, function (m, pre, u) { | |
| 110 | + return pre + '<a href="' + u + '" target="_blank" rel="noopener noreferrer">' + | |
| 111 | + u.replace(/^https?:\/\/(www\.)?/, "").slice(0, 42) + "</a>"; | |
| 112 | + }); | |
| 113 | + return s; | |
| 114 | + } | |
| 115 | + function md(src) { | |
| 116 | + var lines = String(src).split("\n"), out = [], i = 0, m; | |
| 117 | + function para(buf) { if (buf.length) out.push("<p>" + buf.map(inline).join("<br>") + "</p>"); } | |
| 118 | + while (i < lines.length) { | |
| 119 | + var l = lines[i]; | |
| 120 | + if (/^\s*```/.test(l)) { /* bloc de code */ | |
| 121 | + var code = []; i++; | |
| 122 | + while (i < lines.length && !/^\s*```/.test(lines[i])) code.push(lines[i++]); | |
| 123 | + i++; | |
| 124 | + out.push("<pre><code>" + esc(code.join("\n")) + "</code></pre>"); | |
| 125 | + } else if ((m = l.match(/^\s*(#{1,4})\s+(.*)$/))) { /* titres */ | |
| 126 | + out.push("<h" + m[1].length + ">" + inline(m[2]) + "</h" + m[1].length + ">"); i++; | |
| 127 | + } else if (/^\s*(---+|\*\*\*+)\s*$/.test(l)) { /* filet */ | |
| 128 | + out.push("<hr>"); i++; | |
| 129 | + } else if (/^\s*>|^\s*>/.test(l)) { /* citation */ | |
| 130 | + var q = []; | |
| 131 | + while (i < lines.length && /^\s*>/.test(lines[i])) q.push(lines[i++].replace(/^\s*>\s?/, "")); | |
| 132 | + out.push("<blockquote>" + q.map(inline).join("<br>") + "</blockquote>"); | |
| 133 | + } else if (/^\s*\|.*\|\s*$/.test(l)) { /* tableau */ | |
| 134 | + var rows = []; | |
| 135 | + while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) { | |
| 136 | + var cells = lines[i].trim().replace(/^\||\|$/g, "").split("|").map(function (c) { return c.trim(); }); | |
| 137 | + if (!/^[:\-\s|]+$/.test(lines[i].replace(/\|/g, ""))) rows.push(cells); | |
| 138 | + i++; | |
| 139 | + } | |
| 140 | + if (rows.length) { | |
| 141 | + var t = "<table>"; | |
| 142 | + rows.forEach(function (r, ri) { | |
| 143 | + var tag = ri === 0 ? "th" : "td"; | |
| 144 | + t += "<tr>" + r.map(function (c) { return "<" + tag + ">" + inline(c) + "</" + tag + ">"; }).join("") + "</tr>"; | |
| 145 | + }); | |
| 146 | + out.push(t + "</table>"); | |
| 147 | + } | |
| 148 | + } else if (/^\s*[-*+]\s+/.test(l)) { /* liste à puces */ | |
| 149 | + var ul = []; | |
| 150 | + while (i < lines.length && /^\s*[-*+]\s+/.test(lines[i])) | |
| 151 | + ul.push("<li>" + inline(lines[i++].replace(/^\s*[-*+]\s+/, "")) + "</li>"); | |
| 152 | + out.push("<ul>" + ul.join("") + "</ul>"); | |
| 153 | + } else if (/^\s*\d+[.)]\s+/.test(l)) { /* liste numérotée */ | |
| 154 | + var ol = []; | |
| 155 | + while (i < lines.length && /^\s*\d+[.)]\s+/.test(lines[i])) | |
| 156 | + ol.push("<li>" + inline(lines[i++].replace(/^\s*\d+[.)]\s+/, "")) + "</li>"); | |
| 157 | + out.push("<ol>" + ol.join("") + "</ol>"); | |
| 158 | + } else if (!l.trim()) { i++; } /* ligne vide */ | |
| 159 | + else { /* paragraphe */ | |
| 160 | + var buf = []; | |
| 161 | + while (i < lines.length && lines[i].trim() && | |
| 162 | + !/^\s*(```|#{1,4}\s|[-*+]\s|\d+[.)]\s|>|\||---+\s*$)/.test(lines[i])) | |
| 163 | + buf.push(lines[i++]); | |
| 164 | + if (!buf.length) buf.push(lines[i++] || ""); | |
| 165 | + para(buf); | |
| 166 | + } | |
| 167 | + } | |
| 168 | + return out.join(""); | |
| 78 | 169 | } |
| 79 | 170 | |
| 80 | 171 | /* ---------- état ---------- */ |
@@ -98,10 +189,10 @@ | ||
| 98 | 189 | panel.setAttribute("aria-label", "KA Agent"); |
| 99 | 190 | panel.innerHTML = |
| 100 | 191 | '<div class="kaa-head"><b>KA<span class="kaa-ka">Agent</span></b><small>Groupe KA · IA</small><span class="kaa-sp"></span>' + |
| 101 | − '<button class="kaa-hbtn kaa-x1" title="Plein écran" aria-label="Plein écran">⛶</button>' + | |
| 192 | + '<button class="kaa-hbtn kaa-x1" title="Réduire / agrandir" aria-label="Réduire ou agrandir">▭</button>' + | |
| 102 | 193 | '<button class="kaa-hbtn kaa-x2" title="Fermer" aria-label="Fermer">✕</button></div>' + |
| 103 | 194 | '<div class="kaa-log"></div>' + |
| 104 | − '<div class="kaa-in"><textarea rows="1" placeholder="Posez votre question…" aria-label="Votre question"></textarea>' + | |
| 195 | + '<div class="kaa-in"><textarea rows="1" enterkeyhint="send" autocapitalize="sentences" autocomplete="off" placeholder="Posez votre question…" aria-label="Votre question"></textarea>' + | |
| 105 | 196 | "<button aria-label=\"Envoyer\">➤</button></div>"; |
| 106 | 197 | document.body.appendChild(btn); |
| 107 | 198 | document.body.appendChild(panel); |
@@ -132,45 +223,83 @@ | ||
| 132 | 223 | if (log.length) return; |
| 133 | 224 | var d = document.createElement("div"); |
| 134 | 225 | d.className = "kaa-hello"; |
| 135 | − d.textContent = "👋 Je suis KA Agent, l'assistant de l'écosystème Groupe KA. Posez-moi une question sur ce site, ses données (prix, annonces, stats…) ou sur le groupe."; | |
| 226 | + d.textContent = "👋 Je suis KA Agent, l'assistant de l'écosystème Groupe KA. Posez-moi une question sur ce site, ses données (prix, annonces, fiches, stats…) ou sur le groupe."; | |
| 136 | 227 | logEl.appendChild(d); |
| 137 | 228 | } |
| 138 | 229 | function render() { |
| 139 | 230 | logEl.innerHTML = ""; |
| 140 | 231 | hello(); |
| 141 | − log.forEach(function (m) { bubble(m.role === "user" ? "kaa-u" : "kaa-a", md(m.content)); }); | |
| 232 | + log.forEach(function (m) { | |
| 233 | + m.role === "user" ? bubble("kaa-u", esc(m.content)) : bubble("kaa-a", md(m.content)); | |
| 234 | + }); | |
| 142 | 235 | scroll(); |
| 143 | 236 | } |
| 144 | 237 | |
| 145 | − /* ---------- ouverture / plein écran ---------- */ | |
| 146 | − /* Sur téléphone : panneau plein écran d'office + scroll d'arrière-plan | |
| 147 | − verrouillé tant qu'il est ouvert (html.kaa-lock). Pas de focus clavier | |
| 148 | − forcé au tap (le clavier ne s'ouvre que si l'utilisateur touche le champ). */ | |
| 149 | − var mobileMq = window.matchMedia("(max-width: 640px)"); | |
| 238 | + /* ---------- plein écran + clavier mobile ---------- | |
| 239 | + Ouverture = PLEIN ÉCRAN direct (desktop et mobile). ▭ réduit en fenêtre | |
| 240 | + (desktop seulement — caché sur mobile). Tant que le plein écran est ouvert, | |
| 241 | + l'arrière-plan est GELÉ (body position:fixed, scroll restauré à la | |
| 242 | + fermeture) et le panneau se cale sur window.visualViewport : quand le | |
| 243 | + clavier s'ouvre, le panneau rétrécit à la place de laisser iOS | |
| 244 | + zoomer/pousser la page. Pas de focus clavier forcé au tap sur mobile. */ | |
| 150 | 245 | var fineInput = window.matchMedia("(hover: hover) and (pointer: fine)"); |
| 151 | − function syncLock() { | |
| 152 | − var open = panel.classList.contains("kaa-open"); | |
| 153 | − if (open && mobileMq.matches) panel.classList.add("kaa-full"); | |
| 154 | − document.documentElement.classList.toggle( | |
| 155 | − "kaa-lock", open && panel.classList.contains("kaa-full")); | |
| 246 | + var vv = window.visualViewport; | |
| 247 | + var savedY = 0; | |
| 248 | + | |
| 249 | + function isOpen() { return panel.classList.contains("kaa-open"); } | |
| 250 | + function isFull() { return panel.classList.contains("kaa-full"); } | |
| 251 | + | |
| 252 | + function fitVV() { | |
| 253 | + if (!vv || !isOpen() || !isFull()) { panel.style.height = ""; panel.style.top = ""; return; } | |
| 254 | + panel.style.top = Math.round(vv.offsetTop) + "px"; | |
| 255 | + panel.style.height = Math.round(vv.height) + "px"; | |
| 256 | + scroll(); | |
| 156 | 257 | } |
| 157 | − btn.addEventListener("click", function () { | |
| 158 | − panel.classList.toggle("kaa-open"); | |
| 159 | − if (panel.classList.contains("kaa-open")) { | |
| 160 | − render(); | |
| 161 | − if (fineInput.matches) ta.focus(); | |
| 258 | + if (vv) { | |
| 259 | + vv.addEventListener("resize", fitVV); | |
| 260 | + vv.addEventListener("scroll", fitVV); | |
| 261 | + } | |
| 262 | + | |
| 263 | + function lockBg(on) { | |
| 264 | + var b = document.body, h = document.documentElement; | |
| 265 | + if (on && !h.classList.contains("kaa-lock")) { | |
| 266 | + savedY = window.scrollY || 0; | |
| 267 | + h.classList.add("kaa-lock"); | |
| 268 | + b.style.position = "fixed"; | |
| 269 | + b.style.top = -savedY + "px"; | |
| 270 | + b.style.left = "0"; b.style.right = "0"; b.style.width = "100%"; | |
| 271 | + } else if (!on && h.classList.contains("kaa-lock")) { | |
| 272 | + h.classList.remove("kaa-lock"); | |
| 273 | + b.style.position = ""; b.style.top = ""; b.style.left = ""; b.style.right = ""; b.style.width = ""; | |
| 274 | + window.scrollTo(0, savedY); | |
| 162 | 275 | } |
| 163 | − syncLock(); | |
| 276 | + } | |
| 277 | + function sync() { | |
| 278 | + lockBg(isOpen() && isFull()); | |
| 279 | + fitVV(); | |
| 280 | + } | |
| 281 | + | |
| 282 | + btn.addEventListener("click", function () { | |
| 283 | + panel.classList.add("kaa-open", "kaa-full"); // plein écran d'office | |
| 284 | + render(); | |
| 285 | + if (fineInput.matches) ta.focus(); | |
| 286 | + sync(); | |
| 164 | 287 | }); |
| 165 | 288 | panel.querySelector(".kaa-x2").addEventListener("click", function () { |
| 166 | 289 | panel.classList.remove("kaa-open", "kaa-full"); |
| 167 | − syncLock(); | |
| 290 | + sync(); | |
| 168 | 291 | }); |
| 169 | 292 | panel.querySelector(".kaa-x1").addEventListener("click", function () { |
| 170 | 293 | panel.classList.toggle("kaa-full"); |
| 171 | − syncLock(); | |
| 294 | + sync(); | |
| 172 | 295 | scroll(); |
| 173 | 296 | }); |
| 297 | + document.addEventListener("keydown", function (e) { | |
| 298 | + if (e.key === "Escape" && isOpen()) { | |
| 299 | + panel.classList.remove("kaa-open", "kaa-full"); | |
| 300 | + sync(); | |
| 301 | + } | |
| 302 | + }); | |
| 174 | 303 | |
| 175 | 304 | /* ---------- envoi + flux SSE ---------- */ |
| 176 | 305 | var busy = false; |
@@ -182,7 +311,7 @@ | ||
| 182 | 311 | ta.value = ""; |
| 183 | 312 | log.push({ role: "user", content: q }); |
| 184 | 313 | save(); |
| 185 | − bubble("kaa-u", md(q)); | |
| 314 | + bubble("kaa-u", esc(q)); | |
| 186 | 315 | var out = bubble("kaa-a", '<span class="kaa-dots"></span>'); |
| 187 | 316 | var acc = ""; |
| 188 | 317 | var chips = []; |
@@ -211,7 +340,7 @@ | ||
| 211 | 340 | try { data = JSON.parse(dm); } catch (e) {} |
| 212 | 341 | if (ev === "delta" && data.text) { |
| 213 | 342 | acc += data.text; |
| 214 | − out.innerHTML = md(acc); | |
| 343 | + out.innerHTML = md(acc); // markdown re-rendu à chaque delta | |
| 215 | 344 | scroll(); |
| 216 | 345 | } else if (ev === "tool") { |
| 217 | 346 | chips.push(toolChip(data.name || "recherche")); |
modified
frontend/src/index.template.html
+251 −24
@@ -178,11 +178,6 @@ select.f.active{background-color:var(--accent-soft);color:var(--ink);border-colo | ||
| 178 | 178 | .filters::-webkit-scrollbar{display:none} |
| 179 | 179 | select.f{flex:none;font-size:16px;padding:8px 30px 8px 13px} |
| 180 | 180 | } |
| 181 | −/* Anti-zoom iOS jusqu'au breakpoint tabbar (940 px) : champs >= 16 px | |
| 182 | − (filet global : tokens.css force aussi 16 px au doigt) */ | |
| 183 | −@media(max-width:940px){.search-input input,select.f{font-size:16px}} | |
| 184 | −/* Cible tactile >= 44 px du logo (112×26 rendus) : zone étendue invisible */ | |
| 185 | −@media(pointer:coarse){.brand{position:relative}.brand::after{content:"";position:absolute;inset:-8px}} | |
| 186 | 181 | |
| 187 | 182 | /* ===== grille créateurs ===== */ |
| 188 | 183 | .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:18px;padding:24px 0 10px} |
@@ -461,6 +456,36 @@ select.f.active{background-color:var(--accent-soft);color:var(--ink);border-colo | ||
| 461 | 456 | background:var(--surface-2);padding:20px} |
| 462 | 457 | .stats-sect{font-size:17px;text-transform:uppercase;margin:34px 0 14px} |
| 463 | 458 | |
| 459 | +/* ===== page stats v2 : sparklines, jauges, histogrammes, heatmap horaire, menu PDF ===== */ | |
| 460 | +.tile svg.spark{display:block;margin-top:9px;width:100%;height:28px} | |
| 461 | +.gauges{display:grid;grid-template-columns:repeat(auto-fit,minmax(168px,1fr));gap:14px;margin-bottom:8px} | |
| 462 | +.gauge{background:var(--surface);border:1.5px solid var(--ink);border-radius:var(--r-card); | |
| 463 | + padding:16px 14px 13px;box-shadow:var(--shadow-off-soft);text-align:center} | |
| 464 | +.gauge svg{width:124px;max-width:100%;height:auto;margin:0 auto;display:block} | |
| 465 | +.gauge .g-v{font-family:var(--font-display);font-weight:700;font-size:21px;color:var(--ink);margin-top:-30px} | |
| 466 | +.gauge .g-l{font-family:var(--font-mono);font-size:9px;font-weight:700;text-transform:uppercase; | |
| 467 | + letter-spacing:.05em;color:var(--ink-3);margin-top:10px;line-height:1.55} | |
| 468 | +.statsum{display:flex;gap:7px;flex-wrap:wrap;margin-top:10px} | |
| 469 | +.statsum .chip b{font-family:var(--font-mono);margin-left:4px} | |
| 470 | +.leg-swatch.ml1{border-top:3px solid var(--ink)} | |
| 471 | +.leg-swatch.ml2{border-top:3px dashed var(--accent)} | |
| 472 | +.leg-swatch.ml3{border-top:3px dotted var(--ink-3)} | |
| 473 | +.hrow .d{flex:none;font-family:var(--font-mono);font-size:10px;font-weight:700;min-width:54px;text-align:right} | |
| 474 | +.hrow .d.up{color:var(--green)}.hrow .d.down{color:var(--danger)} | |
| 475 | +.hh svg{min-width:560px;width:100%;height:auto} | |
| 476 | +.pdf-menu-wrap{position:relative;display:inline-flex;gap:8px;flex-wrap:wrap} | |
| 477 | +.pdf-menu{position:absolute;right:0;top:calc(100% + 8px);z-index:70;background:var(--surface); | |
| 478 | + border:1.5px solid var(--ink);border-radius:var(--r-card);box-shadow:var(--shadow-off); | |
| 479 | + display:none;min-width:270px;padding:6px} | |
| 480 | +.pdf-menu.open{display:block} | |
| 481 | +.pdf-menu button{display:block;width:100%;text-align:left;border:0;background:none; | |
| 482 | + padding:11px 13px;border-radius:9px;font-family:var(--font-display);font-weight:700; | |
| 483 | + font-size:13px;color:var(--ink);min-height:44px} | |
| 484 | +.pdf-menu button:hover{background:var(--accent-soft)} | |
| 485 | +.pdf-menu small{display:block;font-family:var(--font-body);font-weight:400;font-size:11px; | |
| 486 | + color:var(--ink-3);margin-top:2px} | |
| 487 | +@media(max-width:760px){.pdf-menu{right:auto;left:0}} | |
| 488 | + | |
| 464 | 489 | /* ===== retrait ===== */ |
| 465 | 490 | .optout-page{max-width:620px;margin:0 auto;padding:44px 0 70px} |
| 466 | 491 | .optout-page h1{font-size:clamp(26px,4vw,32px);margin:12px 0;text-transform:uppercase} |
@@ -977,6 +1002,15 @@ const fmtPct=v=>(v>=0?"+":"")+v.toLocaleString("fr-CA",{maximumFractionDigits:1} | ||
| 977 | 1002 | const emptyBlock=t=>`<div class="empty-block"><b style="font-family:var(--font-display);font-size:14px">${esc(t)}</b> |
| 978 | 1003 | <p class="klabel" style="margin:6px 0 0">Pas encore mesuré — aucune donnée disponible pour cette période.</p></div>`; |
| 979 | 1004 | |
| 1005 | +/* mini-tendance dans une carte KPI (série spark du contrat v2) */ | |
| 1006 | +function sparkSvg(spark,hero){ | |
| 1007 | + if(!spark||spark.length<2)return""; | |
| 1008 | + const W=120,H=28,vs=spark.map(p=>p.v); | |
| 1009 | + const mn=Math.min(...vs),mx=Math.max(...vs),rng=(mx-mn)||1; | |
| 1010 | + const pts=spark.map((p,i)=>`${(i/(spark.length-1)*W).toFixed(1)},${(H-2-(H-4)*((p.v-mn)/rng)).toFixed(1)}`).join(" "); | |
| 1011 | + return `<svg class="spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" aria-hidden="true"> | |
| 1012 | + <polyline points="${pts}" fill="none" stroke="${hero?"var(--accent-soft)":"var(--accent)"}" stroke-width="2"/></svg>`; | |
| 1013 | +} | |
| 980 | 1014 | function kpiHtml(k,i){ |
| 981 | 1015 | const v=k.value,hero=i===0; |
| 982 | 1016 | const num=typeof v==="number"?(v>=1e6?fmt.format(v):fmtFull.format(v)):esc(v); |
@@ -986,7 +1020,167 @@ function kpiHtml(k,i){ | ||
| 986 | 1020 | delta=`<div class="tile-d ${up?"up":"down"}">${up?"▲":"▼"} ${fmtPct(k.delta_pct)} <span style="opacity:.6">vs période préc.</span></div>`;} |
| 987 | 1021 | return `<div class="tile${hero?" hero-tile":""}"${typeof v==="number"?` title="${fmtFull.format(v)}"`:""}> |
| 988 | 1022 | <div class="tile-v">${num}${k.unit?`<span style="font-size:.42em;opacity:.6"> ${esc(k.unit)}</span>`:""}</div> |
| 989 | − <div class="tile-k">${esc(k.label)}</div>${delta}</div>`; | |
| 1023 | + <div class="tile-k">${esc(k.label)}</div>${delta}${sparkSvg(k.spark,hero)}</div>`; | |
| 1024 | +} | |
| 1025 | + | |
| 1026 | +/* --- jauge demi-arc (taux, couvertures, complétude) --- */ | |
| 1027 | +function gaugeHtml(g){ | |
| 1028 | + if(typeof g.value!=="number"||!g.max)return""; | |
| 1029 | + const frac=Math.max(0,Math.min(1,g.value/g.max)); | |
| 1030 | + const R=52,C=Math.PI*R; | |
| 1031 | + return `<div class="gauge" title="${esc(g.label)} — ${g.value.toLocaleString("fr-CA")}${g.unit?" "+esc(g.unit):""} (${Math.round(frac*100)} % de ${fmtFull.format(g.max)})"> | |
| 1032 | + <svg viewBox="0 0 120 68" role="img" aria-label="${esc(g.label)}"> | |
| 1033 | + <path d="M8 60 A${R} ${R} 0 0 1 112 60" fill="none" stroke="var(--line)" stroke-width="11" stroke-linecap="round"/> | |
| 1034 | + ${frac>0?`<path d="M8 60 A${R} ${R} 0 0 1 112 60" fill="none" stroke="var(--accent)" stroke-width="11" stroke-linecap="round" | |
| 1035 | + stroke-dasharray="${(frac*C).toFixed(1)} ${(C+20).toFixed(1)}"/>`:""} | |
| 1036 | + </svg> | |
| 1037 | + <div class="g-v">${g.value.toLocaleString("fr-CA",{maximumFractionDigits:1})}${g.unit?`<span style="font-size:.58em;opacity:.65"> ${esc(g.unit)}</span>`:""}</div> | |
| 1038 | + <div class="g-l">${esc(g.label)}</div></div>`; | |
| 1039 | +} | |
| 1040 | + | |
| 1041 | +/* --- statistiques d'une série : min / max / moyenne / médiane / écart-type --- */ | |
| 1042 | +function statSummary(s){ | |
| 1043 | + const vs=(s.points||[]).map(p=>p.v).filter(v=>typeof v==="number"); | |
| 1044 | + if(vs.length<2)return""; | |
| 1045 | + const sv=[...vs].sort((a,b)=>a-b),mean=vs.reduce((a,b)=>a+b,0)/vs.length; | |
| 1046 | + const med=sv[Math.floor(sv.length/2)]; | |
| 1047 | + const sd=Math.sqrt(vs.reduce((a,v)=>a+(v-mean)*(v-mean),0)/vs.length); | |
| 1048 | + const f=v=>fmtFull.format(Math.round(v*100)/100); | |
| 1049 | + return `<div class="statsum"><span class="chip">min<b>${f(sv[0])}</b></span> | |
| 1050 | + <span class="chip">max<b>${f(sv[sv.length-1])}</b></span> | |
| 1051 | + <span class="chip">moyenne<b>${f(mean)}</b></span> | |
| 1052 | + <span class="chip">médiane<b>${f(med)}</b></span> | |
| 1053 | + <span class="chip">écart-type σ<b>${f(sd)}</b></span></div>`; | |
| 1054 | +} | |
| 1055 | + | |
| 1056 | +/* --- barres verticales : série kind=bar (volumes/jour) & histogrammes (bins) --- */ | |
| 1057 | +function vbarsHtml(spec){ | |
| 1058 | + const pts=(spec.points||(spec.bins||[]).map(b=>({t:b.label,v:b.value}))) | |
| 1059 | + .filter(p=>typeof p.v==="number"); | |
| 1060 | + if(!pts.length||!pts.some(p=>p.v>0))return emptyBlock(spec.title); | |
| 1061 | + const W=720,H=250,PL=54,PR=12,PT=14,PB=40,cw=W-PL-PR,ch=H-PT-PB; | |
| 1062 | + const vmax=Math.max(...pts.map(p=>p.v),1); | |
| 1063 | + let grid=""; | |
| 1064 | + for(let k=0;k<5;k++){const y=PT+ch*k/4,v=vmax*(4-k)/4; | |
| 1065 | + grid+=`<line x1="${PL}" x2="${W-PR}" y1="${y.toFixed(1)}" y2="${y.toFixed(1)}" stroke="var(--line)"/> | |
| 1066 | + <text x="${PL-6}" y="${(y+3).toFixed(1)}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${fmtFull.format(Math.round(v))}</text>`;} | |
| 1067 | + const n=pts.length,bw=Math.max(2,cw/n-3); | |
| 1068 | + const bars=pts.map((p,i)=>{const bh=ch*p.v/vmax,x=PL+cw*i/n+1.5; | |
| 1069 | + return `<rect x="${x.toFixed(1)}" y="${(PT+ch-bh).toFixed(1)}" width="${bw.toFixed(1)}" height="${Math.max(bh,p.v>0?1:0).toFixed(1)}" | |
| 1070 | + fill="var(--accent)" stroke="var(--ink)" stroke-width="${n>40?0.4:1}"><title>${esc(p.t)} — ${fmtFull.format(p.v)}${spec.unit?" "+esc(spec.unit):""}</title></rect>`;}).join(""); | |
| 1071 | + const lblIdx=n<=10?pts.map((_,i)=>i):[0,Math.floor(n/2),n-1]; | |
| 1072 | + const xl=lblIdx.map(i=>`<text x="${(PL+cw*i/n+bw/2).toFixed(1)}" y="${H-8}" text-anchor="middle" | |
| 1073 | + font-size="${n<=10?10:10}" fill="var(--ink-3)" font-family="var(--font-mono)">${esc(String(pts[i].t))}</text>`).join(""); | |
| 1074 | + return `<div class="viz-card"><h2>${esc(spec.title)}</h2> | |
| 1075 | + ${spec.unit?`<div class="viz-sub">${esc(spec.unit)}</div>`:'<div style="height:10px"></div>'} | |
| 1076 | + <svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(spec.title)}">${grid}${bars}${xl}</svg></div>`; | |
| 1077 | +} | |
| 1078 | + | |
| 1079 | +/* --- multi-courbes (≤ 4) : identité par MOTIF de trait en plus de la couleur --- */ | |
| 1080 | +const ML_STYLES=[ | |
| 1081 | + {stroke:"var(--accent)",w:2.6,dash:"",cls:"",name:"trait plein accent"}, | |
| 1082 | + {stroke:"var(--ink)",w:2,dash:"",cls:"ml1",name:"trait plein encre"}, | |
| 1083 | + {stroke:"var(--accent)",w:2.2,dash:"7 4",cls:"ml2",name:"tirets accent"}, | |
| 1084 | + {stroke:"var(--ink-3)",w:2,dash:"2 3",cls:"ml3",name:"pointillé gris"}]; | |
| 1085 | +function multiFigure(ms,hide){ | |
| 1086 | + const series=(ms.series||[]).filter(s=>(s.points||[]).length>1).slice(0,4); | |
| 1087 | + if(!series.length)return emptyBlock(ms.title); | |
| 1088 | + const W=720,H=250,PL=54,PR=12,PT=14,PB=26,cw=W-PL-PR,ch=H-PT-PB; | |
| 1089 | + const shown=series.filter((_,i)=>!hide[i]); | |
| 1090 | + const all=(shown.length?shown:series).flatMap(s=>s.points.map(p=>p.v)); | |
| 1091 | + const vmax=Math.max(...all,1),vmin=Math.min(0,...all),rng=(vmax-vmin)||1; | |
| 1092 | + let grid=""; | |
| 1093 | + for(let k=0;k<5;k++){const y=PT+ch*k/4,v=vmax-(vmax-vmin)*k/4; | |
| 1094 | + grid+=`<line x1="${PL}" x2="${W-PR}" y1="${y.toFixed(1)}" y2="${y.toFixed(1)}" stroke="var(--line)"/> | |
| 1095 | + <text x="${PL-6}" y="${(y+3).toFixed(1)}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${fmtFull.format(Math.round(v))}</text>`;} | |
| 1096 | + const X=(i,n)=>PL+cw*i/((n-1)||1),Y=v=>PT+ch*(1-(v-vmin)/rng); | |
| 1097 | + const paths=series.map((s,si)=>{if(hide[si])return""; | |
| 1098 | + const st=ML_STYLES[si]; | |
| 1099 | + const d=s.points.map((p,i)=>`${i?"L":"M"}${X(i,s.points.length).toFixed(1)},${Y(p.v).toFixed(1)}`).join(""); | |
| 1100 | + return `<path d="${d}" fill="none" stroke="${st.stroke}" stroke-width="${st.w}"${st.dash?` stroke-dasharray="${st.dash}"`:""}/>`;}).join(""); | |
| 1101 | + const ref=series[0].points; | |
| 1102 | + const xl=[0,Math.floor(ref.length/2),ref.length-1].map(i=> | |
| 1103 | + `<text x="${X(i,ref.length).toFixed(1)}" y="${H-8}" text-anchor="middle" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${esc(ref[i].t)}</text>`).join(""); | |
| 1104 | + const leg=series.map((s,si)=>`<button type="button" class="leg-btn" data-mls="${si}" aria-pressed="${!hide[si]}" | |
| 1105 | + title="${ML_STYLES[si].name}"><span class="leg-swatch ${ML_STYLES[si].cls}"></span>${esc(s.label)}</button>`).join(""); | |
| 1106 | + return `<div class="viz-card"> | |
| 1107 | + <div style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px;align-items:center"> | |
| 1108 | + <h2>${esc(ms.title)}</h2><span class="lc-legend">${leg}</span></div> | |
| 1109 | + <svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(ms.title)}" style="margin-top:10px"> | |
| 1110 | + ${grid}${xl}${paths} | |
| 1111 | + <g class="lc-cursor" style="display:none"><line y1="${PT}" y2="${H-PB}" stroke="var(--ink)" stroke-dasharray="2 3"/></g> | |
| 1112 | + </svg><span class="chip lc-tip"> </span></div>`; | |
| 1113 | +} | |
| 1114 | +function mountMulti(el,ms){ | |
| 1115 | + const hide=ST.hide["ml:"+ms.id]||(ST.hide["ml:"+ms.id]={}); | |
| 1116 | + const series=(ms.series||[]).filter(s=>(s.points||[]).length>1).slice(0,4); | |
| 1117 | + const render=()=>{ | |
| 1118 | + el.innerHTML=multiFigure(ms,hide); | |
| 1119 | + el.querySelectorAll("[data-mls]").forEach(b=>b.addEventListener("click",()=>{ | |
| 1120 | + hide[b.dataset.mls]=!hide[b.dataset.mls];render();})); | |
| 1121 | + const svg=el.querySelector("svg");if(!svg||!series.length)return; | |
| 1122 | + const W=720,PL=54,PR=12,n=series[0].points.length; | |
| 1123 | + const cursor=el.querySelector(".lc-cursor"),tip=el.querySelector(".lc-tip"); | |
| 1124 | + const cl=cursor?cursor.querySelector("line"):null; | |
| 1125 | + svg.addEventListener("pointermove",e=>{ | |
| 1126 | + const r=svg.getBoundingClientRect(); | |
| 1127 | + const fx=(e.clientX-r.left)/r.width*W; | |
| 1128 | + let i=Math.round((fx-PL)/(W-PL-PR)*(n-1));i=Math.max(0,Math.min(n-1,i)); | |
| 1129 | + const x=(PL+(W-PL-PR)*i/((n-1)||1)).toFixed(1); | |
| 1130 | + if(cl){cl.setAttribute("x1",x);cl.setAttribute("x2",x);cursor.style.display="";} | |
| 1131 | + const vals=series.map((s,si)=>hide[si]?null:`${esc(s.label)} : <b> ${fmtFull.format((s.points[i]||{}).v??0)}</b>`).filter(Boolean).join(" · "); | |
| 1132 | + tip.innerHTML=`${esc(series[0].points[i].t)} — ${vals}${ms.unit?` <span style="color:var(--ink-3)">${esc(ms.unit)}</span>`:""}`; | |
| 1133 | + tip.style.visibility="visible";}); | |
| 1134 | + svg.addEventListener("pointerleave",()=>{if(cursor)cursor.style.display="none";tip.style.visibility="hidden"}); | |
| 1135 | + }; | |
| 1136 | + render(); | |
| 1137 | +} | |
| 1138 | + | |
| 1139 | +/* --- barres empilées (composition dans le temps, nuances d'accent) --- */ | |
| 1140 | +function stackedHtml(st){ | |
| 1141 | + const keys=(st.keys||[]).slice(0,6),pts=st.points||[]; | |
| 1142 | + if(!keys.length||!pts.length)return emptyBlock(st.title); | |
| 1143 | + const totals=pts.map(p=>(p.values||[]).slice(0,keys.length).reduce((a,b)=>a+(b||0),0)); | |
| 1144 | + if(!totals.some(t=>t>0))return emptyBlock(st.title); | |
| 1145 | + const W=720,H=250,PL=54,PR=12,PT=14,PB=26,cw=W-PL-PR,ch=H-PT-PB; | |
| 1146 | + const vmax=Math.max(...totals,1),shades=[1,.78,.58,.42,.3,.22]; | |
| 1147 | + let grid=""; | |
| 1148 | + for(let k=0;k<5;k++){const y=PT+ch*k/4,v=vmax*(4-k)/4; | |
| 1149 | + grid+=`<line x1="${PL}" x2="${W-PR}" y1="${y.toFixed(1)}" y2="${y.toFixed(1)}" stroke="var(--line)"/> | |
| 1150 | + <text x="${PL-6}" y="${(y+3).toFixed(1)}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${fmtFull.format(Math.round(v))}</text>`;} | |
| 1151 | + const n=pts.length,bw=Math.max(2,cw/n-3); | |
| 1152 | + const bars=pts.map((p,i)=>{let y=PT+ch;const x=PL+cw*i/n+1.5; | |
| 1153 | + return keys.map((k,j)=>{const v=(p.values||[])[j]||0;if(!v)return""; | |
| 1154 | + const bh=ch*v/vmax;y-=bh; | |
| 1155 | + return `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${bw.toFixed(1)}" height="${Math.max(bh-.4,.5).toFixed(1)}" | |
| 1156 | + fill="var(--accent)" fill-opacity="${shades[j%6]}" stroke="var(--paper)" stroke-width="0.4"> | |
| 1157 | + <title>${esc(p.t)} · ${esc(k)} — ${fmtFull.format(v)}${st.unit?" "+esc(st.unit):""} (total ${fmtFull.format(totals[i])})</title></rect>`;}).join("");}).join(""); | |
| 1158 | + const lblIdx=[0,Math.floor(n/2),n-1]; | |
| 1159 | + const xl=lblIdx.map(i=>`<text x="${(PL+cw*i/n+bw/2).toFixed(1)}" y="${H-8}" text-anchor="middle" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${esc(String(pts[i].t))}</text>`).join(""); | |
| 1160 | + const leg=keys.map((k,j)=>`<span class="leg-btn" style="min-height:auto"><span class="dsw" style="width:11px;height:11px;border-radius:3px;border:1px solid var(--ink);background:var(--accent);opacity:${shades[j%6]};display:inline-block"></span> ${esc(k)}</span>`).join(""); | |
| 1161 | + return `<div class="viz-card"> | |
| 1162 | + <div style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px;align-items:center"> | |
| 1163 | + <h2>${esc(st.title)}</h2><span class="lc-legend">${leg}</span></div> | |
| 1164 | + <svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(st.title)}" style="margin-top:10px">${grid}${bars}${xl}</svg></div>`; | |
| 1165 | +} | |
| 1166 | + | |
| 1167 | +/* --- heatmap horaire 7 × 24 (dow 0=lun … 6=dim) --- */ | |
| 1168 | +function hourHeatHtml(h){ | |
| 1169 | + const cells=h&&h.cells||[]; | |
| 1170 | + if(!cells.length)return emptyBlock(h?h.title:"Activité horaire"); | |
| 1171 | + const grid=new Map(cells.map(c=>[c.dow+":"+c.hour,c.value||0])); | |
| 1172 | + const max=Math.max(...cells.map(c=>c.value||0),1); | |
| 1173 | + const CS=22,LX=42,LY=18,DOWS=["Lun","Mar","Mer","Jeu","Ven","Sam","Dim"]; | |
| 1174 | + let out=""; | |
| 1175 | + [0,6,12,18,23].forEach(hh=>{out+=`<text x="${LX+hh*CS+CS/2}" y="12" text-anchor="middle" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${hh} h</text>`;}); | |
| 1176 | + for(let d=0;d<7;d++){ | |
| 1177 | + out+=`<text x="${LX-6}" y="${LY+d*CS+CS/2+3.5}" text-anchor="end" font-size="10" fill="var(--ink-3)" font-family="var(--font-mono)">${DOWS[d]}</text>`; | |
| 1178 | + for(let hh=0;hh<24;hh++){const v=grid.get(d+":"+hh)||0; | |
| 1179 | + out+=`<rect x="${LX+hh*CS}" y="${LY+d*CS}" width="${CS-2.5}" height="${CS-2.5}" rx="3.5" | |
| 1180 | + fill="${v?"var(--accent)":"rgba(20,24,20,0.06)"}" fill-opacity="${v?(0.2+0.8*v/max).toFixed(2):1}" | |
| 1181 | + stroke="rgba(20,24,20,0.14)" stroke-width="0.5"><title>${DOWS[d]} ${hh} h — ${fmtFull.format(v)}</title></rect>`;}} | |
| 1182 | + return `<div class="viz-card hh"><h2>${esc(h.title)}</h2><div class="viz-sub">7 jours × 24 heures (heure de l'Est)</div> | |
| 1183 | + <div class="tbl-wrap"><svg viewBox="0 0 ${LX+24*CS} ${LY+7*CS}" role="img" aria-label="${esc(h.title)}">${out}</svg></div></div>`; | |
| 990 | 1184 | } |
| 991 | 1185 | |
| 992 | 1186 | /* --- courbe SVG : infobulle (pointeur), légende cliquable, comparaison N-1 --- */ |
@@ -1019,14 +1213,16 @@ function lineFigure(s,hide){ | ||
| 1019 | 1213 | <svg viewBox="0 0 ${g.W} ${g.H}" role="img" aria-label="${esc(s.title)}" style="margin-top:10px"> |
| 1020 | 1214 | ${grid}${xl} |
| 1021 | 1215 | ${!hide.cmp&&s.compare&&s.compare.length>1?`<path d="${path(s.compare)}" fill="none" stroke="var(--ink-3)" stroke-width="1.4" stroke-dasharray="4 4"/>`:""} |
| 1216 | + ${!hide.cur&&s.kind==="area"?`<path d="${path(pts)} L${X(pts.length-1).toFixed(1)},${(H-PB).toFixed(1)} L${X(0).toFixed(1)},${(H-PB).toFixed(1)} Z" fill="var(--accent)" fill-opacity=".12" stroke="none"/>`:""} | |
| 1022 | 1217 | ${!hide.cur?`<path d="${path(pts)}" fill="none" stroke="var(--accent)" stroke-width="2.4"/>`:""} |
| 1023 | 1218 | <g class="lc-cursor" style="display:none"> |
| 1024 | 1219 | <line y1="${PT}" y2="${H-PB}" stroke="var(--ink)" stroke-dasharray="2 3"/> |
| 1025 | 1220 | <circle r="4" fill="var(--accent)" stroke="var(--ink)" stroke-width="1.5"/></g> |
| 1026 | − </svg><span class="chip lc-tip"> </span>`+ | |
| 1221 | + </svg><span class="chip lc-tip"> </span>`+statSummary(s)+ | |
| 1027 | 1222 | `</div>`; |
| 1028 | 1223 | } |
| 1029 | 1224 | function mountLine(el,s){ |
| 1225 | + if(s.kind==="bar"){el.innerHTML=vbarsHtml(s);return;} | |
| 1030 | 1226 | const hide=ST.hide[s.id]||(ST.hide[s.id]={cur:false,cmp:false}); |
| 1031 | 1227 | const render=()=>{ |
| 1032 | 1228 | el.innerHTML=lineFigure(s,hide); |
@@ -1080,10 +1276,10 @@ function barsHtml(title,items,sub){ | ||
| 1080 | 1276 | if(!rows.length)return emptyBlock(title); |
| 1081 | 1277 | const max=Math.max(...rows.map(r=>r.value),1); |
| 1082 | 1278 | return `<div class="viz-card"><h2>${esc(title)}</h2>${sub?`<div class="viz-sub">${esc(sub)}</div>`:`<div style="height:14px"></div>`} |
| 1083 | − ${rows.map(r=>`<div class="hrow" title="${esc(r.label)} — ${fmtFull.format(r.value)}"> | |
| 1279 | + ${rows.map(r=>`<div class="hrow" title="${esc(r.label)} — ${fmtFull.format(r.value)}${r.delta_pct!=null?` (${fmtPct(r.delta_pct)} sur la période)`:""}"> | |
| 1084 | 1280 | <span class="hrow-label">${esc(r.label)}</span> |
| 1085 | 1281 | <span class="hbar"><i style="width:${Math.max(2,Math.round(r.value/max*100))}%"></i></span> |
| 1086 | − <span class="n">${fmtFull.format(r.value)}</span></div>`).join("")}</div>`; | |
| 1282 | + <span class="n">${fmtFull.format(r.value)}</span>${r.delta_pct!=null?`<span class="d ${r.delta_pct>=0?"up":"down"}">${r.delta_pct>=0?"▲":"▼"} ${fmtPct(r.delta_pct)}</span>`:""}</div>`).join("")}</div>`; | |
| 1087 | 1283 | } |
| 1088 | 1284 | |
| 1089 | 1285 | /* --- calendrier de chaleur (26 dernières semaines) --- */ |
@@ -1164,22 +1360,43 @@ function bindPeriod(){ | ||
| 1164 | 1360 | const go=()=>{if(pf.value&&pt.value){ST.from=pf.value;ST.to=pt.value;loadStatsData();}}; |
| 1165 | 1361 | pf.addEventListener("change",go);pt.addEventListener("change",go); |
| 1166 | 1362 | } |
| 1363 | +/* --- menu PDF : 5 rapports (équivalent vanilla du PdfButton v2) --- */ | |
| 1364 | +const PDF_MODES=[ | |
| 1365 | + ["synthese","Synthèse exécutive","Couverture, KPI, jauges & records (2-3 p.)"], | |
| 1366 | + ["tendances","Tendances & évolution","Toutes les séries + min/max/moy/méd/σ"], | |
| 1367 | + ["repartitions","Répartitions & géographie","Anneaux, distributions, géo, activité horaire"], | |
| 1368 | + ["donnees","Données détaillées","Tous les tableaux en version longue (400 lignes)"]]; | |
| 1369 | +function pdfActionsHtml(){ | |
| 1370 | + return `<span class="pdf-actions pdf-menu-wrap"> | |
| 1371 | + <button type="button" class="btn btn-primary" data-pdf="complet">⬇ Rapport PDF complet</button> | |
| 1372 | + <button type="button" class="btn btn-ghost" id="pdf-more" aria-haspopup="true" aria-expanded="false">Autres rapports ▾</button> | |
| 1373 | + <div class="pdf-menu" id="pdf-menu" role="menu"> | |
| 1374 | + ${PDF_MODES.map(([m,l,d])=>`<button type="button" role="menuitem" data-pdf="${m}">${l}<small>${d}</small></button>`).join("")} | |
| 1375 | + </div></span>`; | |
| 1376 | +} | |
| 1167 | 1377 | function bindPdf(){ |
| 1168 | 1378 | const url=m=>{const p=new URLSearchParams({period:ST.period,mode:m}); |
| 1169 | 1379 | if(ST.from&&ST.to){p.set("from",ST.from);p.set("to",ST.to);} |
| 1170 | 1380 | return "/api/stats/report?"+p;}; |
| 1171 | − [["pdf-full","complet"],["pdf-syn","synthese"]].forEach(([id,m])=>{ | |
| 1172 | − const b=document.getElementById(id);if(!b)return; | |
| 1381 | + const menu=document.getElementById("pdf-menu"),more=document.getElementById("pdf-more"); | |
| 1382 | + if(more&&menu){ | |
| 1383 | + more.addEventListener("click",e=>{e.stopPropagation(); | |
| 1384 | + const open=menu.classList.toggle("open");more.setAttribute("aria-expanded",open); | |
| 1385 | + if(open)document.addEventListener("click",()=>{menu.classList.remove("open"); | |
| 1386 | + more.setAttribute("aria-expanded","false");},{once:true});});} | |
| 1387 | + document.querySelectorAll("[data-pdf]").forEach(b=>{ | |
| 1173 | 1388 | b.addEventListener("click",async()=>{ |
| 1174 | − const t=b.textContent;b.disabled=true;b.textContent="Génération…"; | |
| 1175 | − try{const r=await fetch(url(m));if(!r.ok)throw new Error(r.status); | |
| 1389 | + if(menu)menu.classList.remove("open"); | |
| 1390 | + const t=b.innerHTML;b.disabled=true; | |
| 1391 | + b.innerHTML=b.closest(".pdf-menu")?"Génération…":"⏳ Génération…"; | |
| 1392 | + try{const r=await fetch(url(b.dataset.pdf));if(!r.ok)throw new Error(r.status); | |
| 1176 | 1393 | const blob=await r.blob(); |
| 1177 | 1394 | const fn=((r.headers.get("Content-Disposition")||"").match(/filename="?([^";]+)/)||[])[1]||"rapport-crea-ka.pdf"; |
| 1178 | 1395 | const a=document.createElement("a");a.href=URL.createObjectURL(blob);a.download=fn; |
| 1179 | 1396 | document.body.appendChild(a);a.click();a.remove(); |
| 1180 | 1397 | setTimeout(()=>URL.revokeObjectURL(a.href),4000);} |
| 1181 | 1398 | catch(e){alert("Échec de la génération du PDF — réessayez.");} |
| 1182 | − b.disabled=false;b.textContent=t;});}); | |
| 1399 | + b.disabled=false;b.innerHTML=t;});}); | |
| 1183 | 1400 | } |
| 1184 | 1401 | |
| 1185 | 1402 | async function renderStats(){ |
@@ -1200,8 +1417,10 @@ async function loadStatsData(first){ | ||
| 1200 | 1417 | function renderStatsPage(){ |
| 1201 | 1418 | const d=ST.data; |
| 1202 | 1419 | const upd=new Date(d.updated).toLocaleString("fr-CA",{dateStyle:"medium",timeStyle:"short"}); |
| 1203 | − const donut=(d.breakdowns||[]).find(b=>b.kind==="donut"); | |
| 1420 | + const donuts=(d.breakdowns||[]).filter(b=>b.kind==="donut"); | |
| 1204 | 1421 | const barsB=(d.breakdowns||[]).filter(b=>b.kind!=="donut"); |
| 1422 | + const gauges=(d.gauges||[]).filter(g=>typeof g.value==="number"&&g.max); | |
| 1423 | + const hasEvo=(d.series||[]).length||(d.multiseries||[]).length||(d.stacked||[]).length; | |
| 1205 | 1424 | app.innerHTML=header()+` |
| 1206 | 1425 | <div class="container stats-page" id="stats-main"> |
| 1207 | 1426 | <div class="stats-head"> |
@@ -1209,32 +1428,40 @@ function renderStatsPage(){ | ||
| 1209 | 1428 | <h1 style="font-size:clamp(28px,4.6vw,46px);margin:12px 0 0;text-transform:uppercase">Les créateurs québécois <span class="hl">en chiffres.</span></h1> |
| 1210 | 1429 | <div class="fresh-row"><span>Mis à jour le ${esc(upd)}</span> |
| 1211 | 1430 | <button type="button" class="btn btn-ghost" id="st-refresh">↻ Rafraîchir</button></div></div> |
| 1212 | − <span class="pdf-actions"> | |
| 1213 | − <button type="button" class="btn btn-primary" id="pdf-full">⬇ Télécharger le rapport PDF</button> | |
| 1214 | − <button type="button" class="btn btn-ghost" id="pdf-syn">Synthèse (2 p.)</button></span> | |
| 1431 | + ${pdfActionsHtml()} | |
| 1215 | 1432 | </div> |
| 1216 | 1433 | <div class="tiles">${(d.kpis||[]).map(kpiHtml).join("")||emptyBlock("Indicateurs")}</div> |
| 1217 | 1434 | ${periodBar()} |
| 1218 | 1435 | <p class="klabel" style="margin:6px 0 0">Période analysée : ${esc(d.period.from)} → ${esc(d.period.to)}</p> |
| 1436 | + ${gauges.length?`<h2 class="stats-sect">Taux & couvertures</h2> | |
| 1437 | + <div class="gauges">${gauges.map(gaugeHtml).join("")}</div>`:""} | |
| 1219 | 1438 | <h2 class="stats-sect">Évolution</h2> |
| 1220 | − <div class="viz-grid">${(d.series||[]).map(s=>`<div class="lc" data-serie="${esc(s.id)}"></div>`).join("")||emptyBlock("Évolution")}</div> | |
| 1221 | − <h2 class="stats-sect">Répartitions</h2> | |
| 1439 | + ${hasEvo?`<div class="viz-grid"> | |
| 1440 | + ${(d.series||[]).map(s=>`<div class="lc" data-serie="${esc(s.id)}"></div>`).join("")} | |
| 1441 | + ${(d.multiseries||[]).map(m=>`<div class="lc" data-multi="${esc(m.id)}"></div>`).join("")} | |
| 1442 | + ${(d.stacked||[]).map(st=>stackedHtml(st)).join("")} | |
| 1443 | + </div>`:emptyBlock("Évolution")} | |
| 1444 | + <h2 class="stats-sect">Répartitions & distributions</h2> | |
| 1222 | 1445 | <div class="viz-grid two"> |
| 1223 | − ${donut?donutHtml(donut):""} | |
| 1446 | + ${donuts.map(donutHtml).join("")} | |
| 1224 | 1447 | ${barsB.map(b=>barsHtml(b.title,b.items)).join("")} |
| 1225 | − ${d.geo?barsHtml(d.geo.title,d.geo.items):""} | |
| 1448 | + ${(d.distributions||[]).map(vbarsHtml).join("")} | |
| 1226 | 1449 | </div> |
| 1227 | − ${d.heatmap?`<h2 class="stats-sect">Activité</h2>${heatmapHtml(d.heatmap)}`:""} | |
| 1450 | + ${d.geo?`<h2 class="stats-sect">Répartition géographique</h2> | |
| 1451 | + <div class="viz-grid two">${barsHtml(d.geo.title,d.geo.items)}</div>`:""} | |
| 1452 | + ${d.heatmap||d.hourly?`<h2 class="stats-sect">Activité</h2> | |
| 1453 | + ${d.heatmap?heatmapHtml(d.heatmap):""}${d.hourly?hourHeatHtml(d.hourly):""}`:""} | |
| 1228 | 1454 | ${(d.tables||[]).length?`<h2 class="stats-sect">Détails</h2><div style="display:grid;gap:22px">${(d.tables||[]).map(t=>`<div class="dt" data-table="${esc(t.id)}"></div>`).join("")}</div>`:""} |
| 1229 | 1455 | ${(d.records||[]).length?`<h2 class="stats-sect">Records & faits marquants</h2> |
| 1230 | 1456 | <div class="records-grid">${d.records.map(r=>`<div class="record"><span class="r-lbl">${esc(r.label)}</span> |
| 1231 | 1457 | <span style="text-align:right"><span class="r-val">${esc(r.value)}</span>${r.date?`<span class="klabel" style="display:block">${esc(r.date)}</span>`:""}</span></div>`).join("")}</div>`:""} |
| 1232 | 1458 | <p style="font-size:12px;color:var(--ink-3);margin-top:30px">Données réelles de l'annuaire (fiches actives, comptes vérifiés) — aucune statistique estimée ou inventée. |
| 1233 | − Rapport PDF estampillé Groupe-KA disponible en haut de page.</p> | |
| 1459 | + Rapports PDF estampillés Groupe-KA (5 formats) disponibles en haut de page.</p> | |
| 1234 | 1460 | </div>`+footer()+tabbar("stats"); |
| 1235 | 1461 | bindNav();bindPeriod();bindPdf(); |
| 1236 | 1462 | $("#st-refresh").addEventListener("click",()=>loadStatsData()); |
| 1237 | 1463 | (ST.data.series||[]).forEach(s=>{const el=document.querySelector(`.lc[data-serie="${s.id}"]`);if(el)mountLine(el,s);}); |
| 1464 | + (ST.data.multiseries||[]).forEach(m=>{const el=document.querySelector(`.lc[data-multi="${m.id}"]`);if(el)mountMulti(el,m);}); | |
| 1238 | 1465 | (ST.data.tables||[]).forEach(t=>{const el=document.querySelector(`.dt[data-table="${t.id}"]`);if(el)mountTable(el,t);}); |
| 1239 | 1466 | } |
| 1240 | 1467 | |
modified
frontend/src/ka-agent.js
+177 −48
@@ -3,7 +3,11 @@ | ||
| 3 | 3 | * Groupe KA. Vanilla JS, zéro dépendance, injecté sur les 13 sites. |
| 4 | 4 | * <script>window.KA_AGENT={site:"lou-ka"}</script> |
| 5 | 5 | * <script src="/ka-agent.js" defer></script> |
| 6 | − * Bulle flottante en bas à droite → panneau de chat (bulle) → plein écran (⛶). | |
| 6 | + * v2 (2026-08-19) : ouverture directement PLEIN ÉCRAN (desktop et mobile, | |
| 7 | + * bouton ▭ pour réduire en fenêtre sur desktop) ; sur téléphone le panneau se | |
| 8 | + * cale sur window.visualViewport (le clavier ne fait plus grossir/défiler la | |
| 9 | + * page — fond verrouillé par body position:fixed) ; rendu MARKDOWN complet en | |
| 10 | + * streaming (titres, listes, tableaux, code, liens nommés, citations). | |
| 7 | 11 | * Flux SSE en direct depuis le backend central (texte token par token + |
| 8 | 12 | * indicateur d'outil). Historique conservé en localStorage (par site). |
| 9 | 13 | */ |
@@ -21,60 +25,147 @@ | ||
| 21 | 25 | border-radius:50%;border:2px solid var(--ink,#141814);background:var(--accent,#d9f26b); |
| 22 | 26 | color:var(--on-accent,#141814);font:700 17px/1 "Space Grotesk",system-ui,sans-serif; |
| 23 | 27 | cursor:pointer;box-shadow:4px 4px 0 rgba(20,24,20,.85);display:flex;align-items:center; |
| 24 | − justify-content:center;transition:transform .15s} | |
| 28 | + justify-content:center;transition:transform .15s;touch-action:manipulation} | |
| 25 | 29 | .kaa-btn:hover{transform:translate(-2px,-2px)} |
| 26 | − .kaa-panel{position:fixed;right:16px;bottom:calc(86px + env(safe-area-inset-bottom,0px));z-index:2147483001;width:min(392px,calc(100vw - 24px)); | |
| 27 | − height:min(580px,calc(100vh - 110px));height:min(580px,calc(100dvh - 110px));display:none;flex-direction:column;background:var(--paper,#f5f3ee); | |
| 28 | − border:2px solid var(--ink,#141814);border-radius:14px;box-shadow:8px 8px 0 rgba(20,24,20,.85); | |
| 29 | − overflow:hidden;font-family:Inter,system-ui,sans-serif} | |
| 30 | + .kaa-panel{position:fixed;z-index:2147483001;display:none;flex-direction:column;background:var(--paper,#f5f3ee); | |
| 31 | + overflow:hidden;font-family:Inter,system-ui,sans-serif;touch-action:manipulation} | |
| 30 | 32 | .kaa-panel.kaa-open{display:flex} |
| 31 | − .kaa-panel.kaa-full{right:0;bottom:0;width:100vw;height:100vh;height:100dvh;border-radius:0;border:0;box-shadow:none} | |
| 32 | − html.kaa-lock,html.kaa-lock body{overflow:hidden!important;overscroll-behavior:none} | |
| 33 | + .kaa-panel.kaa-full{left:0;top:0;right:0;bottom:0;width:100vw;height:100vh;height:100dvh;border:0;border-radius:0;box-shadow:none} | |
| 34 | + .kaa-panel:not(.kaa-full){right:16px;bottom:calc(86px + env(safe-area-inset-bottom,0px));width:min(392px,calc(100vw - 24px)); | |
| 35 | + height:min(580px,calc(100vh - 110px));height:min(580px,calc(100dvh - 110px)); | |
| 36 | + border:2px solid var(--ink,#141814);border-radius:14px;box-shadow:8px 8px 0 rgba(20,24,20,.85)} | |
| 37 | + html.kaa-lock,html.kaa-lock body{overflow:hidden!important;overscroll-behavior:none;touch-action:none} | |
| 33 | 38 | .kaa-head{display:flex;align-items:center;gap:9px;padding:11px 14px;background:var(--ink,#141814); |
| 34 | − color:var(--paper,#f5f3ee);flex:none} | |
| 39 | + color:var(--paper,#f5f3ee);flex:none;padding-top:max(11px,env(safe-area-inset-top,0px))} | |
| 35 | 40 | .kaa-head b{font:700 15px "Space Grotesk",system-ui,sans-serif;letter-spacing:-.02em} |
| 36 | 41 | .kaa-head .kaa-ka{display:inline-block;background:var(--accent,#d9f26b);color:var(--on-accent,#141814); |
| 37 | 42 | border-radius:6px;padding:1px 7px 2px;transform:rotate(-2deg);font-weight:700} |
| 38 | 43 | .kaa-head small{font:700 9.5px "JetBrains Mono",monospace;letter-spacing:.09em;text-transform:uppercase;opacity:.65} |
| 39 | 44 | .kaa-head .kaa-sp{flex:1} |
| 40 | 45 | .kaa-hbtn{width:34px;height:34px;border:1.5px solid rgba(245,243,238,.4);border-radius:8px;background:none; |
| 41 | − color:var(--paper,#f5f3ee);font-size:15px;cursor:pointer;line-height:1} | |
| 46 | + color:var(--paper,#f5f3ee);font-size:15px;cursor:pointer;line-height:1;flex:none} | |
| 42 | 47 | .kaa-hbtn:hover{border-color:var(--accent,#d9f26b);color:var(--accent,#d9f26b)} |
| 43 | 48 | .kaa-log{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:10px; |
| 44 | 49 | overscroll-behavior:contain;-webkit-overflow-scrolling:touch} |
| 45 | 50 | .kaa-msg{max-width:86%;padding:9px 13px;border:1.5px solid var(--ink,#141814);border-radius:12px; |
| 46 | − font-size:13.5px;line-height:1.5;white-space:pre-wrap;word-break:break-word} | |
| 51 | + font-size:13.5px;line-height:1.55;word-break:break-word} | |
| 52 | + .kaa-full .kaa-msg{max-width:min(86%,760px)} | |
| 53 | + .kaa-full .kaa-log{align-items:stretch} | |
| 47 | 54 | .kaa-msg.kaa-u{align-self:flex-end;background:var(--accent,#d9f26b);color:var(--on-accent,#141814); |
| 48 | − border-bottom-right-radius:4px} | |
| 55 | + border-bottom-right-radius:4px;white-space:pre-wrap} | |
| 49 | 56 | .kaa-msg.kaa-a{align-self:flex-start;background:#fff;border-bottom-left-radius:4px;box-shadow:3px 3px 0 rgba(20,24,20,.12)} |
| 50 | − .kaa-msg.kaa-a a{color:inherit;text-decoration:underline;text-underline-offset:3px} | |
| 51 | − .kaa-msg.kaa-a b{font-weight:700} | |
| 57 | + .kaa-msg.kaa-a a{color:inherit;text-decoration:underline;text-underline-offset:3px;font-weight:600} | |
| 58 | + .kaa-msg.kaa-a p{margin:.35em 0} | |
| 59 | + .kaa-msg.kaa-a p:first-child{margin-top:0} | |
| 60 | + .kaa-msg.kaa-a p:last-child{margin-bottom:0} | |
| 61 | + .kaa-msg.kaa-a h1,.kaa-msg.kaa-a h2,.kaa-msg.kaa-a h3,.kaa-msg.kaa-a h4{ | |
| 62 | + font:700 14px "Space Grotesk",system-ui,sans-serif;letter-spacing:-.01em;margin:.7em 0 .3em} | |
| 63 | + .kaa-msg.kaa-a h1:first-child,.kaa-msg.kaa-a h2:first-child,.kaa-msg.kaa-a h3:first-child,.kaa-msg.kaa-a h4:first-child{margin-top:.1em} | |
| 64 | + .kaa-msg.kaa-a h1{font-size:15.5px}.kaa-msg.kaa-a h2{font-size:14.5px} | |
| 65 | + .kaa-msg.kaa-a ul,.kaa-msg.kaa-a ol{margin:.35em 0;padding-left:1.35em} | |
| 66 | + .kaa-msg.kaa-a li{margin:.18em 0} | |
| 67 | + .kaa-msg.kaa-a code{font:600 12px "JetBrains Mono",monospace;background:var(--surface-2,#f0eee7); | |
| 68 | + border:1px solid rgba(20,24,20,.15);border-radius:5px;padding:.5px 4px} | |
| 69 | + .kaa-msg.kaa-a pre{margin:.45em 0;padding:9px 11px;background:var(--ink,#141814);color:var(--paper,#f5f3ee); | |
| 70 | + border-radius:9px;overflow-x:auto} | |
| 71 | + .kaa-msg.kaa-a pre code{background:none;border:0;color:inherit;padding:0;font-weight:400;font-size:11.5px;line-height:1.5} | |
| 72 | + .kaa-msg.kaa-a blockquote{margin:.45em 0;padding:.15em .8em;border-left:3px solid var(--accent,#d9f26b); | |
| 73 | + background:var(--surface-2,#faf9f5);color:var(--ink-2,#4d5551)} | |
| 74 | + .kaa-msg.kaa-a hr{border:0;border-top:1.5px dashed rgba(20,24,20,.3);margin:.6em 0} | |
| 75 | + .kaa-msg.kaa-a table{border-collapse:collapse;margin:.45em 0;font-size:12.5px;display:block;overflow-x:auto;max-width:100%} | |
| 76 | + .kaa-msg.kaa-a th,.kaa-msg.kaa-a td{border:1.5px solid var(--ink,#141814);padding:4px 9px;text-align:left;white-space:nowrap} | |
| 77 | + .kaa-msg.kaa-a th{background:var(--accent,#d9f26b);color:var(--on-accent,#141814); | |
| 78 | + font:700 11px "Space Grotesk",system-ui,sans-serif;letter-spacing:.02em} | |
| 79 | + .kaa-msg.kaa-a td{background:#fff} | |
| 52 | 80 | .kaa-tool{align-self:flex-start;font:700 10px "JetBrains Mono",monospace;letter-spacing:.07em; |
| 53 | 81 | text-transform:uppercase;color:var(--ink-2,#4d5551);padding:3px 10px;border:1.5px dashed var(--ink-2,#4d5551); |
| 54 | 82 | border-radius:999px;background:var(--surface-2,#faf9f5)} |
| 55 | 83 | .kaa-in{display:flex;gap:8px;padding:11px;border-top:2px solid var(--ink,#141814);background:#fff;flex:none; |
| 56 | 84 | padding-bottom:calc(11px + env(safe-area-inset-bottom,0))} |
| 85 | + .kaa-full .kaa-in{justify-content:center} | |
| 86 | + .kaa-full .kaa-in textarea{max-width:700px} | |
| 57 | 87 | .kaa-in textarea{flex:1;resize:none;min-height:44px;max-height:110px;padding:10px 12px;font:16px/1.4 Inter,system-ui,sans-serif; |
| 58 | 88 | border:1.5px solid var(--ink,#141814);border-radius:9px;background:var(--paper,#f5f3ee);outline:none} |
| 59 | 89 | .kaa-in button{min-width:52px;min-height:44px;border:1.5px solid var(--ink,#141814);border-radius:9px; |
| 60 | − background:var(--ink,#141814);color:var(--accent,#d9f26b);font:700 16px "Space Grotesk",system-ui;cursor:pointer} | |
| 90 | + background:var(--ink,#141814);color:var(--accent,#d9f26b);font:700 16px "Space Grotesk",system-ui;cursor:pointer;touch-action:manipulation} | |
| 61 | 91 | .kaa-in button:disabled{opacity:.45} |
| 62 | − .kaa-hello{font-size:12.5px;color:var(--ink-2,#4d5551);padding:4px 2px} | |
| 92 | + .kaa-hello{font-size:12.5px;color:var(--ink-2,#4d5551);padding:4px 2px;max-width:760px} | |
| 63 | 93 | .kaa-dots::after{content:"…";animation:kaa-b 1.2s infinite} |
| 64 | 94 | @keyframes kaa-b{0%{opacity:.2}50%{opacity:1}100%{opacity:.2}} |
| 65 | − @media (max-width:560px){.kaa-panel{right:8px;left:8px;width:auto}} | |
| 95 | + @media (max-width:640px){.kaa-x1{display:none}} | |
| 66 | 96 | `; |
| 67 | 97 | |
| 68 | − /* ---------- markdown minimal (gras, liens, puces) — texte échappé d'abord ---------- */ | |
| 98 | + /* ---------- markdown complet (rendu en streaming, texte échappé d'abord) ---------- */ | |
| 69 | 99 | function esc(s) { |
| 70 | 100 | return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); |
| 71 | 101 | } |
| 72 | − function md(s) { | |
| 73 | − return esc(s) | |
| 74 | − .replace(/\*\*([^*]+)\*\*/g, "<b>$1</b>") | |
| 75 | − .replace(/(https?:\/\/[^\s<)"']+)/g, function (u) { | |
| 76 | − return '<a href="' + u + '" target="_blank" rel="noopener noreferrer">' + u.replace(/^https?:\/\/(www\.)?/, "").slice(0, 40) + "</a>"; | |
| 77 | − }); | |
| 102 | + function inline(s) { | |
| 103 | + s = esc(s); | |
| 104 | + s = s.replace(/`([^`\n]+)`/g, "<code>$1</code>"); | |
| 105 | + s = s.replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, | |
| 106 | + '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'); | |
| 107 | + s = s.replace(/\*\*([^*\n]+)\*\*/g, "<b>$1</b>"); | |
| 108 | + s = s.replace(/(^|[^*\w])\*([^*\n]+)\*(?!\*)/g, "$1<i>$2</i>"); | |
| 109 | + s = s.replace(/(^|[^"'>=\w])(https?:\/\/[^\s<)"']+)/g, function (m, pre, u) { | |
| 110 | + return pre + '<a href="' + u + '" target="_blank" rel="noopener noreferrer">' + | |
| 111 | + u.replace(/^https?:\/\/(www\.)?/, "").slice(0, 42) + "</a>"; | |
| 112 | + }); | |
| 113 | + return s; | |
| 114 | + } | |
| 115 | + function md(src) { | |
| 116 | + var lines = String(src).split("\n"), out = [], i = 0, m; | |
| 117 | + function para(buf) { if (buf.length) out.push("<p>" + buf.map(inline).join("<br>") + "</p>"); } | |
| 118 | + while (i < lines.length) { | |
| 119 | + var l = lines[i]; | |
| 120 | + if (/^\s*```/.test(l)) { /* bloc de code */ | |
| 121 | + var code = []; i++; | |
| 122 | + while (i < lines.length && !/^\s*```/.test(lines[i])) code.push(lines[i++]); | |
| 123 | + i++; | |
| 124 | + out.push("<pre><code>" + esc(code.join("\n")) + "</code></pre>"); | |
| 125 | + } else if ((m = l.match(/^\s*(#{1,4})\s+(.*)$/))) { /* titres */ | |
| 126 | + out.push("<h" + m[1].length + ">" + inline(m[2]) + "</h" + m[1].length + ">"); i++; | |
| 127 | + } else if (/^\s*(---+|\*\*\*+)\s*$/.test(l)) { /* filet */ | |
| 128 | + out.push("<hr>"); i++; | |
| 129 | + } else if (/^\s*>|^\s*>/.test(l)) { /* citation */ | |
| 130 | + var q = []; | |
| 131 | + while (i < lines.length && /^\s*>/.test(lines[i])) q.push(lines[i++].replace(/^\s*>\s?/, "")); | |
| 132 | + out.push("<blockquote>" + q.map(inline).join("<br>") + "</blockquote>"); | |
| 133 | + } else if (/^\s*\|.*\|\s*$/.test(l)) { /* tableau */ | |
| 134 | + var rows = []; | |
| 135 | + while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) { | |
| 136 | + var cells = lines[i].trim().replace(/^\||\|$/g, "").split("|").map(function (c) { return c.trim(); }); | |
| 137 | + if (!/^[:\-\s|]+$/.test(lines[i].replace(/\|/g, ""))) rows.push(cells); | |
| 138 | + i++; | |
| 139 | + } | |
| 140 | + if (rows.length) { | |
| 141 | + var t = "<table>"; | |
| 142 | + rows.forEach(function (r, ri) { | |
| 143 | + var tag = ri === 0 ? "th" : "td"; | |
| 144 | + t += "<tr>" + r.map(function (c) { return "<" + tag + ">" + inline(c) + "</" + tag + ">"; }).join("") + "</tr>"; | |
| 145 | + }); | |
| 146 | + out.push(t + "</table>"); | |
| 147 | + } | |
| 148 | + } else if (/^\s*[-*+]\s+/.test(l)) { /* liste à puces */ | |
| 149 | + var ul = []; | |
| 150 | + while (i < lines.length && /^\s*[-*+]\s+/.test(lines[i])) | |
| 151 | + ul.push("<li>" + inline(lines[i++].replace(/^\s*[-*+]\s+/, "")) + "</li>"); | |
| 152 | + out.push("<ul>" + ul.join("") + "</ul>"); | |
| 153 | + } else if (/^\s*\d+[.)]\s+/.test(l)) { /* liste numérotée */ | |
| 154 | + var ol = []; | |
| 155 | + while (i < lines.length && /^\s*\d+[.)]\s+/.test(lines[i])) | |
| 156 | + ol.push("<li>" + inline(lines[i++].replace(/^\s*\d+[.)]\s+/, "")) + "</li>"); | |
| 157 | + out.push("<ol>" + ol.join("") + "</ol>"); | |
| 158 | + } else if (!l.trim()) { i++; } /* ligne vide */ | |
| 159 | + else { /* paragraphe */ | |
| 160 | + var buf = []; | |
| 161 | + while (i < lines.length && lines[i].trim() && | |
| 162 | + !/^\s*(```|#{1,4}\s|[-*+]\s|\d+[.)]\s|>|\||---+\s*$)/.test(lines[i])) | |
| 163 | + buf.push(lines[i++]); | |
| 164 | + if (!buf.length) buf.push(lines[i++] || ""); | |
| 165 | + para(buf); | |
| 166 | + } | |
| 167 | + } | |
| 168 | + return out.join(""); | |
| 78 | 169 | } |
| 79 | 170 | |
| 80 | 171 | /* ---------- état ---------- */ |
@@ -98,10 +189,10 @@ | ||
| 98 | 189 | panel.setAttribute("aria-label", "KA Agent"); |
| 99 | 190 | panel.innerHTML = |
| 100 | 191 | '<div class="kaa-head"><b>KA<span class="kaa-ka">Agent</span></b><small>Groupe KA · IA</small><span class="kaa-sp"></span>' + |
| 101 | − '<button class="kaa-hbtn kaa-x1" title="Plein écran" aria-label="Plein écran">⛶</button>' + | |
| 192 | + '<button class="kaa-hbtn kaa-x1" title="Réduire / agrandir" aria-label="Réduire ou agrandir">▭</button>' + | |
| 102 | 193 | '<button class="kaa-hbtn kaa-x2" title="Fermer" aria-label="Fermer">✕</button></div>' + |
| 103 | 194 | '<div class="kaa-log"></div>' + |
| 104 | − '<div class="kaa-in"><textarea rows="1" placeholder="Posez votre question…" aria-label="Votre question"></textarea>' + | |
| 195 | + '<div class="kaa-in"><textarea rows="1" enterkeyhint="send" autocapitalize="sentences" autocomplete="off" placeholder="Posez votre question…" aria-label="Votre question"></textarea>' + | |
| 105 | 196 | "<button aria-label=\"Envoyer\">➤</button></div>"; |
| 106 | 197 | document.body.appendChild(btn); |
| 107 | 198 | document.body.appendChild(panel); |
@@ -132,45 +223,83 @@ | ||
| 132 | 223 | if (log.length) return; |
| 133 | 224 | var d = document.createElement("div"); |
| 134 | 225 | d.className = "kaa-hello"; |
| 135 | − d.textContent = "👋 Je suis KA Agent, l'assistant de l'écosystème Groupe KA. Posez-moi une question sur ce site, ses données (prix, annonces, stats…) ou sur le groupe."; | |
| 226 | + d.textContent = "👋 Je suis KA Agent, l'assistant de l'écosystème Groupe KA. Posez-moi une question sur ce site, ses données (prix, annonces, fiches, stats…) ou sur le groupe."; | |
| 136 | 227 | logEl.appendChild(d); |
| 137 | 228 | } |
| 138 | 229 | function render() { |
| 139 | 230 | logEl.innerHTML = ""; |
| 140 | 231 | hello(); |
| 141 | − log.forEach(function (m) { bubble(m.role === "user" ? "kaa-u" : "kaa-a", md(m.content)); }); | |
| 232 | + log.forEach(function (m) { | |
| 233 | + m.role === "user" ? bubble("kaa-u", esc(m.content)) : bubble("kaa-a", md(m.content)); | |
| 234 | + }); | |
| 142 | 235 | scroll(); |
| 143 | 236 | } |
| 144 | 237 | |
| 145 | − /* ---------- ouverture / plein écran ---------- */ | |
| 146 | − /* Sur téléphone : panneau plein écran d'office + scroll d'arrière-plan | |
| 147 | − verrouillé tant qu'il est ouvert (html.kaa-lock). Pas de focus clavier | |
| 148 | − forcé au tap (le clavier ne s'ouvre que si l'utilisateur touche le champ). */ | |
| 149 | − var mobileMq = window.matchMedia("(max-width: 640px)"); | |
| 238 | + /* ---------- plein écran + clavier mobile ---------- | |
| 239 | + Ouverture = PLEIN ÉCRAN direct (desktop et mobile). ▭ réduit en fenêtre | |
| 240 | + (desktop seulement — caché sur mobile). Tant que le plein écran est ouvert, | |
| 241 | + l'arrière-plan est GELÉ (body position:fixed, scroll restauré à la | |
| 242 | + fermeture) et le panneau se cale sur window.visualViewport : quand le | |
| 243 | + clavier s'ouvre, le panneau rétrécit à la place de laisser iOS | |
| 244 | + zoomer/pousser la page. Pas de focus clavier forcé au tap sur mobile. */ | |
| 150 | 245 | var fineInput = window.matchMedia("(hover: hover) and (pointer: fine)"); |
| 151 | − function syncLock() { | |
| 152 | − var open = panel.classList.contains("kaa-open"); | |
| 153 | − if (open && mobileMq.matches) panel.classList.add("kaa-full"); | |
| 154 | − document.documentElement.classList.toggle( | |
| 155 | − "kaa-lock", open && panel.classList.contains("kaa-full")); | |
| 246 | + var vv = window.visualViewport; | |
| 247 | + var savedY = 0; | |
| 248 | + | |
| 249 | + function isOpen() { return panel.classList.contains("kaa-open"); } | |
| 250 | + function isFull() { return panel.classList.contains("kaa-full"); } | |
| 251 | + | |
| 252 | + function fitVV() { | |
| 253 | + if (!vv || !isOpen() || !isFull()) { panel.style.height = ""; panel.style.top = ""; return; } | |
| 254 | + panel.style.top = Math.round(vv.offsetTop) + "px"; | |
| 255 | + panel.style.height = Math.round(vv.height) + "px"; | |
| 256 | + scroll(); | |
| 156 | 257 | } |
| 157 | − btn.addEventListener("click", function () { | |
| 158 | − panel.classList.toggle("kaa-open"); | |
| 159 | − if (panel.classList.contains("kaa-open")) { | |
| 160 | − render(); | |
| 161 | − if (fineInput.matches) ta.focus(); | |
| 258 | + if (vv) { | |
| 259 | + vv.addEventListener("resize", fitVV); | |
| 260 | + vv.addEventListener("scroll", fitVV); | |
| 261 | + } | |
| 262 | + | |
| 263 | + function lockBg(on) { | |
| 264 | + var b = document.body, h = document.documentElement; | |
| 265 | + if (on && !h.classList.contains("kaa-lock")) { | |
| 266 | + savedY = window.scrollY || 0; | |
| 267 | + h.classList.add("kaa-lock"); | |
| 268 | + b.style.position = "fixed"; | |
| 269 | + b.style.top = -savedY + "px"; | |
| 270 | + b.style.left = "0"; b.style.right = "0"; b.style.width = "100%"; | |
| 271 | + } else if (!on && h.classList.contains("kaa-lock")) { | |
| 272 | + h.classList.remove("kaa-lock"); | |
| 273 | + b.style.position = ""; b.style.top = ""; b.style.left = ""; b.style.right = ""; b.style.width = ""; | |
| 274 | + window.scrollTo(0, savedY); | |
| 162 | 275 | } |
| 163 | − syncLock(); | |
| 276 | + } | |
| 277 | + function sync() { | |
| 278 | + lockBg(isOpen() && isFull()); | |
| 279 | + fitVV(); | |
| 280 | + } | |
| 281 | + | |
| 282 | + btn.addEventListener("click", function () { | |
| 283 | + panel.classList.add("kaa-open", "kaa-full"); // plein écran d'office | |
| 284 | + render(); | |
| 285 | + if (fineInput.matches) ta.focus(); | |
| 286 | + sync(); | |
| 164 | 287 | }); |
| 165 | 288 | panel.querySelector(".kaa-x2").addEventListener("click", function () { |
| 166 | 289 | panel.classList.remove("kaa-open", "kaa-full"); |
| 167 | − syncLock(); | |
| 290 | + sync(); | |
| 168 | 291 | }); |
| 169 | 292 | panel.querySelector(".kaa-x1").addEventListener("click", function () { |
| 170 | 293 | panel.classList.toggle("kaa-full"); |
| 171 | − syncLock(); | |
| 294 | + sync(); | |
| 172 | 295 | scroll(); |
| 173 | 296 | }); |
| 297 | + document.addEventListener("keydown", function (e) { | |
| 298 | + if (e.key === "Escape" && isOpen()) { | |
| 299 | + panel.classList.remove("kaa-open", "kaa-full"); | |
| 300 | + sync(); | |
| 301 | + } | |
| 302 | + }); | |
| 174 | 303 | |
| 175 | 304 | /* ---------- envoi + flux SSE ---------- */ |
| 176 | 305 | var busy = false; |
@@ -182,7 +311,7 @@ | ||
| 182 | 311 | ta.value = ""; |
| 183 | 312 | log.push({ role: "user", content: q }); |
| 184 | 313 | save(); |
| 185 | − bubble("kaa-u", md(q)); | |
| 314 | + bubble("kaa-u", esc(q)); | |
| 186 | 315 | var out = bubble("kaa-a", '<span class="kaa-dots"></span>'); |
| 187 | 316 | var acc = ""; |
| 188 | 317 | var chips = []; |
@@ -211,7 +340,7 @@ | ||
| 211 | 340 | try { data = JSON.parse(dm); } catch (e) {} |
| 212 | 341 | if (ev === "delta" && data.text) { |
| 213 | 342 | acc += data.text; |
| 214 | − out.innerHTML = md(acc); | |
| 343 | + out.innerHTML = md(acc); // markdown re-rendu à chaque delta | |
| 215 | 344 | scroll(); |
| 216 | 345 | } else if (ev === "tool") { |
| 217 | 346 | chips.push(toolChip(data.name || "recherche")); |
modified
frontend/src/ka/stats/SPEC.md
+128 −66
@@ -1,53 +1,88 @@ | ||
| 1 | −# ka-stats — module Stats commun Groupe KA (spec v1) | |
| 1 | +# ka-stats — module Stats commun Groupe KA (spec v2) | |
| 2 | 2 | |
| 3 | −Contrat partagé par les 12 plateformes pour leurs pages **/stats** (tableau de | |
| 4 | −bord analytique) et l'**export PDF** estampillé Groupe-KA. Le visuel suit le | |
| 5 | −design system ka-ui (tokens.css) avec l'accent de la marque. | |
| 3 | +Contrat partagé par les plateformes pour leurs pages **/stats** (tableau de | |
| 4 | +bord analytique) et les **exports PDF** estampillés Groupe-KA. Le visuel suit | |
| 5 | +le design system ka-ui (tokens.css) avec l'accent de la marque. | |
| 6 | + | |
| 7 | +**v2 (2026-08-19)** : sparklines dans les KPI, jauges, multi-courbes, | |
| 8 | +barres empilées, distributions (histogrammes), heatmap horaire 7×24, deltas | |
| 9 | +sur les répartitions, statistiques de séries (min/max/moy/méd/σ), et **5 | |
| 10 | +rapports PDF** au lieu de 2. Tous les nouveaux champs sont **optionnels** : | |
| 11 | +un dashboard v1 reste valide et se rend tel quel. | |
| 6 | 12 | |
| 7 | 13 | ## 1. Page /stats — structure obligatoire (dans cet ordre) |
| 8 | 14 | |
| 9 | −1. **Bandeau KPI** : 4–6 grandes cartes (`KpiCard`) — valeur, libellé, | |
| 10 | − variation vs période précédente (▲/▼ + %, vert `--green` / rouge `--danger`). | |
| 15 | +1. **Bandeau KPI** : 6–10 grandes cartes (`KpiCard`) — valeur, libellé, | |
| 16 | + variation vs période précédente (▲/▼ + %, vert `--green` / rouge | |
| 17 | + `--danger`), **sparkline** de tendance quand une série existe. | |
| 11 | 18 | 2. **Sélecteur de période global** (`PeriodSelector`) : `aujourd'hui · 7 j · |
| 12 | 19 | 30 j · 3 m · 6 m · 12 m · année en cours · tout` + plage personnalisée |
| 13 | 20 | (2 champs date). Toute la page se recalcule (state → refetch dashboard). |
| 14 | −3. **Graphiques** : courbes d'évolution (`LineChart`, survol = infobulle, | |
| 15 | − légende cliquable pour masquer une série, comparaison N vs N-1 en | |
| 16 | − pointillé), barres (`BarChart`), anneaux (`Donut`), calendrier de chaleur | |
| 17 | − (`CalendarHeatmap`) quand pertinent. | |
| 18 | −4. **Répartition géographique** (par ville/région) quand pertinent — barres | |
| 19 | − horizontales triées (pas besoin de vraie carte). | |
| 20 | −5. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne, | |
| 21 | +3. **Jauges** (`GaugeCard`) quand pertinent : taux, couvertures, complétude. | |
| 22 | +4. **Graphiques d'évolution** : courbes/aires (`LineChart`, survol = | |
| 23 | + infobulle, légende cliquable, comparaison N vs N-1 en pointillé), barres | |
| 24 | + verticales (`VBarChart` — volumes quotidiens), **multi-courbes ≤ 4 séries** | |
| 25 | + (`MultiLineChart` — motifs de trait distincts, jamais la couleur seule), | |
| 26 | + **barres empilées** (`StackedBarChart` — composition dans le temps). | |
| 27 | + Sous les courbes clés : `StatSummary` (min/max/moyenne/médiane/écart-type). | |
| 28 | +5. **Répartitions** : barres horizontales (`BarChart`, deltas optionnels), | |
| 29 | + anneaux (`Donut`), **distributions/histogrammes** (`Histogram`). | |
| 30 | +6. **Répartition géographique** (par ville/région) — barres horizontales | |
| 31 | + triées (pas besoin de vraie carte). | |
| 32 | +7. **Calendriers** : `CalendarHeatmap` (26 semaines) et, quand l'activité | |
| 33 | + horaire est journalisée, `HourHeatmap` (7 jours × 24 h). | |
| 34 | +8. **Tableaux détaillés** (`DataTable`) : tri par colonne, recherche interne, | |
| 21 | 35 | pagination (25/pg), débordement horizontal propre sur mobile (.tbl-wrap). |
| 22 | −6. **Records & faits marquants** : générés depuis les données (jour record, | |
| 23 | − plus forte croissance, meilleure entrée…) — cartes compactes. | |
| 24 | −7. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir. | |
| 25 | −8. **Bouton PDF** bien visible en haut : « Télécharger le rapport PDF » avec | |
| 26 | − deux choix (Rapport complet / Synthèse 2 pages). Indicateur de progression | |
| 27 | − si > 2 s. | |
| 36 | + Viser 3 à 5 tableaux par plateforme. | |
| 37 | +9. **Records & faits marquants** : générés depuis les données (jour record, | |
| 38 | + plus forte croissance, meilleure entrée…) — cartes compactes, 6–12. | |
| 39 | +10. **Fraîcheur** : « Mis à jour le {date heure} » + bouton Rafraîchir. | |
| 40 | +11. **Bouton PDF** bien visible en haut (`PdfButton`) : bouton principal | |
| 41 | + « Rapport PDF complet » + menu « Autres rapports ▾ » listant les | |
| 42 | + **5 rapports** (voir §3). Indicateur de progression si > 2 s. | |
| 28 | 43 | |
| 29 | 44 | Responsive : KPI empilés < 768 px, graphiques pleine largeur redimensionnés |
| 30 | 45 | (SVG viewBox), tableaux en défilement horizontal contenu, tactile ≥ 44 px. |
| 31 | 46 | AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré » |
| 32 | 47 | (carte grise propre), jamais un faux chiffre. |
| 33 | 48 | |
| 49 | +Accessibilité (règles fermes) : un seul axe Y par graphique (jamais de | |
| 50 | +double échelle) ; ≥ 2 séries ⇒ légende obligatoire ; l'identité d'une série | |
| 51 | +multi-courbes passe par le **motif de trait** en plus de la couleur ; le | |
| 52 | +texte reste en encre (jamais coloré à la couleur de série) ; chaque | |
| 53 | +graphique a son infobulle de survol et un équivalent tableau existe. | |
| 54 | + | |
| 34 | 55 | ## 2. API — contrat commun |
| 35 | 56 | |
| 36 | 57 | `GET /api/stats/dashboard?period=7j|30j|3m|6m|12m|annee|tout|auj&from=YYYY-MM-DD&to=YYYY-MM-DD` |
| 37 | 58 | |
| 38 | 59 | ```jsonc |
| 39 | 60 | { |
| 40 | − "updated": "2026-08-17T21:04:00-04:00", | |
| 41 | − "period": { "from": "2026-07-18", "to": "2026-08-17", "label": "30 jours" }, | |
| 61 | + "updated": "2026-08-19T01:00:00-04:00", | |
| 62 | + "period": { "from": "2026-07-20", "to": "2026-08-19", "label": "30 jours" }, | |
| 42 | 63 | "kpis": [ { "id": "total", "label": "Annonces actives", "value": 33744, |
| 43 | − "unit": "", "delta_pct": 4.2, "direction": "up" } ], | |
| 64 | + "unit": "", "delta_pct": 4.2, "direction": "up", | |
| 65 | + "spark": [{ "t": "2026-08-01", "v": 31200 }] } ], // spark optionnel | |
| 66 | + "gauges": [ { "id": "geo", "label": "Fiches géolocalisées", "value": 92, | |
| 67 | + "max": 100, "unit": "%" } ], // optionnel | |
| 44 | 68 | "series": [ { "id": "vol", "title": "Annonces actives par jour", "unit": "annonces", |
| 45 | − "kind": "line", "points": [{ "t": "2026-07-18", "v": 31200 }], | |
| 46 | − "compare": [{ "t": "2025-07-18", "v": 24100 }] } ], | |
| 47 | − "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut", | |
| 48 | − "items": [{ "label": "4½", "value": 9120 }] } ], | |
| 69 | + "kind": "line", // line | bar | area | |
| 70 | + "points": [{ "t": "2026-07-20", "v": 31200 }], | |
| 71 | + "compare": [{ "t": "2025-07-20", "v": 24100 }] } ], | |
| 72 | + "multiseries": [ { "id": "seg", "title": "Prix médian par taille", "unit": "$", | |
| 73 | + "series": [ { "label": "3½", "points": [/* … */] }, | |
| 74 | + { "label": "4½", "points": [/* … */] } ] } ], // ≤ 4 | |
| 75 | + "stacked": [ { "id": "src", "title": "Ajouts par source", "unit": "ajouts", | |
| 76 | + "keys": ["Kijiji", "Centris", "Autres"], | |
| 77 | + "points": [{ "t": "2026-08-01", "values": [120, 80, 30] }] } ], | |
| 78 | + "breakdowns": [ { "id": "types", "title": "Par type", "kind": "donut", // donut | bars | |
| 79 | + "items": [{ "label": "4½", "value": 9120, "delta_pct": 2.1 }] } ], | |
| 80 | + "distributions": [ { "id": "prix", "title": "Distribution des loyers", "unit": "annonces", | |
| 81 | + "bins": [{ "label": "800-1000$", "value": 3120 }] } ], | |
| 49 | 82 | "geo": { "title": "Par région", "items": [{ "label": "Montréal", "value": 15680 }] }, |
| 50 | 83 | "heatmap": { "title": "Activité", "cells": [{ "date": "2026-08-01", "value": 210 }] }, |
| 84 | + "hourly": { "title": "Activité par heure", | |
| 85 | + "cells": [{ "dow": 0, "hour": 9, "value": 40 }] }, // dow 0=lun … 6=dim | |
| 51 | 86 | "tables": [ { "id": "top", "title": "Top villes", "columns": ["Ville", "Annonces", "Δ 30 j"], |
| 52 | 87 | "rows": [["Montréal", 15680, "+3,1 %"]] } ], |
| 53 | 88 | "records": [ { "label": "Jour record d'ajouts", "value": "412 annonces", "date": "2026-08-09" } ] |
@@ -56,23 +91,40 @@ AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré » | ||
| 56 | 91 | |
| 57 | 92 | Champs absents = section masquée. Cache serveur recommandé (≥ 5 min par |
| 58 | 93 | période). Les valeurs proviennent des données réelles (DB de la plateforme, |
| 59 | −journaux de sync des connecteurs, /api/v1/runs d'API-KA…). | |
| 94 | +journaux de sync des connecteurs, /api/v1/runs d'API-KA…). Arrondir les | |
| 95 | +`delta_pct` à 1 décimale côté serveur. | |
| 60 | 96 | |
| 61 | −`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese` | |
| 97 | +## 3. Rapports PDF — 5 modes | |
| 98 | + | |
| 99 | +`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese|tendances|repartitions|donnees` | |
| 62 | 100 | → `application/pdf`, en-tête `Content-Disposition: attachment; filename= |
| 63 | −groupe-ka_<plateforme>_stats_<periode>_<YYYY-MM-DD>.pdf`. | |
| 101 | +groupe-ka_<plateforme>_stats_<periode>[_<mode>]_<YYYY-MM-DD>.pdf` | |
| 102 | +(pas de suffixe pour `complet` — rétrocompatible v1 ; `kapdf.filename()` | |
| 103 | +accepte maintenant `mode` en 3e argument). | |
| 104 | + | |
| 105 | +| Mode | Contenu | | |
| 106 | +|---|---| | |
| 107 | +| `complet` | tout : sommaire, KPI, jauges, séries + stats de séries, multi-séries, empilées, répartitions, distributions, géo, heatmap horaire, tableaux (200 lignes), records | | |
| 108 | +| `synthese` | couverture + KPI + jauges + records (2–3 pages) | | |
| 109 | +| `tendances` | KPI + toutes les séries temporelles + min/max/moy/méd/σ + records | | |
| 110 | +| `repartitions` | breakdowns, distributions, géo, activité horaire | | |
| 111 | +| `donnees` | tous les tableaux en version longue (400 lignes) | | |
| 64 | 112 | |
| 65 | −## 3. PDF — gabarit Groupe-KA (implémentations : `kapdf.py` fpdf2 pour les | |
| 66 | −apps Python ; les apps Next portent le même gabarit en pdfkit) | |
| 113 | +Un `mode` inconnu retombe sur `complet`. Le gabarit (implémentations : | |
| 114 | +`kapdf.py` fpdf2 pour les apps Python ; les apps Next portent le même | |
| 115 | +gabarit en pdfkit) : | |
| 67 | 116 | |
| 68 | 117 | - **Couverture** : cadre encre, kicker « GROUPE KA · RAPPORT STATISTIQUE », |
| 69 | − wordmark de la plateforme (boîte encre + accent), sous-titre, période | |
| 70 | − couverte, date/heure de génération, bande encre au pied avec | |
| 118 | + wordmark de la plateforme (boîte encre + accent), **type de rapport**, | |
| 119 | + période couverte, date/heure de génération, bande encre au pied avec | |
| 71 | 120 | « par Groupe KA — groupe-ka.com ». |
| 72 | −- **Sommaire** avec numéros de pages (mode complet). | |
| 73 | −- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré). | |
| 121 | +- **Sommaire** avec numéros de pages (modes complet et donnees). | |
| 122 | +- **KPI** : grille de cartes (bordure encre, valeur en gros, delta coloré | |
| 123 | + arrondi à 1 décimale). **Jauges** : demi-arcs accent. | |
| 74 | 124 | - **Graphiques VECTORIELS** (dessinés en primitives, jamais de capture) : |
| 75 | − courbes, barres, anneaux — accent de la plateforme, axes/graduations encre. | |
| 125 | + courbes/aires, barres verticales, multi-courbes (motifs distincts), | |
| 126 | + empilées (nuances d'accent), anneaux, heatmap horaire — accent de la | |
| 127 | + plateforme, axes/graduations encre. | |
| 76 | 128 | - **Tableaux** paginés proprement (lignes zébrées `--surface-2`, jamais |
| 77 | 129 | coupés en deux à cheval sur une ligne). |
| 78 | 130 | - **Records** puis **page de fin** : coordonnées Groupe KA (3 courriels + |
@@ -81,43 +133,53 @@ apps Python ; les apps Next portent le même gabarit en pdfkit) | ||
| 81 | 133 | - **Chaque page** : en-tête discret (« Groupe KA · {Plateforme} », filet |
| 82 | 134 | encre) + pied (« © Groupe-KA — {année} — groupe-ka.com · {période} · p. X/Y »). |
| 83 | 135 | - A4 portrait, marges 18 mm, typo : Helvetica (fallback sûr) ou fonts TTF du |
| 84 | − DS si présentes. Mode « synthese » = couverture + 1 page KPI/records. | |
| 136 | + DS si présentes. | |
| 85 | 137 | |
| 86 | 138 | ## 4. Spécifique par plateforme (sections métier attendues) |
| 87 | 139 | |
| 88 | −- **groupe-ka** : tableau de bord maître — consolidation des 12 (volume total, | |
| 89 | − croissance), classement des plateformes, bloc résumé par plateforme + lien | |
| 140 | +- **groupe-ka** : tableau de bord maître — consolidation des plateformes | |
| 141 | + (volume total, croissance), classement, bloc résumé par plateforme + lien | |
| 90 | 142 | vers sa page /stats ; « Rapport écosystème complet » = PDF consolidé. |
| 91 | 143 | - **lou-ka** : annonces actives/nouvelles/retirées, loyers moyens/médians par |
| 92 | − ville & taille, évolution, répartition par type, top villes. | |
| 93 | −- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix moyen/médian | |
| 94 | − par ville/région/type, délai de présence, top villes, tension du marché. | |
| 144 | + ville & taille (multiseries), distribution des loyers, évolution, | |
| 145 | + répartition par type, top villes, sources (stacked). | |
| 146 | +- **immo-ka** : annonces actives/nouvelles/vendues-retirées, prix | |
| 147 | + moyen/médian par ville/région/type (multiseries), distribution des prix, | |
| 148 | + délai de présence, top villes, tension du marché. | |
| 95 | 149 | - **vrai-prix** : couverture du rôle (unités, valeur totale), estimations |
| 96 | − servies si journalisées, répartitions par municipalité/type, indices marché. | |
| 97 | −- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens et | |
| 98 | − km moyens par segment, top marques/modèles. | |
| 99 | −- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix, | |
| 100 | − nouveautés par période, top catégories. | |
| 101 | −- **food-ka** : produits suivis, relevés de prix, soldes détectés (baisses/ | |
| 102 | − hausses, amplitude), top produits en solde, prix moyens par catégorie. | |
| 103 | −- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, nouveautés/ | |
| 104 | − fermetures détectées, top établissements. | |
| 150 | + servies si journalisées, répartitions par municipalité/type, distribution | |
| 151 | + des valeurs, indices marché. | |
| 152 | +- **auto-ka** : volume par marque/modèle/année/carburant/boîte, prix moyens | |
| 153 | + et km moyens par segment (multiseries), distributions prix/km/année, | |
| 154 | + top marques/modèles. | |
| 155 | +- **fabri-ka** : produits par catégorie/région/boutique, fourchettes de prix | |
| 156 | + (distribution), nouveautés par période, top catégories. | |
| 157 | +- **food-ka** : produits suivis, relevés de prix, soldes détectés | |
| 158 | + (baisses/hausses, amplitude — stacked), top produits en solde, prix moyens | |
| 159 | + par catégorie, distribution des rabais. | |
| 160 | +- **resto-ka** : restos par cuisine/ville/gamme, menus & plats, distribution | |
| 161 | + des prix de plats, nouveautés/fermetures détectées, top établissements. | |
| 105 | 162 | - **sorti-ka** : événements à venir/passés par catégorie/ville, gratuits vs |
| 106 | − payants, heatmap calendrier, top lieux. | |
| 107 | −- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés, top | |
| 108 | − créateurs, croissance du répertoire. | |
| 109 | −- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h), | |
| 110 | − erreurs, file frontier, tendances si les requêtes sont journalisées. | |
| 111 | −- **api-ka** : appels par endpoint/jour/heure, latences moyennes + p95, taux | |
| 112 | − d'erreur, top endpoints, uptime (données des middlewares de logging + runs). | |
| 113 | −- **Transverse (tous)** : volume total agrégé + croissance, connecteurs actifs | |
| 114 | − et éléments ajoutés/mis à jour par période (journaux de sync), complétude/ | |
| 115 | − fraîcheur moyenne des fiches quand mesurable. Trafic web : seulement si des | |
| 116 | − journaux d'accès existent — sinon état vide propre. | |
| 163 | + payants (stacked), heatmap calendrier + horaire, top lieux. | |
| 164 | +- **crea-ka** : créateurs par plateforme/niche/tier, comptes reliés | |
| 165 | + (stacked par plateforme), distribution des audiences, top créateurs, | |
| 166 | + croissance du répertoire. | |
| 167 | +- **trouve-ka** : pages indexées, domaines, rythme de crawl (indexées/h — | |
| 168 | + hourly), erreurs, file frontier, tendances des requêtes journalisées. | |
| 169 | +- **api-ka** : appels par endpoint/jour/heure (hourly), latences moyennes + | |
| 170 | + p95 (multiseries), taux d'erreur, top endpoints/clés, uptime. | |
| 171 | +- **job-ka** : offres actives/nouvelles/expirées par catégorie/ville/ | |
| 172 | + entreprise, distribution des salaires affichés, top employeurs. | |
| 173 | +- **Transverse (tous)** : volume total agrégé + croissance, connecteurs | |
| 174 | + actifs et éléments ajoutés/mis à jour par période (journaux de sync — | |
| 175 | + stacked par source quand possible), complétude/fraîcheur moyenne des | |
| 176 | + fiches quand mesurable (jauges). Trafic web : seulement si des journaux | |
| 177 | + d'accès existent — sinon état vide propre. | |
| 117 | 178 | |
| 118 | 179 | ## 5. Ajouter une métrique / un graphique / une plateforme |
| 119 | 180 | |
| 120 | −1 métrique = 1 entrée `kpis[]` ou `series[]` côté API (requête SQL agrégée + | |
| 121 | −cache) — le front la rend automatiquement. 1 plateforme = implémenter les 2 | |
| 122 | −endpoints du contrat + une page /stats montée sur les composants du kit + | |
| 123 | −`kapdf.py` (ou gabarit pdfkit) branché sur le même JSON de dashboard. | |
| 181 | +1 métrique = 1 entrée `kpis[]`, `series[]`, `multiseries[]`, `stacked[]`, | |
| 182 | +`distributions[]` ou `gauges[]` côté API (requête SQL agrégée + cache) — le | |
| 183 | +front la rend automatiquement. 1 plateforme = implémenter les 2 endpoints du | |
| 184 | +contrat + une page /stats montée sur les composants du kit + `kapdf.py` (ou | |
| 185 | +gabarit pdfkit) branché sur le même JSON de dashboard. | |
modified
frontend/src/ka/stats/kacharts.tsx
+393 −30
@@ -2,22 +2,39 @@ | ||
| 2 | 2 | // ka-ui/stats/kacharts.tsx — kit de graphiques SVG du module Stats commun |
| 3 | 3 | // Groupe KA (zéro dépendance, React 18+). Style : design system ka-ui |
| 4 | 4 | // (bordures encre, accent de la plateforme via var(--accent)). |
| 5 | −// Composants : KpiCard, PeriodSelector, LineChart (infobulle + légende | |
| 6 | −// cliquable + comparaison N-1), BarChart, Donut, CalendarHeatmap, DataTable | |
| 7 | −// (tri/recherche/pagination), RecordCard, PdfButton, EmptyBlock, Fraicheur. | |
| 8 | −import { useMemo, useState } from "react"; | |
| 5 | +// v2 — composants : KpiCard (+sparkline), PeriodSelector, LineChart (ligne/ | |
| 6 | +// aire, infobulle + légende cliquable + comparaison N-1), MultiLineChart | |
| 7 | +// (≤4 séries, pointillés distincts = jamais la couleur seule), VBarChart | |
| 8 | +// (barres verticales / histogrammes), StackedBarChart, BarChart (horizontal, | |
| 9 | +// deltas), Donut, GaugeCard, CalendarHeatmap, HourHeatmap (7×24), | |
| 10 | +// StatSummary (min/max/moy/méd/σ), DataTable (tri/recherche/pagination), | |
| 11 | +// RecordCard, PdfButton (menu de rapports), EmptyBlock, Fraicheur. | |
| 12 | +import { useEffect, useMemo, useRef, useState } from "react"; | |
| 9 | 13 | |
| 10 | −/* ---------- types (contrat SPEC.md) ---------- */ | |
| 14 | +/* ---------- types (contrat SPEC.md v2) ---------- */ | |
| 11 | 15 | export type Kpi = { |
| 12 | 16 | id: string; label: string; value: number | string; unit?: string; |
| 13 | 17 | delta_pct?: number | null; direction?: "up" | "down"; |
| 18 | + spark?: Point[]; help?: string; | |
| 14 | 19 | }; |
| 15 | 20 | export type Point = { t: string; v: number }; |
| 16 | 21 | export type Serie = { |
| 17 | − id: string; title: string; unit?: string; kind?: "line" | "bar"; | |
| 22 | + id: string; title: string; unit?: string; | |
| 23 | + kind?: "line" | "bar" | "area"; | |
| 18 | 24 | points: Point[]; compare?: Point[]; |
| 19 | 25 | }; |
| 20 | −export type BreakItem = { label: string; value: number }; | |
| 26 | +export type MultiSerie = { | |
| 27 | + id: string; title: string; unit?: string; | |
| 28 | + series: { label: string; points: Point[] }[]; // ≤ 4 séries | |
| 29 | +}; | |
| 30 | +export type StackedSerie = { | |
| 31 | + id: string; title: string; unit?: string; | |
| 32 | + keys: string[]; points: { t: string; values: number[] }[]; | |
| 33 | +}; | |
| 34 | +export type BreakItem = { label: string; value: number; delta_pct?: number | null }; | |
| 35 | +export type Distribution = { id: string; title: string; unit?: string; bins: { label: string; value: number }[] }; | |
| 36 | +export type Gauge = { id: string; label: string; value: number; max: number; unit?: string; help?: string }; | |
| 37 | +export type HourCell = { dow: number; hour: number; value: number }; // dow 0=lun … 6=dim | |
| 21 | 38 | export type TableSpec = { id: string; title: string; columns: string[]; rows: (string | number)[][] }; |
| 22 | 39 | export type RecordFact = { label: string; value: string; date?: string }; |
| 23 | 40 | |
@@ -32,25 +49,63 @@ export const PERIODS: { id: string; label: string }[] = [ | ||
| 32 | 49 | { id: "tout", label: "Tout" }, |
| 33 | 50 | ]; |
| 34 | 51 | |
| 52 | +export const REPORT_MODES: { id: string; label: string; desc: string }[] = [ | |
| 53 | + { id: "complet", label: "Rapport complet", desc: "Toutes les sections — KPI, tendances, répartitions, tableaux, records" }, | |
| 54 | + { id: "synthese", label: "Synthèse exécutive", desc: "2 pages — indicateurs clés et faits marquants" }, | |
| 55 | + { id: "tendances", label: "Tendances & évolution", desc: "Courbes, comparaisons N-1 et statistiques de séries" }, | |
| 56 | + { id: "repartitions", label: "Répartitions & géographie", desc: "Catégories, distributions, régions et activité" }, | |
| 57 | + { id: "donnees", label: "Données détaillées", desc: "Tous les tableaux, en version longue" }, | |
| 58 | +]; | |
| 59 | + | |
| 35 | 60 | export const fmtInt = (n: number) => n.toLocaleString("fr-CA"); |
| 36 | 61 | export const fmtNum = (n: number) => |
| 37 | 62 | Number.isInteger(n) ? fmtInt(n) : n.toLocaleString("fr-CA", { maximumFractionDigits: 2 }); |
| 63 | +const fmtPct = (n: number) => `${n >= 0 ? "+" : ""}${fmtNum(n)} %`; | |
| 38 | 64 | |
| 39 | −/* ---------- KPI ---------- */ | |
| 65 | +/* Styles des séries multiples : couleur + motif de trait (l'identité n'est | |
| 66 | + jamais portée par la couleur seule — règle d'accessibilité). */ | |
| 67 | +const MULTI_STYLES = [ | |
| 68 | + { stroke: "var(--accent)", dash: undefined, width: 2.4 }, | |
| 69 | + { stroke: "var(--ink)", dash: undefined, width: 1.6 }, | |
| 70 | + { stroke: "var(--accent-deep, var(--accent))", dash: "6 3", width: 2 }, | |
| 71 | + { stroke: "var(--ink-3)", dash: "2 3", width: 2 }, | |
| 72 | +]; | |
| 73 | + | |
| 74 | +/* ---------- KPI (+ sparkline) ---------- */ | |
| 40 | 75 | export function KpiCard({ k }: { k: Kpi }) { |
| 41 | 76 | const up = (k.direction ?? ((k.delta_pct ?? 0) >= 0 ? "up" : "down")) === "up"; |
| 77 | + const sp = (k.spark ?? []).filter((p) => typeof p.v === "number"); | |
| 78 | + const spark = useMemo(() => { | |
| 79 | + if (sp.length < 2) return null; | |
| 80 | + const w = 120, h = 30; | |
| 81 | + const vmax = Math.max(...sp.map((p) => p.v)); | |
| 82 | + const vmin = Math.min(...sp.map((p) => p.v)); | |
| 83 | + const rng = vmax - vmin || 1; | |
| 84 | + const X = (i: number) => (w * i) / (sp.length - 1); | |
| 85 | + const Y = (v: number) => 2 + (h - 4) * (1 - (v - vmin) / rng); | |
| 86 | + const d = sp.map((p, i) => `${i ? "L" : "M"}${X(i).toFixed(1)},${Y(p.v).toFixed(1)}`).join(""); | |
| 87 | + return { w, h, d, area: `${d}L${w},${h}L0,${h}Z` }; | |
| 88 | + }, [k.spark]); | |
| 42 | 89 | return ( |
| 43 | − <article className="card" style={{ padding: "14px 16px", minWidth: 0 }}> | |
| 90 | + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={k.help}> | |
| 44 | 91 | <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px,2.4vw,30px)", letterSpacing: "-0.02em" }}> |
| 45 | 92 | {typeof k.value === "number" ? fmtNum(k.value) : k.value} |
| 46 | 93 | {k.unit ? <span style={{ fontSize: "0.6em", color: "var(--ink-2)" }}> {k.unit}</span> : null} |
| 47 | 94 | </p> |
| 48 | 95 | <p className="klabel" style={{ margin: "6px 0 0" }}>{k.label}</p> |
| 49 | − {k.delta_pct !== undefined && k.delta_pct !== null && ( | |
| 50 | − <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}> | |
| 51 | − {up ? "▲" : "▼"} {k.delta_pct >= 0 ? "+" : ""}{fmtNum(k.delta_pct)} % <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span> | |
| 52 | − </p> | |
| 53 | − )} | |
| 96 | + <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 8 }}> | |
| 97 | + {k.delta_pct !== undefined && k.delta_pct !== null ? ( | |
| 98 | + <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}> | |
| 99 | + {up ? "▲" : "▼"} {fmtPct(k.delta_pct)} <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span> | |
| 100 | + </p> | |
| 101 | + ) : <span />} | |
| 102 | + {spark && ( | |
| 103 | + <svg viewBox={`0 0 ${spark.w} ${spark.h}`} style={{ width: 96, height: 24, flex: "none" }} aria-hidden="true"> | |
| 104 | + <path d={spark.area} fill="var(--accent)" opacity={0.14} /> | |
| 105 | + <path d={spark.d} fill="none" stroke="var(--accent)" strokeWidth={1.8} /> | |
| 106 | + </svg> | |
| 107 | + )} | |
| 108 | + </div> | |
| 54 | 109 | </article> |
| 55 | 110 | ); |
| 56 | 111 | } |
@@ -84,12 +139,13 @@ export function PeriodSelector({ | ||
| 84 | 139 | ); |
| 85 | 140 | } |
| 86 | 141 | |
| 87 | −/* ---------- Courbe ---------- */ | |
| 142 | +/* ---------- Courbe / aire ---------- */ | |
| 88 | 143 | export function LineChart({ serie, height = 240 }: { serie: Serie; height?: number }) { |
| 89 | 144 | const [hide, setHide] = useState<{ cur: boolean; cmp: boolean }>({ cur: false, cmp: false }); |
| 90 | 145 | const [hover, setHover] = useState<number | null>(null); |
| 91 | 146 | const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26; |
| 92 | 147 | const pts = serie.points ?? []; |
| 148 | + if (serie.kind === "bar") return <VBarChart serie={serie} height={height} />; | |
| 93 | 149 | if (pts.length < 2) return <EmptyBlock title={serie.title} />; |
| 94 | 150 | const all = [...(hide.cur ? [] : pts), ...(!hide.cmp && serie.compare ? serie.compare : [])]; |
| 95 | 151 | const vmax = Math.max(...all.map((p) => p.v), 1); |
@@ -127,6 +183,9 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb | ||
| 127 | 183 | {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => ( |
| 128 | 184 | <text key={i} x={X(i, pts.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text> |
| 129 | 185 | ))} |
| 186 | + {serie.kind === "area" && !hide.cur && ( | |
| 187 | + <path d={`${path(pts)}L${X(pts.length - 1, pts.length)},${Y(0)}L${X(0, pts.length)},${Y(0)}Z`} fill="var(--accent)" opacity={0.13} /> | |
| 188 | + )} | |
| 130 | 189 | {!hide.cmp && serie.compare && serie.compare.length > 1 && ( |
| 131 | 190 | <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" /> |
| 132 | 191 | )} |
@@ -148,17 +207,211 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb | ||
| 148 | 207 | ); |
| 149 | 208 | } |
| 150 | 209 | |
| 151 | −function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off: boolean; dashed?: boolean; onClick: () => void }) { | |
| 210 | +function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off?: boolean; dashed?: boolean; onClick?: () => void }) { | |
| 152 | 211 | return ( |
| 153 | − <button type="button" onClick={onClick} aria-pressed={!off} | |
| 154 | − style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: "pointer", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}> | |
| 212 | + <button type="button" onClick={onClick} aria-pressed={!off} disabled={!onClick} | |
| 213 | + style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: onClick ? "pointer" : "default", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}> | |
| 155 | 214 | <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} /> |
| 156 | 215 | {label} |
| 157 | 216 | </button> |
| 158 | 217 | ); |
| 159 | 218 | } |
| 160 | 219 | |
| 161 | −/* ---------- Barres horizontales (répartitions, géo) ---------- */ | |
| 220 | +/* ---------- Multi-courbes (≤ 4 séries, motifs distincts) ---------- */ | |
| 221 | +export function MultiLineChart({ ms, height = 260 }: { ms: MultiSerie; height?: number }) { | |
| 222 | + const series = (ms.series ?? []).filter((s) => (s.points ?? []).length > 1).slice(0, 4); | |
| 223 | + const [off, setOff] = useState<Record<string, boolean>>({}); | |
| 224 | + const [hover, setHover] = useState<number | null>(null); | |
| 225 | + if (!series.length) return <EmptyBlock title={ms.title} />; | |
| 226 | + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26; | |
| 227 | + const n = Math.max(...series.map((s) => s.points.length)); | |
| 228 | + const shown = series.filter((s) => !off[s.label]); | |
| 229 | + const all = shown.flatMap((s) => s.points.map((p) => p.v)); | |
| 230 | + const vmax = Math.max(...(all.length ? all : [1]), 1); | |
| 231 | + const vmin = Math.min(0, ...(all.length ? all : [0])); | |
| 232 | + const X = (i: number, len: number) => PL + ((W - PL - PR) * i) / (len - 1); | |
| 233 | + const Y = (v: number) => PT + (H - PT - PB) * (1 - (v - vmin) / (vmax - vmin || 1)); | |
| 234 | + const ref = series[0].points; | |
| 235 | + const hi = hover !== null ? Math.min(n - 1, Math.max(0, hover)) : null; | |
| 236 | + return ( | |
| 237 | + <figure className="card" style={{ margin: 0, padding: 16 }}> | |
| 238 | + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}> | |
| 239 | + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{ms.title}</b> | |
| 240 | + <span style={{ display: "flex", gap: 10, flexWrap: "wrap" }}> | |
| 241 | + {series.map((s, i) => ( | |
| 242 | + <LegendChip key={s.label} label={s.label} color={MULTI_STYLES[i].stroke} | |
| 243 | + dashed={!!MULTI_STYLES[i].dash} off={!!off[s.label]} | |
| 244 | + onClick={() => setOff((o) => ({ ...o, [s.label]: !o[s.label] }))} /> | |
| 245 | + ))} | |
| 246 | + </span> | |
| 247 | + </figcaption> | |
| 248 | + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10, touchAction: "pan-y" }} role="img" aria-label={ms.title} | |
| 249 | + onMouseMove={(e) => { | |
| 250 | + const r = (e.currentTarget as SVGSVGElement).getBoundingClientRect(); | |
| 251 | + const fx = ((e.clientX - r.left) / r.width) * W; | |
| 252 | + setHover(Math.round(((fx - PL) / (W - PL - PR)) * (n - 1))); | |
| 253 | + }} | |
| 254 | + onMouseLeave={() => setHover(null)}> | |
| 255 | + {[0, 1, 2, 3, 4].map((g) => { | |
| 256 | + const y = PT + ((H - PT - PB) * g) / 4; | |
| 257 | + const v = vmax - ((vmax - vmin) * g) / 4; | |
| 258 | + return ( | |
| 259 | + <g key={g}> | |
| 260 | + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} /> | |
| 261 | + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text> | |
| 262 | + </g> | |
| 263 | + ); | |
| 264 | + })} | |
| 265 | + {[0, Math.floor(ref.length / 2), ref.length - 1].map((i) => ( | |
| 266 | + <text key={i} x={X(i, ref.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{ref[i]?.t}</text> | |
| 267 | + ))} | |
| 268 | + {series.map((s, i) => off[s.label] ? null : ( | |
| 269 | + <path key={s.label} | |
| 270 | + d={s.points.map((p, j) => `${j ? "L" : "M"}${X(j, s.points.length)},${Y(p.v)}`).join("")} | |
| 271 | + fill="none" stroke={MULTI_STYLES[i].stroke} strokeWidth={MULTI_STYLES[i].width} | |
| 272 | + strokeDasharray={MULTI_STYLES[i].dash} /> | |
| 273 | + ))} | |
| 274 | + {hi !== null && ( | |
| 275 | + <line x1={X(hi, n)} x2={X(hi, n)} y1={PT} y2={H - PB} stroke="var(--ink)" strokeWidth={1} strokeDasharray="2 3" /> | |
| 276 | + )} | |
| 277 | + </svg> | |
| 278 | + {hi !== null && ( | |
| 279 | + <p className="chip" style={{ marginTop: 8, display: "inline-flex", gap: 12, flexWrap: "wrap" }}> | |
| 280 | + <b>{ref[hi]?.t}</b> | |
| 281 | + {shown.map((s) => ( | |
| 282 | + <span key={s.label}>{s.label} : <b>{s.points[hi] ? fmtNum(s.points[hi].v) : "—"}{ms.unit ? ` ${ms.unit}` : ""}</b></span> | |
| 283 | + ))} | |
| 284 | + </p> | |
| 285 | + )} | |
| 286 | + </figure> | |
| 287 | + ); | |
| 288 | +} | |
| 289 | + | |
| 290 | +/* ---------- Barres verticales (volumes quotidiens, histogrammes) ---------- */ | |
| 291 | +export function VBarChart({ serie, height = 240 }: { serie: Serie; height?: number }) { | |
| 292 | + const [hover, setHover] = useState<number | null>(null); | |
| 293 | + const pts = serie.points ?? []; | |
| 294 | + if (!pts.length) return <EmptyBlock title={serie.title} />; | |
| 295 | + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26; | |
| 296 | + const vmax = Math.max(...pts.map((p) => p.v), 1); | |
| 297 | + const bw = Math.max(2, (W - PL - PR) / pts.length - 2); | |
| 298 | + return ( | |
| 299 | + <figure className="card" style={{ margin: 0, padding: 16 }}> | |
| 300 | + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{serie.title}</b></figcaption> | |
| 301 | + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10 }} role="img" aria-label={serie.title} | |
| 302 | + onMouseLeave={() => setHover(null)}> | |
| 303 | + {[0, 1, 2, 3, 4].map((g) => { | |
| 304 | + const y = PT + ((H - PT - PB) * g) / 4; | |
| 305 | + const v = vmax - (vmax * g) / 4; | |
| 306 | + return ( | |
| 307 | + <g key={g}> | |
| 308 | + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} /> | |
| 309 | + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text> | |
| 310 | + </g> | |
| 311 | + ); | |
| 312 | + })} | |
| 313 | + {pts.map((p, i) => { | |
| 314 | + const x = PL + ((W - PL - PR) * i) / pts.length; | |
| 315 | + const h = (H - PT - PB) * (p.v / vmax); | |
| 316 | + return ( | |
| 317 | + <rect key={i} x={x + 1} y={H - PB - h} width={bw} height={Math.max(h, p.v > 0 ? 1.5 : 0)} rx={2} | |
| 318 | + fill="var(--accent)" opacity={hover === null || hover === i ? 1 : 0.45} | |
| 319 | + stroke="var(--ink)" strokeWidth={0.5} | |
| 320 | + onMouseEnter={() => setHover(i)}> | |
| 321 | + <title>{`${p.t} — ${fmtNum(p.v)}${serie.unit ? ` ${serie.unit}` : ""}`}</title> | |
| 322 | + </rect> | |
| 323 | + ); | |
| 324 | + })} | |
| 325 | + {[0, Math.floor(pts.length / 2), pts.length - 1].filter((v, i, a) => a.indexOf(v) === i).map((i) => ( | |
| 326 | + <text key={i} x={PL + ((W - PL - PR) * (i + 0.5)) / pts.length} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text> | |
| 327 | + ))} | |
| 328 | + </svg> | |
| 329 | + {hover !== null && ( | |
| 330 | + <p className="chip" style={{ marginTop: 8 }}>{pts[hover].t} — <b>{fmtNum(pts[hover].v)}{serie.unit ? ` ${serie.unit}` : ""}</b></p> | |
| 331 | + )} | |
| 332 | + </figure> | |
| 333 | + ); | |
| 334 | +} | |
| 335 | + | |
| 336 | +/* ---------- Histogramme (distribution) ---------- */ | |
| 337 | +export function Histogram({ dist }: { dist: Distribution }) { | |
| 338 | + const serie: Serie = { | |
| 339 | + id: dist.id, title: dist.title, unit: dist.unit, kind: "bar", | |
| 340 | + points: (dist.bins ?? []).map((b) => ({ t: b.label, v: b.value })), | |
| 341 | + }; | |
| 342 | + return <VBarChart serie={serie} height={220} />; | |
| 343 | +} | |
| 344 | + | |
| 345 | +/* ---------- Barres empilées (composition dans le temps) ---------- */ | |
| 346 | +export function StackedBarChart({ st, height = 260 }: { st: StackedSerie; height?: number }) { | |
| 347 | + const [hover, setHover] = useState<number | null>(null); | |
| 348 | + const keys = (st.keys ?? []).slice(0, 6); | |
| 349 | + const pts = st.points ?? []; | |
| 350 | + if (!keys.length || !pts.length) return <EmptyBlock title={st.title} />; | |
| 351 | + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26; | |
| 352 | + const totals = pts.map((p) => p.values.slice(0, keys.length).reduce((s, v) => s + (v || 0), 0)); | |
| 353 | + const vmax = Math.max(...totals, 1); | |
| 354 | + const bw = Math.max(2, (W - PL - PR) / pts.length - 2); | |
| 355 | + const shades = [1, 0.72, 0.5, 0.34, 0.22, 0.13]; | |
| 356 | + return ( | |
| 357 | + <figure className="card" style={{ margin: 0, padding: 16 }}> | |
| 358 | + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}> | |
| 359 | + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{st.title}</b> | |
| 360 | + <span style={{ display: "flex", gap: 10, flexWrap: "wrap" }}> | |
| 361 | + {keys.map((k, i) => ( | |
| 362 | + <span key={k} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em" }}> | |
| 363 | + <span style={{ width: 11, height: 11, borderRadius: 3, border: "1px solid var(--ink)", background: "var(--accent)", opacity: shades[i] }} /> | |
| 364 | + {k} | |
| 365 | + </span> | |
| 366 | + ))} | |
| 367 | + </span> | |
| 368 | + </figcaption> | |
| 369 | + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10 }} role="img" aria-label={st.title} | |
| 370 | + onMouseLeave={() => setHover(null)}> | |
| 371 | + {[0, 1, 2, 3, 4].map((g) => { | |
| 372 | + const y = PT + ((H - PT - PB) * g) / 4; | |
| 373 | + return ( | |
| 374 | + <g key={g}> | |
| 375 | + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} /> | |
| 376 | + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(vmax - (vmax * g) / 4))}</text> | |
| 377 | + </g> | |
| 378 | + ); | |
| 379 | + })} | |
| 380 | + {pts.map((p, i) => { | |
| 381 | + const x = PL + ((W - PL - PR) * i) / pts.length; | |
| 382 | + let yAcc = H - PB; | |
| 383 | + return ( | |
| 384 | + <g key={i} onMouseEnter={() => setHover(i)} opacity={hover === null || hover === i ? 1 : 0.5}> | |
| 385 | + {keys.map((k, j) => { | |
| 386 | + const v = p.values[j] || 0; | |
| 387 | + const h = (H - PT - PB) * (v / vmax); | |
| 388 | + yAcc -= h; | |
| 389 | + return v > 0 ? ( | |
| 390 | + <rect key={k} x={x + 1} y={yAcc} width={bw} height={Math.max(h - 1, 0.8)} rx={1.5} | |
| 391 | + fill="var(--accent)" opacity={shades[j]} stroke="var(--ink)" strokeWidth={0.4}> | |
| 392 | + <title>{`${p.t} · ${k} — ${fmtNum(v)}${st.unit ? ` ${st.unit}` : ""}`}</title> | |
| 393 | + </rect> | |
| 394 | + ) : null; | |
| 395 | + })} | |
| 396 | + </g> | |
| 397 | + ); | |
| 398 | + })} | |
| 399 | + {[0, Math.floor(pts.length / 2), pts.length - 1].filter((v, i, a) => a.indexOf(v) === i).map((i) => ( | |
| 400 | + <text key={i} x={PL + ((W - PL - PR) * (i + 0.5)) / pts.length} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text> | |
| 401 | + ))} | |
| 402 | + </svg> | |
| 403 | + {hover !== null && ( | |
| 404 | + <p className="chip" style={{ marginTop: 8, display: "inline-flex", gap: 12, flexWrap: "wrap" }}> | |
| 405 | + <b>{pts[hover].t}</b> | |
| 406 | + {keys.map((k, j) => <span key={k}>{k} : <b>{fmtNum(pts[hover].values[j] || 0)}</b></span>)} | |
| 407 | + <span style={{ color: "var(--ink-3)" }}>total {fmtNum(totals[hover])}</span> | |
| 408 | + </p> | |
| 409 | + )} | |
| 410 | + </figure> | |
| 411 | + ); | |
| 412 | +} | |
| 413 | + | |
| 414 | +/* ---------- Barres horizontales (répartitions, géo) — deltas optionnels ---------- */ | |
| 162 | 415 | export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) { |
| 163 | 416 | const rows = (items ?? []).slice(0, 14); |
| 164 | 417 | if (!rows.length) return <EmptyBlock title={title} />; |
@@ -169,9 +422,16 @@ export function BarChart({ title, items, unit }: { title: string; items: BreakIt | ||
| 169 | 422 | <div style={{ marginTop: 12, display: "grid", gap: 9 }}> |
| 170 | 423 | {rows.map((r) => ( |
| 171 | 424 | <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}> |
| 172 | − <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}> | |
| 425 | + <div style={{ display: "flex", justifyContent: "space-between", gap: 8, fontSize: 12.5 }}> | |
| 173 | 426 | <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span> |
| 174 | − <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b> | |
| 427 | + <span style={{ display: "inline-flex", gap: 8, alignItems: "baseline", flex: "none" }}> | |
| 428 | + {r.delta_pct !== undefined && r.delta_pct !== null && ( | |
| 429 | + <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 700, color: r.delta_pct >= 0 ? "var(--green)" : "var(--danger)" }}> | |
| 430 | + {r.delta_pct >= 0 ? "▲" : "▼"} {fmtPct(r.delta_pct)} | |
| 431 | + </span> | |
| 432 | + )} | |
| 433 | + <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b> | |
| 434 | + </span> | |
| 175 | 435 | </div> |
| 176 | 436 | <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}> |
| 177 | 437 | <div style={{ height: "100%", width: `${Math.max((r.value / max) * 100, 1)}%`, background: "var(--accent)", border: "1px solid var(--ink)", borderRadius: "0 3px 3px 0", boxSizing: "border-box" }} /> |
@@ -224,6 +484,26 @@ export function Donut({ title, items }: { title: string; items: BreakItem[] }) { | ||
| 224 | 484 | ); |
| 225 | 485 | } |
| 226 | 486 | |
| 487 | +/* ---------- Jauge (taux, complétude, couverture) ---------- */ | |
| 488 | +export function GaugeCard({ g }: { g: Gauge }) { | |
| 489 | + const frac = Math.max(0, Math.min(1, g.max ? g.value / g.max : 0)); | |
| 490 | + const R = 60, C = Math.PI * R; | |
| 491 | + return ( | |
| 492 | + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={g.help}> | |
| 493 | + <svg viewBox="0 0 150 84" style={{ width: "100%", maxWidth: 190, display: "block", margin: "0 auto" }} role="img" aria-label={`${g.label} : ${fmtNum(g.value)}${g.unit ?? ""} sur ${fmtNum(g.max)}`}> | |
| 494 | + <path d={`M15,75 A${R},${R} 0 0 1 135,75`} fill="none" stroke="rgba(20,24,20,0.08)" strokeWidth={13} strokeLinecap="round" /> | |
| 495 | + <path d={`M15,75 A${R},${R} 0 0 1 135,75`} fill="none" stroke="var(--accent)" strokeWidth={13} strokeLinecap="round" | |
| 496 | + strokeDasharray={`${frac * C} ${C}`} /> | |
| 497 | + <text x={75} y={66} textAnchor="middle" fontFamily="var(--font-display)" fontWeight={700} fontSize={22} fill="var(--ink)"> | |
| 498 | + {fmtNum(g.value)}{g.unit ? <tspan fontSize={12} fill="var(--ink-2)"> {g.unit}</tspan> : null} | |
| 499 | + </text> | |
| 500 | + <text x={75} y={80} textAnchor="middle" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{(frac * 100).toFixed(0)} % de {fmtNum(g.max)}{g.unit ? ` ${g.unit}` : ""}</text> | |
| 501 | + </svg> | |
| 502 | + <p className="klabel" style={{ margin: "8px 0 0", textAlign: "center" }}>{g.label}</p> | |
| 503 | + </article> | |
| 504 | + ); | |
| 505 | +} | |
| 506 | + | |
| 227 | 507 | /* ---------- Calendrier de chaleur ---------- */ |
| 228 | 508 | export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) { |
| 229 | 509 | if (!cells?.length) return <EmptyBlock title={title} />; |
@@ -261,6 +541,64 @@ export function CalendarHeatmap({ title, cells }: { title: string; cells: { date | ||
| 261 | 541 | ); |
| 262 | 542 | } |
| 263 | 543 | |
| 544 | +/* ---------- Heatmap horaire 7 × 24 (activité par heure) ---------- */ | |
| 545 | +const DOW = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"]; | |
| 546 | +export function HourHeatmap({ title, cells }: { title: string; cells: HourCell[] }) { | |
| 547 | + if (!cells?.length) return <EmptyBlock title={title} />; | |
| 548 | + const grid = new Map(cells.map((c) => [`${c.dow}-${c.hour}`, c.value])); | |
| 549 | + const max = Math.max(...cells.map((c) => c.value), 1); | |
| 550 | + const CW = 24, CH = 20, LX = 34, LY = 16; | |
| 551 | + return ( | |
| 552 | + <figure className="card" style={{ margin: 0, padding: 16 }}> | |
| 553 | + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b> <span className="klabel">jour × heure</span></figcaption> | |
| 554 | + <div className="tbl-wrap" style={{ marginTop: 12 }}> | |
| 555 | + <svg viewBox={`0 0 ${LX + 24 * CW} ${LY + 7 * CH}`} style={{ minWidth: 520, width: "100%", height: "auto" }} role="img" aria-label={title}> | |
| 556 | + {[0, 6, 12, 18, 23].map((h) => ( | |
| 557 | + <text key={h} x={LX + h * CW + CW / 2} y={11} textAnchor="middle" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{h} h</text> | |
| 558 | + ))} | |
| 559 | + {DOW.map((d, i) => ( | |
| 560 | + <text key={d} x={LX - 6} y={LY + i * CH + CH / 2 + 3} textAnchor="end" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{d}</text> | |
| 561 | + ))} | |
| 562 | + {Array.from({ length: 7 }, (_, d) => Array.from({ length: 24 }, (_, h) => { | |
| 563 | + const v = grid.get(`${d}-${h}`) ?? 0; | |
| 564 | + return ( | |
| 565 | + <rect key={`${d}-${h}`} x={LX + h * CW} y={LY + d * CH} width={CW - 2} height={CH - 2} rx={2.5} | |
| 566 | + fill={v ? "var(--accent)" : "rgba(20,24,20,0.07)"} fillOpacity={v ? 0.22 + 0.78 * (v / max) : 1} | |
| 567 | + stroke="rgba(20,24,20,0.15)" strokeWidth={0.5}> | |
| 568 | + <title>{`${DOW[d]} ${h} h — ${fmtNum(v)}`}</title> | |
| 569 | + </rect> | |
| 570 | + ); | |
| 571 | + }))} | |
| 572 | + </svg> | |
| 573 | + </div> | |
| 574 | + </figure> | |
| 575 | + ); | |
| 576 | +} | |
| 577 | + | |
| 578 | +/* ---------- Statistiques de série (min/max/moy/méd/σ) ---------- */ | |
| 579 | +export function StatSummary({ serie }: { serie: Serie }) { | |
| 580 | + const vs = (serie.points ?? []).map((p) => p.v).filter((v) => typeof v === "number"); | |
| 581 | + if (vs.length < 2) return null; | |
| 582 | + const sorted = [...vs].sort((a, b) => a - b); | |
| 583 | + const mean = vs.reduce((s, v) => s + v, 0) / vs.length; | |
| 584 | + const med = sorted[Math.floor(sorted.length / 2)]; | |
| 585 | + const sd = Math.sqrt(vs.reduce((s, v) => s + (v - mean) ** 2, 0) / vs.length); | |
| 586 | + const items: [string, number][] = [ | |
| 587 | + ["Min", sorted[0]], ["Max", sorted[sorted.length - 1]], | |
| 588 | + ["Moyenne", Math.round(mean * 100) / 100], ["Médiane", med], | |
| 589 | + ["Écart-type", Math.round(sd * 100) / 100], | |
| 590 | + ]; | |
| 591 | + return ( | |
| 592 | + <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 }}> | |
| 593 | + {items.map(([l, v]) => ( | |
| 594 | + <span key={l} className="chip" style={{ fontSize: 11 }}> | |
| 595 | + <span style={{ color: "var(--ink-3)" }}>{l}</span> <b style={{ fontFamily: "var(--font-mono)" }}>{fmtNum(v)}</b> | |
| 596 | + </span> | |
| 597 | + ))} | |
| 598 | + </div> | |
| 599 | + ); | |
| 600 | +} | |
| 601 | + | |
| 264 | 602 | /* ---------- Tableau : tri, recherche, pagination ---------- */ |
| 265 | 603 | export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) { |
| 266 | 604 | const [q, setQ] = useState(""); |
@@ -338,9 +676,19 @@ export function RecordCard({ r }: { r: RecordFact }) { | ||
| 338 | 676 | ); |
| 339 | 677 | } |
| 340 | 678 | |
| 341 | −/* ---------- Bouton PDF ---------- */ | |
| 679 | +/* ---------- Menu de rapports PDF (5 rapports) ---------- */ | |
| 342 | 680 | export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) { |
| 343 | − const [busy, setBusy] = useState(false); | |
| 681 | + const [open, setOpen] = useState(false); | |
| 682 | + const [busy, setBusy] = useState<string | null>(null); | |
| 683 | + const box = useRef<HTMLSpanElement>(null); | |
| 684 | + useEffect(() => { | |
| 685 | + if (!open) return; | |
| 686 | + const close = (e: MouseEvent) => { | |
| 687 | + if (box.current && !box.current.contains(e.target as Node)) setOpen(false); | |
| 688 | + }; | |
| 689 | + document.addEventListener("mousedown", close); | |
| 690 | + return () => document.removeEventListener("mousedown", close); | |
| 691 | + }, [open]); | |
| 344 | 692 | const url = (mode: string) => { |
| 345 | 693 | const p = new URLSearchParams({ period, mode }); |
| 346 | 694 | if (from) p.set("from", from); |
@@ -348,23 +696,38 @@ export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: | ||
| 348 | 696 | return `${endpoint}?${p}`; |
| 349 | 697 | }; |
| 350 | 698 | const dl = (mode: string) => { |
| 351 | − setBusy(true); | |
| 699 | + setBusy(mode); | |
| 700 | + setOpen(false); | |
| 352 | 701 | const a = document.createElement("a"); |
| 353 | 702 | a.href = url(mode); |
| 354 | 703 | a.download = ""; |
| 355 | 704 | document.body.appendChild(a); |
| 356 | 705 | a.click(); |
| 357 | 706 | a.remove(); |
| 358 | − setTimeout(() => setBusy(false), 2500); | |
| 707 | + setTimeout(() => setBusy(null), 3000); | |
| 359 | 708 | }; |
| 360 | 709 | return ( |
| 361 | − <span style={{ display: "inline-flex", gap: 8, flexWrap: "wrap" }}> | |
| 362 | − <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={busy}> | |
| 363 | − {busy ? "Génération…" : "⬇ Télécharger le rapport PDF"} | |
| 710 | + <span ref={box} style={{ position: "relative", display: "inline-flex", gap: 8, flexWrap: "wrap" }}> | |
| 711 | + <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={!!busy}> | |
| 712 | + {busy ? "Génération…" : "⬇ Rapport PDF complet"} | |
| 364 | 713 | </button> |
| 365 | − <button type="button" className="btn btn-ghost" onClick={() => dl("synthese")} disabled={busy}> | |
| 366 | − Synthèse (2 p.) | |
| 714 | + <button type="button" className="btn btn-ghost" onClick={() => setOpen((o) => !o)} disabled={!!busy} | |
| 715 | + aria-haspopup="menu" aria-expanded={open}> | |
| 716 | + Autres rapports ▾ | |
| 367 | 717 | </button> |
| 718 | + {open && ( | |
| 719 | + <div role="menu" className="card" style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, zIndex: 50, minWidth: 300, padding: 6, background: "var(--surface)", boxShadow: "0 10px 28px rgba(20,24,20,0.18)" }}> | |
| 720 | + {REPORT_MODES.map((m) => ( | |
| 721 | + <button key={m.id} type="button" role="menuitem" onClick={() => dl(m.id)} | |
| 722 | + style={{ display: "block", width: "100%", textAlign: "left", border: 0, background: "none", cursor: "pointer", padding: "9px 10px", borderRadius: 6 }} | |
| 723 | + onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-2)")} | |
| 724 | + onMouseLeave={(e) => (e.currentTarget.style.background = "none")}> | |
| 725 | + <b style={{ display: "block", fontSize: 13, fontFamily: "var(--font-display)" }}>{m.label}</b> | |
| 726 | + <span className="klabel" style={{ fontSize: 11 }}>{m.desc}</span> | |
| 727 | + </button> | |
| 728 | + ))} | |
| 729 | + </div> | |
| 730 | + )} | |
| 368 | 731 | </span> |
| 369 | 732 | ); |
| 370 | 733 | } |
modified
frontend/src/ka/stats/kapdf.py
+389 −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,7 +67,8 @@ def _fr(n) -> str: | ||
| 52 | 67 | _SUBST = { |
| 53 | 68 | "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-", |
| 54 | 69 | "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"', |
| 55 | − "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", | |
| 70 | + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", | |
| 71 | + "×": "x", "·": ".", "σ": "sigma", "Δ": "delta", | |
| 56 | 72 | } |
| 57 | 73 | |
| 58 | 74 | |
@@ -79,7 +95,7 @@ class _PDF(FPDF): | ||
| 79 | 95 | self.set_auto_page_break(True, margin=22) |
| 80 | 96 | |
| 81 | 97 | def header(self): |
| 82 | − if self.cover_mode or self.page_no() == 1: # jamais sur la couverture | |
| 98 | + if self.cover_mode or self.page_no() == 1: | |
| 83 | 99 | return |
| 84 | 100 | self.set_font("helvetica", "B", 8.5) |
| 85 | 101 | self.set_text_color(*INK) |
@@ -95,8 +111,8 @@ class _PDF(FPDF): | ||
| 95 | 111 | self.set_y(20) |
| 96 | 112 | |
| 97 | 113 | def footer(self): |
| 98 | − # le pied de la couverture se rend APRÈS la remise à zéro de cover_mode | |
| 99 | − # (add_page suivant) : on exclut donc aussi explicitement la page 1 | |
| 114 | + # page 1 = couverture (le flag cover_mode est déjà retombé quand | |
| 115 | + # add_page() clôt la page 1 → tester aussi le numéro de page) | |
| 100 | 116 | if self.cover_mode or self.page_no() == 1: |
| 101 | 117 | return |
| 102 | 118 | self.set_y(-15) |
@@ -114,7 +130,7 @@ class GroupeKAReport: | ||
| 114 | 130 | def __init__(self, site: dict, dashboard: dict, mode: str = "complet"): |
| 115 | 131 | self.site = site |
| 116 | 132 | self.d = dashboard |
| 117 | − self.mode = mode | |
| 133 | + self.mode = mode if mode in REPORT_MODES else "complet" | |
| 118 | 134 | self.accent = _hex(site.get("accent", "#d9f26b")) |
| 119 | 135 | period = dashboard.get("period", {}) or {} |
| 120 | 136 | self.period_label = period.get("label") or "toute la période" |
@@ -129,6 +145,11 @@ class GroupeKAReport: | ||
| 129 | 145 | p.set_fill_color(*fill) |
| 130 | 146 | p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2) |
| 131 | 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 | + | |
| 132 | 153 | def _kicker(self, text): |
| 133 | 154 | p = self.pdf |
| 134 | 155 | p.set_font("helvetica", "B", 8) |
@@ -152,6 +173,14 @@ class GroupeKAReport: | ||
| 152 | 173 | self.toc.append((title, self.pdf.page_no())) |
| 153 | 174 | self.pdf.ln(11) |
| 154 | 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 | + | |
| 155 | 184 | # ---------- pages ---------- |
| 156 | 185 | def _cover(self): |
| 157 | 186 | p = self.pdf |
@@ -163,12 +192,10 @@ class GroupeKAReport: | ||
| 163 | 192 | p.set_draw_color(*INK) |
| 164 | 193 | p.set_line_width(1.0) |
| 165 | 194 | p.rect(10, 10, 190, 277) |
| 166 | − # kicker | |
| 167 | 195 | p.set_font("helvetica", "B", 10) |
| 168 | 196 | p.set_text_color(*GREEN) |
| 169 | 197 | p.set_xy(24, 34) |
| 170 | 198 | p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE") |
| 171 | − # wordmark : partie gauche + boîte encre/accent | |
| 172 | 199 | wm = self.site.get("wordmark", "") |
| 173 | 200 | left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None) |
| 174 | 201 | p.set_xy(24, 70) |
@@ -186,7 +213,7 @@ class GroupeKAReport: | ||
| 186 | 213 | p.set_xy(24, 100) |
| 187 | 214 | p.set_font("helvetica", "", 13) |
| 188 | 215 | p.set_text_color(*INK2) |
| 189 | − p.multi_cell(150, 7, f"Rapport statistique — {wm}") | |
| 216 | + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}") | |
| 190 | 217 | now = datetime.now(ZoneInfo("America/Toronto")) |
| 191 | 218 | per = self.d.get("period", {}) or {} |
| 192 | 219 | p.set_xy(24, 125) |
@@ -195,7 +222,7 @@ class GroupeKAReport: | ||
| 195 | 222 | ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")), |
| 196 | 223 | ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"), |
| 197 | 224 | ("Plateforme", "https://" + self.site.get("domain", "")), |
| 198 | − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"), | |
| 225 | + ("Type de rapport", REPORT_MODES[self.mode]), | |
| 199 | 226 | ] |
| 200 | 227 | y = 128 |
| 201 | 228 | for k, v in rows: |
@@ -207,7 +234,6 @@ class GroupeKAReport: | ||
| 207 | 234 | p.cell(0, 6, str(v)) |
| 208 | 235 | p.set_font("helvetica", "", 10.5) |
| 209 | 236 | y += 8 |
| 210 | − # bande encre au pied | |
| 211 | 237 | p.set_fill_color(*INK) |
| 212 | 238 | p.rect(10, 262, 190, 25, style="F") |
| 213 | 239 | p.set_xy(24, 270) |
@@ -232,7 +258,7 @@ class GroupeKAReport: | ||
| 232 | 258 | p = self.pdf |
| 233 | 259 | cols, gw, gh, gap = 3, 56, 26, 3 |
| 234 | 260 | x0, y = p.l_margin, p.get_y() |
| 235 | − for i, k in enumerate(kpis[:9]): | |
| 261 | + for i, k in enumerate(kpis[:12]): | |
| 236 | 262 | x = x0 + (i % cols) * (gw + gap) |
| 237 | 263 | if i and i % cols == 0: |
| 238 | 264 | y += gh + gap |
@@ -254,20 +280,81 @@ class GroupeKAReport: | ||
| 254 | 280 | p.set_font("helvetica", "B", 8) |
| 255 | 281 | p.set_text_color(*(GREEN if up else DANGER)) |
| 256 | 282 | arrow = "+" if k["delta_pct"] >= 0 else "" |
| 257 | − 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.") | |
| 286 | + p.set_y(y + gh + 8) | |
| 287 | + | |
| 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") | |
| 258 | 330 | p.set_y(y + gh + 8) |
| 259 | 331 | |
| 260 | − def _line_chart(self, s): | |
| 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): | |
| 261 | 348 | p = self.pdf |
| 262 | 349 | pts = s.get("points") or [] |
| 263 | 350 | if len(pts) < 2: |
| 264 | 351 | return |
| 352 | + if s.get("kind") == "bar": | |
| 353 | + self._vbars(s) | |
| 354 | + return | |
| 265 | 355 | if p.get_y() > 200: |
| 266 | 356 | p.add_page() |
| 267 | − p.set_font("helvetica", "B", 10) | |
| 268 | − p.set_text_color(*INK) | |
| 269 | − p.cell(0, 6, s.get("title", "")) | |
| 270 | − p.ln(7) | |
| 357 | + self._chart_title(s.get("title", "")) | |
| 271 | 358 | x0, y0, w, h = p.l_margin, p.get_y(), 174, 52 |
| 272 | 359 | self._card(x0, y0, w, h, fill=WHITE) |
| 273 | 360 | cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16 |
@@ -275,7 +362,6 @@ class GroupeKAReport: | ||
| 275 | 362 | vmax = max(vals) or 1 |
| 276 | 363 | vmin = min(0, min(vals)) |
| 277 | 364 | rng = (vmax - vmin) or 1 |
| 278 | − # grille + graduations | |
| 279 | 365 | p.set_font("helvetica", "", 6.3) |
| 280 | 366 | p.set_text_color(*INK3) |
| 281 | 367 | p.set_draw_color(200, 200, 195) |
@@ -286,6 +372,20 @@ class GroupeKAReport: | ||
| 286 | 372 | p.set_xy(x0 + 1, gy - 1.6) |
| 287 | 373 | p.cell(10, 3, _fr(vmin + rng * g / 4), align="R") |
| 288 | 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 | + | |
| 289 | 389 | def draw(series, color, width, dash=None): |
| 290 | 390 | n = len(series) |
| 291 | 391 | p.set_draw_color(*color) |
@@ -294,8 +394,7 @@ class GroupeKAReport: | ||
| 294 | 394 | p.set_dash_pattern(dash=1.2, gap=1.2) |
| 295 | 395 | last = None |
| 296 | 396 | for i, pt in enumerate(series): |
| 297 | − px = cx + cw * (i / (n - 1)) | |
| 298 | − py = cy + ch - ch * ((pt["v"] - vmin) / rng) | |
| 397 | + px, py = xy(i, n, pt["v"]) | |
| 299 | 398 | if last: |
| 300 | 399 | p.line(last[0], last[1], px, py) |
| 301 | 400 | last = (px, py) |
@@ -304,7 +403,6 @@ class GroupeKAReport: | ||
| 304 | 403 | if s.get("compare"): |
| 305 | 404 | draw(s["compare"], INK3, 0.35, dash=True) |
| 306 | 405 | draw(pts, self.accent, 0.7) |
| 307 | − # libellés d'axe X (premier / milieu / dernier) | |
| 308 | 406 | p.set_text_color(*INK3) |
| 309 | 407 | for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)): |
| 310 | 408 | p.set_xy(cx + cw * frac - 9, cy + ch + 1.5) |
@@ -314,9 +412,166 @@ class GroupeKAReport: | ||
| 314 | 412 | p.set_font("helvetica", "", 6.8) |
| 315 | 413 | p.set_text_color(*INK3) |
| 316 | 414 | p.cell(0, 4, "— période courante (accent) · ---- période comparée") |
| 317 | − p.ln(6) | |
| 318 | − else: | |
| 319 | − 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) | |
| 320 | 575 | |
| 321 | 576 | def _bars(self, title, items, unit=""): |
| 322 | 577 | p = self.pdf |
@@ -326,10 +581,8 @@ class GroupeKAReport: | ||
| 326 | 581 | need = 10 + len(items) * 7 |
| 327 | 582 | if p.get_y() + need > 265: |
| 328 | 583 | p.add_page() |
| 329 | − p.set_font("helvetica", "B", 10) | |
| 330 | − p.set_text_color(*INK) | |
| 331 | − p.cell(0, 6, title) | |
| 332 | − p.ln(8) | |
| 584 | + self._chart_title(title) | |
| 585 | + p.ln(1) | |
| 333 | 586 | vmax = max(it["value"] for it in items) or 1 |
| 334 | 587 | for it in items: |
| 335 | 588 | y = p.get_y() |
@@ -337,19 +590,23 @@ class GroupeKAReport: | ||
| 337 | 590 | p.set_text_color(*INK) |
| 338 | 591 | p.set_x(p.l_margin) |
| 339 | 592 | p.cell(46, 5, str(it["label"])[:34]) |
| 340 | − bw = 96 * (it["value"] / vmax) | |
| 593 | + bw = 86 * (it["value"] / vmax) | |
| 341 | 594 | p.set_fill_color(*self.accent) |
| 342 | 595 | p.set_draw_color(*INK) |
| 343 | 596 | p.set_line_width(0.25) |
| 344 | 597 | p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF") |
| 345 | − p.set_xy(p.l_margin + 148, y) | |
| 598 | + p.set_xy(p.l_margin + 136, y) | |
| 346 | 599 | p.set_font("helvetica", "B", 7.6) |
| 347 | − 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") | |
| 348 | 606 | p.ln(6.4) |
| 349 | 607 | p.ln(3) |
| 350 | 608 | |
| 351 | 609 | def _donut(self, b): |
| 352 | − # anneau vectoriel simple (arcs) + légende | |
| 353 | 610 | p = self.pdf |
| 354 | 611 | items = [it for it in (b.get("items") or []) if it.get("value")][:8] |
| 355 | 612 | total = sum(it["value"] for it in items) |
@@ -357,17 +614,13 @@ class GroupeKAReport: | ||
| 357 | 614 | return |
| 358 | 615 | if p.get_y() > 210: |
| 359 | 616 | p.add_page() |
| 360 | − p.set_font("helvetica", "B", 10) | |
| 361 | − p.set_text_color(*INK) | |
| 362 | − p.cell(0, 6, b.get("title", "")) | |
| 363 | − p.ln(8) | |
| 617 | + self._chart_title(b.get("title", "")) | |
| 618 | + p.ln(1) | |
| 364 | 619 | cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20 |
| 365 | − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10] | |
| 366 | 620 | start = -90.0 |
| 367 | 621 | for i, it in enumerate(items): |
| 368 | 622 | frac = it["value"] / total |
| 369 | − f = shades[i % len(shades)] | |
| 370 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 623 | + col = self._shade(i) | |
| 371 | 624 | steps = max(2, int(72 * frac)) |
| 372 | 625 | p.set_fill_color(*col) |
| 373 | 626 | p.set_draw_color(*col) |
@@ -386,11 +639,9 @@ class GroupeKAReport: | ||
| 386 | 639 | p.set_line_width(0.4) |
| 387 | 640 | p.ellipse(cx - 11, cy - 11, 22, 22, style="DF") |
| 388 | 641 | p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D") |
| 389 | − # légende | |
| 390 | 642 | ly = cy - 22 |
| 391 | 643 | for i, it in enumerate(items): |
| 392 | − f = shades[i % len(shades)] | |
| 393 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 644 | + col = self._shade(i) | |
| 394 | 645 | p.set_fill_color(*col) |
| 395 | 646 | p.set_draw_color(*INK) |
| 396 | 647 | p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF") |
@@ -402,7 +653,39 @@ class GroupeKAReport: | ||
| 402 | 653 | ly += 5.6 |
| 403 | 654 | p.set_y(max(cy + r, ly) + 6) |
| 404 | 655 | |
| 405 | − 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): | |
| 406 | 689 | p = self.pdf |
| 407 | 690 | cols = t.get("columns") or [] |
| 408 | 691 | rows = t.get("rows") or [] |
@@ -419,7 +702,7 @@ class GroupeKAReport: | ||
| 419 | 702 | p.ln(6) |
| 420 | 703 | head() |
| 421 | 704 | p.set_text_color(*INK) |
| 422 | − for i, row in enumerate(rows[:200]): | |
| 705 | + for i, row in enumerate(rows[:max_rows]): | |
| 423 | 706 | if p.get_y() > 262: |
| 424 | 707 | p.add_page() |
| 425 | 708 | head() |
@@ -430,10 +713,10 @@ class GroupeKAReport: | ||
| 430 | 713 | txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell) |
| 431 | 714 | p.cell(w, 5.4, " " + txt[:34], fill=True) |
| 432 | 715 | p.ln(5.4) |
| 433 | − if len(rows) > 200: | |
| 716 | + if len(rows) > max_rows: | |
| 434 | 717 | p.set_font("helvetica", "", 7) |
| 435 | 718 | p.set_text_color(*INK3) |
| 436 | − 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") | |
| 437 | 720 | p.ln(6) |
| 438 | 721 | |
| 439 | 722 | def _records(self): |
@@ -442,7 +725,7 @@ class GroupeKAReport: | ||
| 442 | 725 | return |
| 443 | 726 | self._section_title("Records & faits marquants") |
| 444 | 727 | p = self.pdf |
| 445 | − for r in recs[:10]: | |
| 728 | + for r in recs[:14]: | |
| 446 | 729 | if p.get_y() > 258: |
| 447 | 730 | p.add_page() |
| 448 | 731 | y = p.get_y() |
@@ -500,43 +783,76 @@ class GroupeKAReport: | ||
| 500 | 783 | "groupe-ka.com/conditions · /confidentialite · /loi-25.", |
| 501 | 784 | ) |
| 502 | 785 | |
| 503 | − def _toc_page(self): | |
| 504 | − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en | |
| 505 | − # page 2 en réservant la page lors du build (voir build()). | |
| 506 | − 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() | |
| 507 | 807 | |
| 508 | 808 | def build(self) -> bytes: |
| 509 | 809 | p = self.pdf |
| 510 | 810 | p.alias_nb_pages() |
| 511 | 811 | self._cover() |
| 812 | + with_toc = self.mode in ("complet", "donnees") | |
| 813 | + toc_page_no = None | |
| 512 | 814 | if self.mode == "synthese": |
| 513 | 815 | p.add_page() |
| 514 | 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) | |
| 515 | 825 | self._records() |
| 516 | 826 | self._final_page() |
| 517 | − 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 | |
| 518 | 839 | p.add_page() |
| 519 | 840 | toc_page_no = p.page_no() |
| 520 | 841 | p.add_page() |
| 521 | 842 | self._kpis() |
| 522 | − for s in self.d.get("series") or []: | |
| 523 | − if s.get("kind") == "bar": | |
| 524 | − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", "")) | |
| 525 | − else: | |
| 526 | − self._line_chart(s) | |
| 527 | − for b in self.d.get("breakdowns") or []: | |
| 528 | − if b.get("kind") == "donut": | |
| 529 | − self._donut(b) | |
| 530 | − else: | |
| 531 | − self._bars(b.get("title", ""), b.get("items")) | |
| 532 | − geo = self.d.get("geo") | |
| 533 | − if geo: | |
| 534 | − 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() | |
| 535 | 850 | for t in self.d.get("tables") or []: |
| 536 | 851 | self._table(t) |
| 537 | 852 | self._records() |
| 538 | 853 | self._final_page() |
| 539 | − # 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: | |
| 540 | 856 | last_page = p.page |
| 541 | 857 | p.page = toc_page_no |
| 542 | 858 | p.set_y(22) |
@@ -555,6 +871,7 @@ class GroupeKAReport: | ||
| 555 | 871 | return bytes(p.output()) |
| 556 | 872 | |
| 557 | 873 | |
| 558 | −def filename(platform_id: str, period: str) -> str: | |
| 874 | +def filename(platform_id: str, period: str, mode: str = "complet") -> str: | |
| 559 | 875 | today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d") |
| 560 | − 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" | |
| 561 | 878 | |