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)
8 changed files +2,012 −404
modified
apps/api/kapdf.py
+390 −71
@@ -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: | |
| 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,7 +111,9 @@ class _PDF(FPDF): | ||
| 95 | 111 | self.set_y(20) |
| 96 | 112 | |
| 97 | 113 | def footer(self): |
| 98 | − if self.cover_mode: | |
| 114 | + # page 1 = couverture (le flag cover_mode est déjà retombé quand | |
| 115 | + # add_page() clôt la page 1 → tester aussi le numéro de page) | |
| 116 | + if self.cover_mode or self.page_no() == 1: | |
| 99 | 117 | return |
| 100 | 118 | self.set_y(-15) |
| 101 | 119 | self.set_draw_color(*INK3) |
@@ -112,7 +130,7 @@ class GroupeKAReport: | ||
| 112 | 130 | def __init__(self, site: dict, dashboard: dict, mode: str = "complet"): |
| 113 | 131 | self.site = site |
| 114 | 132 | self.d = dashboard |
| 115 | − self.mode = mode | |
| 133 | + self.mode = mode if mode in REPORT_MODES else "complet" | |
| 116 | 134 | self.accent = _hex(site.get("accent", "#d9f26b")) |
| 117 | 135 | period = dashboard.get("period", {}) or {} |
| 118 | 136 | self.period_label = period.get("label") or "toute la période" |
@@ -127,6 +145,11 @@ class GroupeKAReport: | ||
| 127 | 145 | p.set_fill_color(*fill) |
| 128 | 146 | p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2) |
| 129 | 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 | + | |
| 130 | 153 | def _kicker(self, text): |
| 131 | 154 | p = self.pdf |
| 132 | 155 | p.set_font("helvetica", "B", 8) |
@@ -150,6 +173,14 @@ class GroupeKAReport: | ||
| 150 | 173 | self.toc.append((title, self.pdf.page_no())) |
| 151 | 174 | self.pdf.ln(11) |
| 152 | 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 | + | |
| 153 | 184 | # ---------- pages ---------- |
| 154 | 185 | def _cover(self): |
| 155 | 186 | p = self.pdf |
@@ -161,12 +192,10 @@ class GroupeKAReport: | ||
| 161 | 192 | p.set_draw_color(*INK) |
| 162 | 193 | p.set_line_width(1.0) |
| 163 | 194 | p.rect(10, 10, 190, 277) |
| 164 | − # kicker | |
| 165 | 195 | p.set_font("helvetica", "B", 10) |
| 166 | 196 | p.set_text_color(*GREEN) |
| 167 | 197 | p.set_xy(24, 34) |
| 168 | 198 | p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE") |
| 169 | − # wordmark : partie gauche + boîte encre/accent | |
| 170 | 199 | wm = self.site.get("wordmark", "") |
| 171 | 200 | left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None) |
| 172 | 201 | p.set_xy(24, 70) |
@@ -184,7 +213,7 @@ class GroupeKAReport: | ||
| 184 | 213 | p.set_xy(24, 100) |
| 185 | 214 | p.set_font("helvetica", "", 13) |
| 186 | 215 | p.set_text_color(*INK2) |
| 187 | − p.multi_cell(150, 7, f"Rapport statistique — {wm}") | |
| 216 | + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}") | |
| 188 | 217 | now = datetime.now(ZoneInfo("America/Toronto")) |
| 189 | 218 | per = self.d.get("period", {}) or {} |
| 190 | 219 | p.set_xy(24, 125) |
@@ -193,7 +222,7 @@ class GroupeKAReport: | ||
| 193 | 222 | ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")), |
| 194 | 223 | ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"), |
| 195 | 224 | ("Plateforme", "https://" + self.site.get("domain", "")), |
| 196 | − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"), | |
| 225 | + ("Type de rapport", REPORT_MODES[self.mode]), | |
| 197 | 226 | ] |
| 198 | 227 | y = 128 |
| 199 | 228 | for k, v in rows: |
@@ -205,7 +234,6 @@ class GroupeKAReport: | ||
| 205 | 234 | p.cell(0, 6, str(v)) |
| 206 | 235 | p.set_font("helvetica", "", 10.5) |
| 207 | 236 | y += 8 |
| 208 | − # bande encre au pied | |
| 209 | 237 | p.set_fill_color(*INK) |
| 210 | 238 | p.rect(10, 262, 190, 25, style="F") |
| 211 | 239 | p.set_xy(24, 270) |
@@ -230,7 +258,7 @@ class GroupeKAReport: | ||
| 230 | 258 | p = self.pdf |
| 231 | 259 | cols, gw, gh, gap = 3, 56, 26, 3 |
| 232 | 260 | x0, y = p.l_margin, p.get_y() |
| 233 | − for i, k in enumerate(kpis[:9]): | |
| 261 | + for i, k in enumerate(kpis[:12]): | |
| 234 | 262 | x = x0 + (i % cols) * (gw + gap) |
| 235 | 263 | if i and i % cols == 0: |
| 236 | 264 | y += gh + gap |
@@ -252,20 +280,81 @@ class GroupeKAReport: | ||
| 252 | 280 | p.set_font("helvetica", "B", 8) |
| 253 | 281 | p.set_text_color(*(GREEN if up else DANGER)) |
| 254 | 282 | arrow = "+" if k["delta_pct"] >= 0 else "" |
| 255 | − 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.") | |
| 256 | 286 | p.set_y(y + gh + 8) |
| 257 | 287 | |
| 258 | − def _line_chart(self, s): | |
| 288 | + def _gauges(self): | |
| 289 | + gs = self.d.get("gauges") or [] | |
| 290 | + gs = [g for g in gs if isinstance(g.get("value"), (int, float)) and g.get("max")] | |
| 291 | + if not gs: | |
| 292 | + return | |
| 293 | + self._section_title("Taux & couvertures") | |
| 294 | + p = self.pdf | |
| 295 | + cols, gw, gh, gap = 3, 56, 34, 3 | |
| 296 | + x0, y = p.l_margin, p.get_y() | |
| 297 | + for i, g in enumerate(gs[:9]): | |
| 298 | + x = x0 + (i % cols) * (gw + gap) | |
| 299 | + if i and i % cols == 0: | |
| 300 | + y += gh + gap | |
| 301 | + if y > 240: | |
| 302 | + p.add_page(); y = p.get_y() | |
| 303 | + self._card(x, y, gw, gh) | |
| 304 | + frac = max(0.0, min(1.0, g["value"] / g["max"])) | |
| 305 | + cx, cy, r = x + gw / 2, y + 20, 14 | |
| 306 | + # arc de fond + arc de valeur (demi-cercle en petits segments) | |
| 307 | + for pass_col, pass_frac, lw in (((225, 223, 217), 1.0, 2.6), (self.accent, frac, 2.6)): | |
| 308 | + p.set_draw_color(*pass_col) | |
| 309 | + p.set_line_width(lw) | |
| 310 | + steps = max(2, int(60 * pass_frac)) | |
| 311 | + last = None | |
| 312 | + for st in range(steps + 1): | |
| 313 | + a = math.pi + math.pi * pass_frac * st / steps | |
| 314 | + pt = (cx + r * math.cos(a), cy + r * math.sin(a)) | |
| 315 | + if last: | |
| 316 | + p.line(last[0], last[1], pt[0], pt[1]) | |
| 317 | + last = pt | |
| 318 | + p.set_font("helvetica", "B", 11) | |
| 319 | + p.set_text_color(*INK) | |
| 320 | + p.set_xy(x + 4, cy - 5) | |
| 321 | + p.cell(gw - 8, 6, f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}", align="C") | |
| 322 | + p.set_font("helvetica", "", 6.6) | |
| 323 | + p.set_text_color(*INK3) | |
| 324 | + p.set_xy(x + 4, cy + 1.5) | |
| 325 | + p.cell(gw - 8, 4, f"{frac * 100:.0f} % de {_fr(g['max'])}", align="C") | |
| 326 | + p.set_xy(x + 3, y + gh - 7) | |
| 327 | + p.set_font("helvetica", "", 7) | |
| 328 | + p.set_text_color(*INK2) | |
| 329 | + p.multi_cell(gw - 6, 3.3, str(g.get("label", ""))[:60], align="C") | |
| 330 | + p.set_y(y + gh + 8) | |
| 331 | + | |
| 332 | + def _serie_stats_row(self, s): | |
| 333 | + """Ligne min/max/moyenne/médiane sous un graphique de série.""" | |
| 334 | + p = self.pdf | |
| 335 | + vs = [pt["v"] for pt in (s.get("points") or []) if isinstance(pt.get("v"), (int, float))] | |
| 336 | + if len(vs) < 2: | |
| 337 | + return | |
| 338 | + sv = sorted(vs) | |
| 339 | + mean = sum(vs) / len(vs) | |
| 340 | + med = sv[len(sv) // 2] | |
| 341 | + sd = math.sqrt(sum((v - mean) ** 2 for v in vs) / len(vs)) | |
| 342 | + p.set_font("helvetica", "", 6.8) | |
| 343 | + p.set_text_color(*INK3) | |
| 344 | + p.cell(0, 4, f"min {_fr(sv[0])} · max {_fr(sv[-1])} · moyenne {_fr(round(mean, 2))} · médiane {_fr(med)} · écart-type {_fr(round(sd, 2))}") | |
| 345 | + p.ln(5.5) | |
| 346 | + | |
| 347 | + def _line_chart(self, s, with_stats=False): | |
| 259 | 348 | p = self.pdf |
| 260 | 349 | pts = s.get("points") or [] |
| 261 | 350 | if len(pts) < 2: |
| 262 | 351 | return |
| 352 | + if s.get("kind") == "bar": | |
| 353 | + self._vbars(s) | |
| 354 | + return | |
| 263 | 355 | if p.get_y() > 200: |
| 264 | 356 | p.add_page() |
| 265 | − p.set_font("helvetica", "B", 10) | |
| 266 | − p.set_text_color(*INK) | |
| 267 | − p.cell(0, 6, s.get("title", "")) | |
| 268 | − p.ln(7) | |
| 357 | + self._chart_title(s.get("title", "")) | |
| 269 | 358 | x0, y0, w, h = p.l_margin, p.get_y(), 174, 52 |
| 270 | 359 | self._card(x0, y0, w, h, fill=WHITE) |
| 271 | 360 | cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16 |
@@ -273,7 +362,6 @@ class GroupeKAReport: | ||
| 273 | 362 | vmax = max(vals) or 1 |
| 274 | 363 | vmin = min(0, min(vals)) |
| 275 | 364 | rng = (vmax - vmin) or 1 |
| 276 | − # grille + graduations | |
| 277 | 365 | p.set_font("helvetica", "", 6.3) |
| 278 | 366 | p.set_text_color(*INK3) |
| 279 | 367 | p.set_draw_color(200, 200, 195) |
@@ -284,6 +372,20 @@ class GroupeKAReport: | ||
| 284 | 372 | p.set_xy(x0 + 1, gy - 1.6) |
| 285 | 373 | p.cell(10, 3, _fr(vmin + rng * g / 4), align="R") |
| 286 | 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 | + | |
| 287 | 389 | def draw(series, color, width, dash=None): |
| 288 | 390 | n = len(series) |
| 289 | 391 | p.set_draw_color(*color) |
@@ -292,8 +394,7 @@ class GroupeKAReport: | ||
| 292 | 394 | p.set_dash_pattern(dash=1.2, gap=1.2) |
| 293 | 395 | last = None |
| 294 | 396 | for i, pt in enumerate(series): |
| 295 | − px = cx + cw * (i / (n - 1)) | |
| 296 | − py = cy + ch - ch * ((pt["v"] - vmin) / rng) | |
| 397 | + px, py = xy(i, n, pt["v"]) | |
| 297 | 398 | if last: |
| 298 | 399 | p.line(last[0], last[1], px, py) |
| 299 | 400 | last = (px, py) |
@@ -302,7 +403,6 @@ class GroupeKAReport: | ||
| 302 | 403 | if s.get("compare"): |
| 303 | 404 | draw(s["compare"], INK3, 0.35, dash=True) |
| 304 | 405 | draw(pts, self.accent, 0.7) |
| 305 | − # libellés d'axe X (premier / milieu / dernier) | |
| 306 | 406 | p.set_text_color(*INK3) |
| 307 | 407 | for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)): |
| 308 | 408 | p.set_xy(cx + cw * frac - 9, cy + ch + 1.5) |
@@ -312,9 +412,166 @@ class GroupeKAReport: | ||
| 312 | 412 | p.set_font("helvetica", "", 6.8) |
| 313 | 413 | p.set_text_color(*INK3) |
| 314 | 414 | p.cell(0, 4, "— période courante (accent) · ---- période comparée") |
| 315 | − p.ln(6) | |
| 316 | − else: | |
| 317 | − 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) | |
| 318 | 575 | |
| 319 | 576 | def _bars(self, title, items, unit=""): |
| 320 | 577 | p = self.pdf |
@@ -324,10 +581,8 @@ class GroupeKAReport: | ||
| 324 | 581 | need = 10 + len(items) * 7 |
| 325 | 582 | if p.get_y() + need > 265: |
| 326 | 583 | p.add_page() |
| 327 | − p.set_font("helvetica", "B", 10) | |
| 328 | − p.set_text_color(*INK) | |
| 329 | − p.cell(0, 6, title) | |
| 330 | − p.ln(8) | |
| 584 | + self._chart_title(title) | |
| 585 | + p.ln(1) | |
| 331 | 586 | vmax = max(it["value"] for it in items) or 1 |
| 332 | 587 | for it in items: |
| 333 | 588 | y = p.get_y() |
@@ -335,19 +590,23 @@ class GroupeKAReport: | ||
| 335 | 590 | p.set_text_color(*INK) |
| 336 | 591 | p.set_x(p.l_margin) |
| 337 | 592 | p.cell(46, 5, str(it["label"])[:34]) |
| 338 | − bw = 96 * (it["value"] / vmax) | |
| 593 | + bw = 86 * (it["value"] / vmax) | |
| 339 | 594 | p.set_fill_color(*self.accent) |
| 340 | 595 | p.set_draw_color(*INK) |
| 341 | 596 | p.set_line_width(0.25) |
| 342 | 597 | p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF") |
| 343 | − p.set_xy(p.l_margin + 148, y) | |
| 598 | + p.set_xy(p.l_margin + 136, y) | |
| 344 | 599 | p.set_font("helvetica", "B", 7.6) |
| 345 | − 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") | |
| 346 | 606 | p.ln(6.4) |
| 347 | 607 | p.ln(3) |
| 348 | 608 | |
| 349 | 609 | def _donut(self, b): |
| 350 | − # anneau vectoriel simple (arcs) + légende | |
| 351 | 610 | p = self.pdf |
| 352 | 611 | items = [it for it in (b.get("items") or []) if it.get("value")][:8] |
| 353 | 612 | total = sum(it["value"] for it in items) |
@@ -355,17 +614,13 @@ class GroupeKAReport: | ||
| 355 | 614 | return |
| 356 | 615 | if p.get_y() > 210: |
| 357 | 616 | p.add_page() |
| 358 | − p.set_font("helvetica", "B", 10) | |
| 359 | − p.set_text_color(*INK) | |
| 360 | − p.cell(0, 6, b.get("title", "")) | |
| 361 | − p.ln(8) | |
| 617 | + self._chart_title(b.get("title", "")) | |
| 618 | + p.ln(1) | |
| 362 | 619 | cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20 |
| 363 | − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10] | |
| 364 | 620 | start = -90.0 |
| 365 | 621 | for i, it in enumerate(items): |
| 366 | 622 | frac = it["value"] / total |
| 367 | − f = shades[i % len(shades)] | |
| 368 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 623 | + col = self._shade(i) | |
| 369 | 624 | steps = max(2, int(72 * frac)) |
| 370 | 625 | p.set_fill_color(*col) |
| 371 | 626 | p.set_draw_color(*col) |
@@ -384,11 +639,9 @@ class GroupeKAReport: | ||
| 384 | 639 | p.set_line_width(0.4) |
| 385 | 640 | p.ellipse(cx - 11, cy - 11, 22, 22, style="DF") |
| 386 | 641 | p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D") |
| 387 | − # légende | |
| 388 | 642 | ly = cy - 22 |
| 389 | 643 | for i, it in enumerate(items): |
| 390 | − f = shades[i % len(shades)] | |
| 391 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 644 | + col = self._shade(i) | |
| 392 | 645 | p.set_fill_color(*col) |
| 393 | 646 | p.set_draw_color(*INK) |
| 394 | 647 | p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF") |
@@ -400,7 +653,39 @@ class GroupeKAReport: | ||
| 400 | 653 | ly += 5.6 |
| 401 | 654 | p.set_y(max(cy + r, ly) + 6) |
| 402 | 655 | |
| 403 | − 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): | |
| 404 | 689 | p = self.pdf |
| 405 | 690 | cols = t.get("columns") or [] |
| 406 | 691 | rows = t.get("rows") or [] |
@@ -417,7 +702,7 @@ class GroupeKAReport: | ||
| 417 | 702 | p.ln(6) |
| 418 | 703 | head() |
| 419 | 704 | p.set_text_color(*INK) |
| 420 | − for i, row in enumerate(rows[:200]): | |
| 705 | + for i, row in enumerate(rows[:max_rows]): | |
| 421 | 706 | if p.get_y() > 262: |
| 422 | 707 | p.add_page() |
| 423 | 708 | head() |
@@ -428,10 +713,10 @@ class GroupeKAReport: | ||
| 428 | 713 | txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell) |
| 429 | 714 | p.cell(w, 5.4, " " + txt[:34], fill=True) |
| 430 | 715 | p.ln(5.4) |
| 431 | − if len(rows) > 200: | |
| 716 | + if len(rows) > max_rows: | |
| 432 | 717 | p.set_font("helvetica", "", 7) |
| 433 | 718 | p.set_text_color(*INK3) |
| 434 | − 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") | |
| 435 | 720 | p.ln(6) |
| 436 | 721 | |
| 437 | 722 | def _records(self): |
@@ -440,7 +725,7 @@ class GroupeKAReport: | ||
| 440 | 725 | return |
| 441 | 726 | self._section_title("Records & faits marquants") |
| 442 | 727 | p = self.pdf |
| 443 | − for r in recs[:10]: | |
| 728 | + for r in recs[:14]: | |
| 444 | 729 | if p.get_y() > 258: |
| 445 | 730 | p.add_page() |
| 446 | 731 | y = p.get_y() |
@@ -498,43 +783,76 @@ class GroupeKAReport: | ||
| 498 | 783 | "groupe-ka.com/conditions · /confidentialite · /loi-25.", |
| 499 | 784 | ) |
| 500 | 785 | |
| 501 | − def _toc_page(self): | |
| 502 | − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en | |
| 503 | − # page 2 en réservant la page lors du build (voir build()). | |
| 504 | − 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() | |
| 505 | 807 | |
| 506 | 808 | def build(self) -> bytes: |
| 507 | 809 | p = self.pdf |
| 508 | 810 | p.alias_nb_pages() |
| 509 | 811 | self._cover() |
| 812 | + with_toc = self.mode in ("complet", "donnees") | |
| 813 | + toc_page_no = None | |
| 510 | 814 | if self.mode == "synthese": |
| 511 | 815 | p.add_page() |
| 512 | 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) | |
| 513 | 825 | self._records() |
| 514 | 826 | self._final_page() |
| 515 | − 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 | |
| 516 | 839 | p.add_page() |
| 517 | 840 | toc_page_no = p.page_no() |
| 518 | 841 | p.add_page() |
| 519 | 842 | self._kpis() |
| 520 | − for s in self.d.get("series") or []: | |
| 521 | − if s.get("kind") == "bar": | |
| 522 | − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", "")) | |
| 523 | − else: | |
| 524 | − self._line_chart(s) | |
| 525 | − for b in self.d.get("breakdowns") or []: | |
| 526 | − if b.get("kind") == "donut": | |
| 527 | − self._donut(b) | |
| 528 | − else: | |
| 529 | − self._bars(b.get("title", ""), b.get("items")) | |
| 530 | − geo = self.d.get("geo") | |
| 531 | − if geo: | |
| 532 | − 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() | |
| 533 | 850 | for t in self.d.get("tables") or []: |
| 534 | 851 | self._table(t) |
| 535 | 852 | self._records() |
| 536 | 853 | self._final_page() |
| 537 | − # 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: | |
| 538 | 856 | last_page = p.page |
| 539 | 857 | p.page = toc_page_no |
| 540 | 858 | p.set_y(22) |
@@ -553,6 +871,7 @@ class GroupeKAReport: | ||
| 553 | 871 | return bytes(p.output()) |
| 554 | 872 | |
| 555 | 873 | |
| 556 | −def filename(platform_id: str, period: str) -> str: | |
| 874 | +def filename(platform_id: str, period: str, mode: str = "complet") -> str: | |
| 557 | 875 | today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d") |
| 558 | − 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
apps/api/main.py
+6 −4
@@ -24,7 +24,7 @@ from fastapi.middleware.cors import CORSMiddleware | ||
| 24 | 24 | from pydantic import BaseModel |
| 25 | 25 | |
| 26 | 26 | from trouveka.api import stats as stats_mod |
| 27 | −from trouveka.api.kapdf import GroupeKAReport | |
| 27 | +from trouveka.api.kapdf import REPORT_MODES, GroupeKAReport | |
| 28 | 28 | from trouveka.api.kapdf import filename as pdf_filename |
| 29 | 29 | from trouveka.config import get_settings |
| 30 | 30 | from trouveka.database import Database |
@@ -317,9 +317,11 @@ async def api_stats_report( | ||
| 317 | 317 | period: str = Query("30j", pattern=PERIOD_PATTERN), |
| 318 | 318 | from_date: str | None = Query(None, alias="from", pattern=r"^\d{4}-\d{2}-\d{2}$"), |
| 319 | 319 | to_date: str | None = Query(None, alias="to", pattern=r"^\d{4}-\d{2}-\d{2}$"), |
| 320 | − mode: str = Query("complet", pattern="^(complet|synthese)$"), | |
| 320 | + mode: str = Query("complet", max_length=20), | |
| 321 | 321 | ): |
| 322 | − """Rapport PDF estampillé Groupe-KA (gabarit kapdf, graphiques vectoriels).""" | |
| 322 | + """Rapport PDF estampillé Groupe-KA — 5 modes (complet, synthese, | |
| 323 | + tendances, repartitions, donnees). Mode inconnu → complet (SPEC §3).""" | |
| 324 | + mode = mode if mode in REPORT_MODES else "complet" | |
| 323 | 325 | try: |
| 324 | 326 | dash = await stats_mod.dashboard(db, period, from_date, to_date) |
| 325 | 327 | pdf_bytes = await anyio.to_thread.run_sync( |
@@ -332,7 +334,7 @@ async def api_stats_report( | ||
| 332 | 334 | content=pdf_bytes, |
| 333 | 335 | media_type="application/pdf", |
| 334 | 336 | headers={ |
| 335 | − "Content-Disposition": f'attachment; filename="{pdf_filename("trouve-ka", period)}"' | |
| 337 | + "Content-Disposition": f'attachment; filename="{pdf_filename("trouve-ka", period, mode)}"' | |
| 336 | 338 | }, |
| 337 | 339 | ) |
| 338 | 340 | |
modified
apps/api/stats.py
+459 −94
@@ -2,12 +2,18 @@ | ||
| 2 | 2 | # Author: Simon-Pierre Boucher |
| 3 | 3 | # Contact: contact@spboucher.ai |
| 4 | 4 | |
| 5 | −"""Statistiques du moteur (contrat ka-ui/stats/SPEC.md). | |
| 5 | +"""Statistiques du moteur (contrat ka-ui/stats/SPEC.md v2). | |
| 6 | 6 | |
| 7 | 7 | - `dashboard()` agrège Postgres (documents, crawl_attempts, frontier_items, |
| 8 | − domains, search_queries) en JSON conforme au contrat /api/stats/dashboard. | |
| 8 | + domains, search_queries) en JSON conforme au contrat /api/stats/dashboard : | |
| 9 | + KPI (+sparklines), jauges, séries, multi-séries, empilées, répartitions, | |
| 10 | + distributions, heatmap calendrier, heatmap horaire 7×24, tableaux, records. | |
| 9 | 11 | - Cache mémoire par période (>= 5 min) : les tables sont volumineuses |
| 10 | 12 | (crawl_attempts ~5 M lignes), on ne re-agrège jamais à chaque appel. |
| 13 | + Toutes les requêtes sont bornées sur des colonnes indexées (fetched_at, | |
| 14 | + first_indexed_at, created_at) — jamais de scan complet par requête HTTP. | |
| 15 | + Les agrégats globaux lourds (profil documents, profondeurs frontier) | |
| 16 | + vivent dans un cache dédié (10 min à 1 h). | |
| 11 | 17 | - AUCUNE donnée inventée : une section sans données est simplement absente |
| 12 | 18 | (le front affiche « Pas encore mesuré »). |
| 13 | 19 | - Purge opportuniste des journaux de recherche (> 90 jours), 1×/jour max. |
@@ -17,7 +23,7 @@ from __future__ import annotations | ||
| 17 | 23 | |
| 18 | 24 | import asyncio |
| 19 | 25 | import time |
| 20 | −from datetime import date, datetime, timedelta | |
| 26 | +from datetime import datetime, timedelta | |
| 21 | 27 | from zoneinfo import ZoneInfo |
| 22 | 28 | |
| 23 | 29 | from trouveka.logging import get_logger |
@@ -62,6 +68,10 @@ FRONTIER_LABELS = { | ||
| 62 | 68 | "blocked": "Bloquée", |
| 63 | 69 | } |
| 64 | 70 | |
| 71 | +LANG_LABELS = {"fr": "Français", "en": "Anglais", "?": "Non détectée"} | |
| 72 | + | |
| 73 | +HTTP_CLASSES = ["2xx", "3xx", "4xx", "5xx", "Sans réponse"] | |
| 74 | + | |
| 65 | 75 | # Cache mémoire : clé période → (expiration monotonic, payload) |
| 66 | 76 | _cache: dict[str, tuple[float, dict]] = {} |
| 67 | 77 | _global_cache: dict[str, tuple[float, object]] = {} |
@@ -70,8 +80,8 @@ _last_purge = 0.0 | ||
| 70 | 80 | |
| 71 | 81 | CACHE_TTL = 300 # 5 min par période |
| 72 | 82 | CACHE_TTL_TOUT = 900 # « tout » agrège 5 M lignes : 15 min |
| 73 | −GLOBAL_TTL = 600 # heatmap / records globaux | |
| 74 | −DEEP_TTL = 3600 # domaine le plus profond (scan frontier 3,7 M lignes) | |
| 83 | +GLOBAL_TTL = 600 # heatmap / profil documents / records globaux | |
| 84 | +DEEP_TTL = 3600 # profondeurs frontier (scan 3,7 M lignes) : 1 h | |
| 75 | 85 | |
| 76 | 86 | |
| 77 | 87 | def _fr_int(n: int | float) -> str: |
@@ -85,6 +95,29 @@ def _delta(cur: float | None, prev: float | None) -> float | None: | ||
| 85 | 95 | return round(100.0 * (cur - prev) / prev, 1) |
| 86 | 96 | |
| 87 | 97 | |
| 98 | +def _spark(points: list[dict], max_pts: int = 40) -> list[dict] | None: | |
| 99 | + """Sous-échantillonne une série pour la sparkline d'un KPI (≥ 2 points).""" | |
| 100 | + pts = [p for p in points if isinstance(p.get("v"), (int, float))] | |
| 101 | + if len(pts) < 2: | |
| 102 | + return None | |
| 103 | + if len(pts) <= max_pts: | |
| 104 | + return pts | |
| 105 | + step = len(pts) / max_pts | |
| 106 | + out = [pts[int(i * step)] for i in range(max_pts)] | |
| 107 | + if out[-1] is not pts[-1]: | |
| 108 | + out.append(pts[-1]) | |
| 109 | + return out | |
| 110 | + | |
| 111 | + | |
| 112 | +def _mb(nbytes: int) -> tuple[float, str]: | |
| 113 | + """Octets → (valeur, unité) lisibles (Mo / Go / To).""" | |
| 114 | + if nbytes >= 1e12: | |
| 115 | + return round(nbytes / 1e12, 2), "To" | |
| 116 | + if nbytes >= 1e9: | |
| 117 | + return round(nbytes / 1e9, 2), "Go" | |
| 118 | + return round(nbytes / 1e6, 1), "Mo" | |
| 119 | + | |
| 120 | + | |
| 88 | 121 | def resolve_period( |
| 89 | 122 | period: str, from_s: str | None, to_s: str | None, dataset_start: datetime |
| 90 | 123 | ) -> tuple[datetime, datetime, str, datetime | None, datetime | None]: |
@@ -116,6 +149,28 @@ def resolve_period( | ||
| 116 | 149 | return start, end, label, start - span, start |
| 117 | 150 | |
| 118 | 151 | |
| 152 | +def _bucket_grid(start: datetime, end: datetime, bucket: str) -> tuple[list[datetime], list[str]]: | |
| 153 | + """Clés (datetime naïfs, heure locale — même forme que date_trunc AT TIME | |
| 154 | + ZONE) et libellés d'axe pour une plage, trous compris.""" | |
| 155 | + keys: list[datetime] = [] | |
| 156 | + labels: list[str] = [] | |
| 157 | + if bucket == "hour": | |
| 158 | + cur = start.replace(minute=0, second=0, microsecond=0) | |
| 159 | + while cur < end: | |
| 160 | + k = cur.astimezone(TZ).replace(tzinfo=None, minute=0, second=0, microsecond=0) | |
| 161 | + keys.append(k) | |
| 162 | + labels.append(k.strftime("%Hh")) | |
| 163 | + cur += timedelta(hours=1) | |
| 164 | + else: | |
| 165 | + cur_d = start.astimezone(TZ).date() | |
| 166 | + end_d = end.astimezone(TZ).date() | |
| 167 | + while cur_d <= end_d: | |
| 168 | + keys.append(datetime(cur_d.year, cur_d.month, cur_d.day)) | |
| 169 | + labels.append(cur_d.isoformat()) | |
| 170 | + cur_d += timedelta(days=1) | |
| 171 | + return keys, labels | |
| 172 | + | |
| 173 | + | |
| 119 | 174 | async def _dataset_start(db) -> datetime: |
| 120 | 175 | """Première trace du crawler (min borné par index) — cache 1 h.""" |
| 121 | 176 | hit = _global_cache.get("dataset_start") |
@@ -147,21 +202,8 @@ async def _bucket_counts( | ||
| 147 | 202 | start, end, |
| 148 | 203 | ) |
| 149 | 204 | got = {r["b"]: r["n"] for r in rows} |
| 150 | − points: list[dict] = [] | |
| 151 | − if bucket == "hour": | |
| 152 | − cur = start.replace(minute=0, second=0, microsecond=0) | |
| 153 | − while cur < end: | |
| 154 | − key = cur.astimezone(TZ).replace(tzinfo=None).replace(minute=0, second=0, microsecond=0) | |
| 155 | − points.append({"t": key.strftime("%Hh"), "v": got.get(key, 0)}) | |
| 156 | − cur += timedelta(hours=1) | |
| 157 | − else: | |
| 158 | − cur_d = start.astimezone(TZ).date() | |
| 159 | − end_d = end.astimezone(TZ).date() | |
| 160 | − while cur_d <= end_d: | |
| 161 | − key = datetime(cur_d.year, cur_d.month, cur_d.day) | |
| 162 | − points.append({"t": cur_d.isoformat(), "v": got.get(key, 0)}) | |
| 163 | − cur_d += timedelta(days=1) | |
| 164 | − return points | |
| 205 | + keys, labels = _bucket_grid(start, end, bucket) | |
| 206 | + return [{"t": lab, "v": got.get(k, 0)} for k, lab in zip(keys, labels)] | |
| 165 | 207 | |
| 166 | 208 | |
| 167 | 209 | async def _heatmap_cells(db) -> list[dict]: |
@@ -183,12 +225,48 @@ async def _heatmap_cells(db) -> list[dict]: | ||
| 183 | 225 | return cells |
| 184 | 226 | |
| 185 | 227 | |
| 186 | −async def _deepest_domain(db) -> dict | None: | |
| 187 | − """Domaine atteint à la plus grande profondeur de crawl (scan lourd → 1 h).""" | |
| 188 | − hit = _global_cache.get("deepest") | |
| 228 | +async def _doc_profile(db) -> dict: | |
| 229 | + """Profil global de l'index (1 seul passage sur documents, cache 10 min) : | |
| 230 | + total, fraîcheur < 30 j, langues, score Québec moyen.""" | |
| 231 | + hit = _global_cache.get("doc_profile") | |
| 189 | 232 | if hit and hit[0] > time.monotonic(): |
| 190 | 233 | return hit[1] # type: ignore[return-value] |
| 191 | − row = await db.pool.fetchrow( | |
| 234 | + fresh_since = datetime.now(TZ) - timedelta(days=30) | |
| 235 | + rows = await db.pool.fetch( | |
| 236 | + """ | |
| 237 | + SELECT coalesce(nullif(language, ''), '?') AS lang, | |
| 238 | + count(*)::int AS n, | |
| 239 | + count(*) FILTER (WHERE last_indexed_at >= $1)::int AS fresh, | |
| 240 | + sum(page_quebec_score)::float AS qs_sum | |
| 241 | + FROM documents GROUP BY 1 | |
| 242 | + """, | |
| 243 | + fresh_since, | |
| 244 | + ) | |
| 245 | + total = sum(r["n"] for r in rows) | |
| 246 | + prof = { | |
| 247 | + "total": total, | |
| 248 | + "fresh30": sum(r["fresh"] for r in rows), | |
| 249 | + "avg_qs": round(sum(r["qs_sum"] or 0 for r in rows) / total, 2) if total else None, | |
| 250 | + "langs": sorted( | |
| 251 | + ({"label": LANG_LABELS.get(r["lang"], r["lang"]), "value": r["n"]} for r in rows), | |
| 252 | + key=lambda x: -x["value"], | |
| 253 | + ), | |
| 254 | + } | |
| 255 | + _global_cache["doc_profile"] = (time.monotonic() + GLOBAL_TTL, prof) | |
| 256 | + return prof | |
| 257 | + | |
| 258 | + | |
| 259 | +async def _frontier_depths(db) -> tuple[list[dict], dict | None]: | |
| 260 | + """Distribution des profondeurs + domaine le plus profond (scans lourds | |
| 261 | + sur frontier_items ~3,7 M lignes → cache 1 h).""" | |
| 262 | + hit = _global_cache.get("frontier_depths") | |
| 263 | + if hit and hit[0] > time.monotonic(): | |
| 264 | + return hit[1] # type: ignore[return-value] | |
| 265 | + rows = await db.pool.fetch( | |
| 266 | + "SELECT least(depth, 10)::int AS d, count(*)::int AS n FROM frontier_items GROUP BY 1 ORDER BY 1" | |
| 267 | + ) | |
| 268 | + bins = [{"label": ("10+" if r["d"] >= 10 else str(r["d"])), "value": r["n"]} for r in rows] | |
| 269 | + deep = await db.pool.fetchrow( | |
| 192 | 270 | """ |
| 193 | 271 | SELECT d.domain, f.depth |
| 194 | 272 | FROM frontier_items f |
@@ -197,8 +275,47 @@ async def _deepest_domain(db) -> dict | None: | ||
| 197 | 275 | ORDER BY f.depth DESC LIMIT 1 |
| 198 | 276 | """ |
| 199 | 277 | ) |
| 200 | − val = {"domain": row["domain"], "depth": row["depth"]} if row else None | |
| 201 | − _global_cache["deepest"] = (time.monotonic() + DEEP_TTL, val) | |
| 278 | + deepest = {"domain": deep["domain"], "depth": deep["depth"]} if deep else None | |
| 279 | + val = (bins, deepest) | |
| 280 | + _global_cache["frontier_depths"] = (time.monotonic() + DEEP_TTL, val) | |
| 281 | + return val | |
| 282 | + | |
| 283 | + | |
| 284 | +async def _tld_breakdown(db) -> list[dict]: | |
| 285 | + """Pages indexées par TLD (table domains, petite — cache 10 min).""" | |
| 286 | + hit = _global_cache.get("tld") | |
| 287 | + if hit and hit[0] > time.monotonic(): | |
| 288 | + return hit[1] # type: ignore[return-value] | |
| 289 | + rows = await db.pool.fetch( | |
| 290 | + """ | |
| 291 | + SELECT CASE WHEN domain LIKE '%.qc.ca' THEN 'qc.ca' | |
| 292 | + ELSE substring(domain from '[^.]+$') END AS tld, | |
| 293 | + sum(page_count)::int AS n | |
| 294 | + FROM domains WHERE page_count > 0 | |
| 295 | + GROUP BY 1 ORDER BY n DESC LIMIT 9 | |
| 296 | + """ | |
| 297 | + ) | |
| 298 | + items = [{"label": "." + r["tld"], "value": r["n"]} for r in rows if r["tld"]] | |
| 299 | + _global_cache["tld"] = (time.monotonic() + GLOBAL_TTL, items) | |
| 300 | + return items | |
| 301 | + | |
| 302 | + | |
| 303 | +async def _crawl_hour_record(db) -> dict | None: | |
| 304 | + """Heure record de crawl sur 30 jours (plage indexée — cache 10 min).""" | |
| 305 | + hit = _global_cache.get("hour_record") | |
| 306 | + if hit and hit[0] > time.monotonic(): | |
| 307 | + return hit[1] # type: ignore[return-value] | |
| 308 | + since = datetime.now(TZ) - timedelta(days=30) | |
| 309 | + row = await db.pool.fetchrow( | |
| 310 | + """ | |
| 311 | + SELECT date_trunc('hour', fetched_at AT TIME ZONE 'America/Toronto') AS h, count(*)::int AS n | |
| 312 | + FROM crawl_attempts WHERE fetched_at >= $1 | |
| 313 | + GROUP BY 1 ORDER BY n DESC LIMIT 1 | |
| 314 | + """, | |
| 315 | + since, | |
| 316 | + ) | |
| 317 | + val = {"hour": row["h"], "n": row["n"]} if row else None | |
| 318 | + _global_cache["hour_record"] = (time.monotonic() + GLOBAL_TTL, val) | |
| 202 | 319 | return val |
| 203 | 320 | |
| 204 | 321 | |
@@ -237,133 +354,317 @@ async def _build(db, period: str, from_s: str | None, to_s: str | None) -> dict: | ||
| 237 | 354 | ds_start = await _dataset_start(db) |
| 238 | 355 | start, end, label, prev_start, prev_end = resolve_period(period, from_s, to_s, ds_start) |
| 239 | 356 | bucket = "hour" if (end - start) <= timedelta(hours=36) else "day" |
| 357 | + unit_sql = "hour" if bucket == "hour" else "day" | |
| 358 | + unit_label = "par heure" if bucket == "hour" else "par jour" | |
| 240 | 359 | hours = max((end - start).total_seconds() / 3600.0, 0.01) |
| 360 | + keys, klabels = _bucket_grid(start, end, bucket) | |
| 241 | 361 | |
| 242 | 362 | await _purge_old_queries(db) |
| 243 | 363 | |
| 244 | − # ---- KPI (toutes les bornes exploitent les index temporels) ---- | |
| 245 | − cur = await db.pool.fetchrow( | |
| 246 | − """ | |
| 247 | − SELECT | |
| 248 | − (SELECT count(*)::int FROM documents) AS docs_total, | |
| 249 | − (SELECT count(*)::int FROM domains WHERE page_count > 0) AS domains_count, | |
| 250 | − (SELECT count(*)::int FROM documents | |
| 251 | − WHERE first_indexed_at >= $1 AND first_indexed_at < $2) AS indexed_cur, | |
| 252 | − (SELECT count(*)::int FROM documents WHERE first_indexed_at < $1) AS docs_before, | |
| 253 | − (SELECT count(*)::int FROM crawl_attempts | |
| 254 | − WHERE outcome = 'error' AND fetched_at >= $1 AND fetched_at < $2) AS errors_cur, | |
| 255 | − (SELECT count(*)::int FROM frontier_items WHERE status = 'pending') AS frontier_pending | |
| 364 | + # ---- Crawl : un passage borné, ventilé par (bucket, outcome) ---------- | |
| 365 | + oc_rows = await db.pool.fetch( | |
| 366 | + f""" | |
| 367 | + SELECT date_trunc('{unit_sql}', fetched_at AT TIME ZONE 'America/Toronto') AS b, | |
| 368 | + outcome, count(*)::int AS n, | |
| 369 | + coalesce(sum(bytes), 0)::bigint AS bytes, | |
| 370 | + max(bytes)::int AS bytes_max, | |
| 371 | + sum(duration_ms)::bigint AS dur_sum, | |
| 372 | + max(duration_ms)::int AS dur_max | |
| 373 | + FROM crawl_attempts | |
| 374 | + WHERE fetched_at >= $1 AND fetched_at < $2 | |
| 375 | + GROUP BY 1, 2 | |
| 376 | + """, | |
| 377 | + start, end, | |
| 378 | + ) | |
| 379 | + oc_map: dict[tuple, int] = {} | |
| 380 | + outcome_totals: dict[str, int] = {} | |
| 381 | + attempts_cur = errors_cur = indexed_ok_cur = 0 | |
| 382 | + bytes_sum = dur_sum = 0 | |
| 383 | + bytes_max = dur_max = 0 | |
| 384 | + for r in oc_rows: | |
| 385 | + oc_map[(r["b"], r["outcome"])] = r["n"] | |
| 386 | + outcome_totals[r["outcome"]] = outcome_totals.get(r["outcome"], 0) + r["n"] | |
| 387 | + attempts_cur += r["n"] | |
| 388 | + bytes_sum += r["bytes"] | |
| 389 | + dur_sum += r["dur_sum"] or 0 | |
| 390 | + bytes_max = max(bytes_max, r["bytes_max"] or 0) | |
| 391 | + dur_max = max(dur_max, r["dur_max"] or 0) | |
| 392 | + errors_cur = outcome_totals.get("error", 0) | |
| 393 | + indexed_ok_cur = outcome_totals.get("indexed", 0) | |
| 394 | + crawl_pts = [{"t": lab, "v": sum(oc_map.get((k, o), 0) for o in outcome_totals)} | |
| 395 | + for k, lab in zip(keys, klabels)] | |
| 396 | + err_pts = [{"t": lab, "v": oc_map.get((k, "error"), 0)} for k, lab in zip(keys, klabels)] | |
| 397 | + idx_ok_pts = [{"t": lab, "v": oc_map.get((k, "indexed"), 0)} for k, lab in zip(keys, klabels)] | |
| 398 | + | |
| 399 | + # ---- Crawl : classes de statut HTTP par bucket (empilées) ------------- | |
| 400 | + st_rows = await db.pool.fetch( | |
| 401 | + f""" | |
| 402 | + SELECT date_trunc('{unit_sql}', fetched_at AT TIME ZONE 'America/Toronto') AS b, | |
| 403 | + CASE WHEN status_code BETWEEN 200 AND 299 THEN '2xx' | |
| 404 | + WHEN status_code BETWEEN 300 AND 399 THEN '3xx' | |
| 405 | + WHEN status_code BETWEEN 400 AND 499 THEN '4xx' | |
| 406 | + WHEN status_code >= 500 THEN '5xx' | |
| 407 | + ELSE 'Sans réponse' END AS cls, | |
| 408 | + count(*)::int AS n | |
| 409 | + FROM crawl_attempts | |
| 410 | + WHERE fetched_at >= $1 AND fetched_at < $2 | |
| 411 | + GROUP BY 1, 2 | |
| 256 | 412 | """, |
| 257 | 413 | start, end, |
| 258 | 414 | ) |
| 259 | − prev = None | |
| 415 | + st_map = {(r["b"], r["cls"]): r["n"] for r in st_rows} | |
| 416 | + st_totals = {c: sum(n for (b, cls), n in st_map.items() if cls == c) for c in HTTP_CLASSES} | |
| 417 | + st_keys = [c for c in HTTP_CLASSES if st_totals.get(c)] | |
| 418 | + stacked_pts = [{"t": lab, "values": [st_map.get((k, c), 0) for c in st_keys]} | |
| 419 | + for k, lab in zip(keys, klabels)] | |
| 420 | + | |
| 421 | + # ---- Période précédente (bornée) --------------------------------------- | |
| 422 | + prev_oc: dict[str, int] = {} | |
| 423 | + attempts_prev = errors_prev = indexed_prev = searches_prev = bytes_prev = None | |
| 260 | 424 | if prev_start is not None: |
| 425 | + prows = await db.pool.fetch( | |
| 426 | + """ | |
| 427 | + SELECT outcome, count(*)::int AS n, coalesce(sum(bytes), 0)::bigint AS bytes | |
| 428 | + FROM crawl_attempts WHERE fetched_at >= $1 AND fetched_at < $2 | |
| 429 | + GROUP BY 1 | |
| 430 | + """, | |
| 431 | + prev_start, prev_end, | |
| 432 | + ) | |
| 433 | + prev_oc = {r["outcome"]: r["n"] for r in prows} | |
| 434 | + attempts_prev = sum(prev_oc.values()) | |
| 435 | + errors_prev = prev_oc.get("error", 0) | |
| 436 | + bytes_prev = sum(r["bytes"] for r in prows) | |
| 261 | 437 | prev = await db.pool.fetchrow( |
| 262 | 438 | """ |
| 263 | 439 | SELECT |
| 264 | 440 | (SELECT count(*)::int FROM documents |
| 265 | − WHERE first_indexed_at >= $1 AND first_indexed_at < $2) AS indexed_prev, | |
| 266 | − (SELECT count(*)::int FROM crawl_attempts | |
| 267 | − WHERE outcome = 'error' AND fetched_at >= $1 AND fetched_at < $2) AS errors_prev, | |
| 441 | + WHERE first_indexed_at >= $1 AND first_indexed_at < $2) AS indexed_prev, | |
| 268 | 442 | (SELECT count(*)::int FROM search_queries |
| 269 | − WHERE created_at >= $1 AND created_at < $2) AS searches_prev | |
| 443 | + WHERE created_at >= $1 AND created_at < $2) AS searches_prev | |
| 270 | 444 | """, |
| 271 | 445 | prev_start, prev_end, |
| 272 | 446 | ) |
| 447 | + indexed_prev = prev["indexed_prev"] | |
| 448 | + searches_prev = prev["searches_prev"] | |
| 449 | + | |
| 450 | + # ---- Index / domaines / frontier (compteurs indexés) ------------------- | |
| 451 | + cur = await db.pool.fetchrow( | |
| 452 | + """ | |
| 453 | + SELECT | |
| 454 | + (SELECT count(*)::int FROM domains WHERE page_count > 0) AS domains_count, | |
| 455 | + (SELECT count(*)::int FROM documents | |
| 456 | + WHERE first_indexed_at >= $1 AND first_indexed_at < $2) AS indexed_cur, | |
| 457 | + (SELECT count(*)::int FROM documents WHERE first_indexed_at < $1) AS docs_before, | |
| 458 | + (SELECT count(*)::int FROM frontier_items WHERE status = 'pending') AS frontier_pending | |
| 459 | + """, | |
| 460 | + start, end, | |
| 461 | + ) | |
| 462 | + prof = await _doc_profile(db) | |
| 463 | + docs_total = prof["total"] | |
| 464 | + indexed_cur = cur["indexed_cur"] | |
| 465 | + | |
| 466 | + # ---- Recherches --------------------------------------------------------- | |
| 273 | 467 | sq = await db.pool.fetchrow( |
| 274 | 468 | """ |
| 275 | 469 | SELECT count(*)::int AS n, |
| 276 | − round(avg((NOT zero_result)::int) * 100, 1)::float AS found_rate | |
| 470 | + round(avg((NOT zero_result)::int) * 100, 1)::float AS found_rate, | |
| 471 | + round(avg(took_ms))::int AS took_avg | |
| 277 | 472 | FROM search_queries WHERE created_at >= $1 AND created_at < $2 |
| 278 | 473 | """, |
| 279 | 474 | start, end, |
| 280 | 475 | ) |
| 281 | 476 | |
| 282 | − indexed_cur = cur["indexed_cur"] | |
| 283 | − indexed_prev = prev["indexed_prev"] if prev else None | |
| 284 | − errors_prev = prev["errors_prev"] if prev else None | |
| 285 | − searches_prev = prev["searches_prev"] if prev else None | |
| 477 | + # ---- Séries ------------------------------------------------------------- | |
| 478 | + per_bucket = await _bucket_counts(db, "documents", "first_indexed_at", start, end, bucket) | |
| 479 | + running = cur["docs_before"] | |
| 480 | + cum_points = [] | |
| 481 | + for p in per_bucket: | |
| 482 | + running += p["v"] | |
| 483 | + cum_points.append({"t": p["t"], "v": running}) | |
| 484 | + idx_compare = None | |
| 485 | + if prev_start is not None and bucket == "day": | |
| 486 | + idx_compare = await _bucket_counts( | |
| 487 | + db, "documents", "first_indexed_at", prev_start, prev_end, bucket | |
| 488 | + ) | |
| 489 | + | |
| 286 | 490 | growth = round(100.0 * indexed_cur / cur["docs_before"], 1) if cur["docs_before"] else None |
| 287 | − err_delta = _delta(cur["errors_cur"], errors_prev) | |
| 491 | + vol_val, vol_unit = _mb(bytes_sum) | |
| 288 | 492 | |
| 289 | 493 | kpis = [ |
| 290 | − {"id": "pages", "label": "Pages indexées (total)", "value": cur["docs_total"], | |
| 291 | − "delta_pct": growth, "direction": "up"}, | |
| 494 | + {"id": "pages", "label": "Pages indexées (total)", "value": docs_total, | |
| 495 | + "delta_pct": growth, "direction": "up", "spark": _spark(cum_points)}, | |
| 292 | 496 | {"id": "domaines", "label": "Domaines dans l'index", "value": cur["domains_count"]}, |
| 497 | + {"id": "crawlees", "label": f"Pages crawlées — {label}", "value": attempts_cur, | |
| 498 | + "delta_pct": _delta(attempts_cur, attempts_prev), "spark": _spark(crawl_pts)}, | |
| 499 | + {"id": "rythme", "label": "Rythme de crawl", "value": round(attempts_cur / hours, 1), | |
| 500 | + "unit": "pages/h", "delta_pct": _delta(attempts_cur, attempts_prev)}, | |
| 293 | 501 | {"id": "indexees", "label": f"Pages indexées — {label}", "value": indexed_cur, |
| 294 | − "delta_pct": _delta(indexed_cur, indexed_prev)}, | |
| 295 | − {"id": "rythme", "label": "Rythme d'indexation", "value": round(indexed_cur / hours, 1), | |
| 296 | − "unit": "pages/h", "delta_pct": _delta(indexed_cur, indexed_prev)}, | |
| 297 | − {"id": "erreurs", "label": f"Erreurs de crawl — {label}", "value": cur["errors_cur"], | |
| 298 | − "delta_pct": err_delta}, | |
| 502 | + "delta_pct": _delta(indexed_cur, indexed_prev), "spark": _spark(per_bucket)}, | |
| 503 | + {"id": "erreurs", "label": f"Erreurs de crawl — {label}", "value": errors_cur, | |
| 504 | + "delta_pct": _delta(errors_cur, errors_prev), "spark": _spark(err_pts)}, | |
| 299 | 505 | {"id": "frontier", "label": "Frontier en attente", "value": cur["frontier_pending"]}, |
| 300 | 506 | {"id": "recherches", "label": f"Recherches — {label}", "value": sq["n"], |
| 301 | 507 | "delta_pct": _delta(sq["n"], searches_prev)}, |
| 302 | 508 | ] |
| 303 | − if sq["n"]: | |
| 304 | − kpis.append({"id": "taux", "label": "Recherches avec résultats", "value": sq["found_rate"], | |
| 305 | − "unit": "%"}) | |
| 509 | + if bytes_sum: | |
| 510 | + kpis.append({"id": "volume", "label": f"Volume téléchargé — {label}", "value": vol_val, | |
| 511 | + "unit": vol_unit, "delta_pct": _delta(bytes_sum, bytes_prev)}) | |
| 512 | + if dur_sum and attempts_cur: | |
| 513 | + kpis.append({"id": "duree", "label": "Durée moyenne d'une tentative", | |
| 514 | + "value": int(round(dur_sum / attempts_cur)), "unit": "ms"}) | |
| 515 | + | |
| 516 | + # ---- Jauges ------------------------------------------------------------- | |
| 517 | + gauges = [] | |
| 518 | + if attempts_cur: | |
| 519 | + gauges.append({"id": "succes", "label": "Crawl sans erreur", | |
| 520 | + "value": round(100.0 * (attempts_cur - errors_cur) / attempts_cur, 1), | |
| 521 | + "max": 100, "unit": "%", | |
| 522 | + "help": "Part des tentatives de crawl qui ne finissent pas en erreur"}) | |
| 523 | + gauges.append({"id": "convert", "label": "Crawl menant à l'index", | |
| 524 | + "value": round(100.0 * indexed_ok_cur / attempts_cur, 1), | |
| 525 | + "max": 100, "unit": "%", | |
| 526 | + "help": "Part des tentatives dont l'issue est « indexée »"}) | |
| 527 | + if docs_total: | |
| 528 | + gauges.append({"id": "frais", "label": "Index frais (< 30 jours)", | |
| 529 | + "value": round(100.0 * prof["fresh30"] / docs_total, 1), | |
| 530 | + "max": 100, "unit": "%", | |
| 531 | + "help": "Pages re-visitées par le crawler dans les 30 derniers jours"}) | |
| 532 | + if sq["n"] and sq["found_rate"] is not None: | |
| 533 | + gauges.append({"id": "taux", "label": "Recherches avec résultats", | |
| 534 | + "value": sq["found_rate"], "max": 100, "unit": "%"}) | |
| 306 | 535 | |
| 307 | − # ---- Séries temporelles ---- | |
| 308 | − per_bucket = await _bucket_counts(db, "documents", "first_indexed_at", start, end, bucket) | |
| 309 | − err_bucket = await _bucket_counts( | |
| 310 | − db, "crawl_attempts", "fetched_at", start, end, bucket, "AND outcome = 'error'" | |
| 311 | − ) | |
| 312 | − unit_label = "par heure" if bucket == "hour" else "par jour" | |
| 313 | − running = cur["docs_before"] | |
| 314 | − cum_points = [] | |
| 315 | − for p in per_bucket: | |
| 316 | − running += p["v"] | |
| 317 | − cum_points.append({"t": p["t"], "v": running}) | |
| 318 | 536 | series = [ |
| 319 | − {"id": "cumul", "title": "Pages indexées — cumul", "unit": "pages", "kind": "line", | |
| 537 | + {"id": "cumul", "title": "Pages indexées — cumul", "unit": "pages", "kind": "area", | |
| 320 | 538 | "points": cum_points}, |
| 539 | + {"id": "crawlees", "title": f"Pages crawlées {unit_label}", "unit": "pages", "kind": "bar", | |
| 540 | + "points": crawl_pts}, | |
| 321 | 541 | {"id": "indexees", "title": f"Pages indexées {unit_label}", "unit": "pages", "kind": "line", |
| 322 | − "points": per_bucket}, | |
| 542 | + "points": per_bucket, **({"compare": idx_compare} if idx_compare else {})}, | |
| 323 | 543 | {"id": "erreurs", "title": f"Erreurs de crawl {unit_label}", "unit": "erreurs", "kind": "line", |
| 324 | − "points": err_bucket}, | |
| 544 | + "points": err_pts}, | |
| 325 | 545 | ] |
| 326 | 546 | if sq["n"]: |
| 327 | 547 | sq_bucket = await _bucket_counts(db, "search_queries", "created_at", start, end, bucket) |
| 328 | 548 | series.append({"id": "recherches", "title": f"Recherches {unit_label}", "unit": "recherches", |
| 329 | − "kind": "line", "points": sq_bucket}) | |
| 330 | − | |
| 331 | − # ---- Répartitions ---- | |
| 332 | − outcomes = await db.pool.fetch( | |
| 333 | − """ | |
| 334 | − SELECT outcome, count(*)::int AS n FROM crawl_attempts | |
| 335 | − WHERE fetched_at >= $1 AND fetched_at < $2 | |
| 336 | − GROUP BY outcome ORDER BY n DESC | |
| 337 | − """, | |
| 338 | − start, end, | |
| 339 | − ) | |
| 549 | + "kind": "bar", "points": sq_bucket}) | |
| 550 | + | |
| 551 | + multiseries = [{ | |
| 552 | + "id": "crawlmix", "title": f"Crawl {unit_label} : tentatives, indexées, erreurs", | |
| 553 | + "unit": "pages", | |
| 554 | + "series": [ | |
| 555 | + {"label": "Crawlées", "points": crawl_pts}, | |
| 556 | + {"label": "Indexées", "points": idx_ok_pts}, | |
| 557 | + {"label": "Erreurs", "points": err_pts}, | |
| 558 | + ], | |
| 559 | + }] | |
| 560 | + | |
| 561 | + stacked = [] | |
| 562 | + if st_keys: | |
| 563 | + stacked.append({"id": "http", "title": f"Crawl {unit_label} par classe de statut HTTP", | |
| 564 | + "unit": "pages", "keys": st_keys, "points": stacked_pts}) | |
| 565 | + | |
| 566 | + # ---- Répartitions ------------------------------------------------------- | |
| 340 | 567 | frontier = await db.pool.fetch( |
| 341 | 568 | "SELECT status, count(*)::int AS n FROM frontier_items GROUP BY status ORDER BY n DESC" |
| 342 | 569 | ) |
| 343 | 570 | top_domains = await db.pool.fetch( |
| 344 | 571 | """ |
| 345 | − SELECT domain, page_count, url_count, round(quebec_score::numeric, 2)::float AS qs | |
| 572 | + SELECT domain, page_count, url_count, round(quebec_score::numeric, 2)::float AS qs, | |
| 573 | + last_crawled_at | |
| 346 | 574 | FROM domains WHERE page_count > 0 |
| 347 | 575 | ORDER BY page_count DESC LIMIT 100 |
| 348 | 576 | """ |
| 349 | 577 | ) |
| 578 | + tld_items = await _tld_breakdown(db) | |
| 350 | 579 | breakdowns = [ |
| 351 | 580 | {"id": "outcomes", "title": f"Résultats de crawl — {label}", "kind": "donut", |
| 352 | − "items": [{"label": OUTCOME_LABELS.get(r["outcome"], r["outcome"]), "value": r["n"]} | |
| 353 | − for r in outcomes]}, | |
| 354 | − {"id": "topdom", "title": "Top domaines par pages indexées (tout l'index)", "kind": "bar", | |
| 581 | + "items": [{"label": OUTCOME_LABELS.get(o, o), "value": n, | |
| 582 | + **({"delta_pct": _delta(n, prev_oc.get(o))} if prev_oc else {})} | |
| 583 | + for o, n in sorted(outcome_totals.items(), key=lambda kv: -kv[1])]}, | |
| 584 | + {"id": "http", "title": f"Crawl par classe de statut HTTP — {label}", "kind": "bars", | |
| 585 | + "items": [{"label": c, "value": st_totals[c]} for c in st_keys]}, | |
| 586 | + {"id": "topdom", "title": "Top domaines par pages indexées (tout l'index)", "kind": "bars", | |
| 355 | 587 | "items": [{"label": r["domain"], "value": r["page_count"]} for r in top_domains[:12]]}, |
| 356 | 588 | {"id": "frontier", "title": "File frontier par statut", "kind": "donut", |
| 357 | 589 | "items": [{"label": FRONTIER_LABELS.get(r["status"], r["status"]), "value": r["n"]} |
| 358 | 590 | for r in frontier]}, |
| 359 | 591 | ] |
| 592 | + if tld_items: | |
| 593 | + breakdowns.insert(2, {"id": "tld", "title": "Pages indexées par TLD", "kind": "donut", | |
| 594 | + "items": tld_items}) | |
| 595 | + if prof["langs"]: | |
| 596 | + breakdowns.append({"id": "langues", "title": "Langue des pages indexées", "kind": "donut", | |
| 597 | + "items": prof["langs"][:8]}) | |
| 598 | + | |
| 599 | + # ---- Distributions ------------------------------------------------------ | |
| 600 | + distributions = [] | |
| 601 | + size_rows = await db.pool.fetch( | |
| 602 | + """ | |
| 603 | + SELECT width_bucket(bytes, 0, 512000, 16) AS wb, count(*)::int AS n | |
| 604 | + FROM crawl_attempts | |
| 605 | + WHERE fetched_at >= $1 AND fetched_at < $2 AND bytes IS NOT NULL AND bytes > 0 | |
| 606 | + GROUP BY 1 ORDER BY 1 | |
| 607 | + """, | |
| 608 | + start, end, | |
| 609 | + ) | |
| 610 | + if size_rows: | |
| 611 | + bins = [] | |
| 612 | + got = {r["wb"]: r["n"] for r in size_rows} | |
| 613 | + for i in range(1, 17): | |
| 614 | + bins.append({"label": f"{(i - 1) * 32}-{i * 32} Ko", "value": got.get(i, 0)}) | |
| 615 | + over = got.get(17, 0) | |
| 616 | + if over: | |
| 617 | + bins.append({"label": "> 512 Ko", "value": over}) | |
| 618 | + distributions.append({"id": "taille", "title": f"Distribution de la taille des pages — {label}", | |
| 619 | + "unit": "pages", "bins": bins}) | |
| 620 | + dur_rows = await db.pool.fetch( | |
| 621 | + """ | |
| 622 | + SELECT width_bucket(duration_ms, 0, 10000, 10) AS wb, count(*)::int AS n | |
| 623 | + FROM crawl_attempts | |
| 624 | + WHERE fetched_at >= $1 AND fetched_at < $2 AND duration_ms IS NOT NULL | |
| 625 | + GROUP BY 1 ORDER BY 1 | |
| 626 | + """, | |
| 627 | + start, end, | |
| 628 | + ) | |
| 629 | + if dur_rows: | |
| 630 | + got = {r["wb"]: r["n"] for r in dur_rows} | |
| 631 | + bins = [{"label": f"{i - 1}-{i} s", "value": got.get(i, 0)} for i in range(1, 11)] | |
| 632 | + over = got.get(11, 0) | |
| 633 | + if over: | |
| 634 | + bins.append({"label": "> 10 s", "value": over}) | |
| 635 | + distributions.append({"id": "duree", "title": f"Distribution de la durée des requêtes — {label}", | |
| 636 | + "unit": "pages", "bins": bins}) | |
| 637 | + depth_bins, deepest = await _frontier_depths(db) | |
| 638 | + if depth_bins: | |
| 639 | + distributions.append({"id": "profondeur", "title": "Profondeur des URLs de la frontier", | |
| 640 | + "unit": "URLs", "bins": depth_bins}) | |
| 641 | + | |
| 642 | + # ---- Heatmap horaire 7×24 (bornée à 56 jours max) ----------------------- | |
| 643 | + hh_start = max(start, end - timedelta(days=56)) | |
| 644 | + hh_rows = await db.pool.fetch( | |
| 645 | + """ | |
| 646 | + SELECT (extract(isodow FROM fetched_at AT TIME ZONE 'America/Toronto')::int - 1) AS dow, | |
| 647 | + extract(hour FROM fetched_at AT TIME ZONE 'America/Toronto')::int AS hr, | |
| 648 | + count(*)::int AS n | |
| 649 | + FROM crawl_attempts WHERE fetched_at >= $1 AND fetched_at < $2 | |
| 650 | + GROUP BY 1, 2 | |
| 651 | + """, | |
| 652 | + hh_start, end, | |
| 653 | + ) | |
| 654 | + hourly = None | |
| 655 | + if hh_rows: | |
| 656 | + hourly = {"title": "Pages crawlées par jour × heure", | |
| 657 | + "cells": [{"dow": r["dow"], "hour": r["hr"], "value": r["n"]} for r in hh_rows]} | |
| 360 | 658 | |
| 361 | − # ---- Tableaux ---- | |
| 659 | + # ---- Tableaux ----------------------------------------------------------- | |
| 362 | 660 | tables = [ |
| 363 | 661 | {"id": "topdom", "title": "Top domaines (tout l'index)", |
| 364 | − "columns": ["Domaine", "Pages indexées", "URLs connues", "Score Québec"], | |
| 365 | − "rows": [[r["domain"], r["page_count"], r["url_count"], r["qs"]] for r in top_domains]}, | |
| 662 | + "columns": ["Domaine", "Pages indexées", "URLs connues", "Score Québec", "Dernier crawl"], | |
| 663 | + "rows": [[r["domain"], r["page_count"], r["url_count"], r["qs"], | |
| 664 | + r["last_crawled_at"].astimezone(TZ).strftime("%Y-%m-%d %H:%M") | |
| 665 | + if r["last_crawled_at"] else "—"] for r in top_domains]}, | |
| 366 | 666 | ] |
| 667 | + top_q = [] | |
| 367 | 668 | if sq["n"]: |
| 368 | 669 | top_q = await db.pool.fetch( |
| 369 | 670 | """ |
@@ -380,6 +681,40 @@ async def _build(db, period: str, from_s: str | None, to_s: str | None) -> dict: | ||
| 380 | 681 | "rows": [[r["q"], r["n"], r["avg_res"], |
| 381 | 682 | r["last_at"].astimezone(TZ).strftime("%Y-%m-%d %H:%M")] for r in top_q], |
| 382 | 683 | }) |
| 684 | + zero_q = await db.pool.fetch( | |
| 685 | + """ | |
| 686 | + SELECT lower(query) AS q, count(*)::int AS n, max(created_at) AS last_at | |
| 687 | + FROM search_queries | |
| 688 | + WHERE zero_result AND created_at >= $1 AND created_at < $2 | |
| 689 | + GROUP BY 1 ORDER BY n DESC, last_at DESC LIMIT 30 | |
| 690 | + """, | |
| 691 | + start, end, | |
| 692 | + ) | |
| 693 | + if zero_q: | |
| 694 | + tables.append({ | |
| 695 | + "id": "zeroq", "title": f"Requêtes sans résultat — {label}", | |
| 696 | + "columns": ["Requête", "Tentatives", "Dernière fois"], | |
| 697 | + "rows": [[r["q"], r["n"], | |
| 698 | + r["last_at"].astimezone(TZ).strftime("%Y-%m-%d %H:%M")] for r in zero_q], | |
| 699 | + }) | |
| 700 | + err_dom = await db.pool.fetch( | |
| 701 | + """ | |
| 702 | + SELECT d.domain, count(*)::int AS n, max(a.fetched_at) AS last_at | |
| 703 | + FROM crawl_attempts a | |
| 704 | + JOIN urls u ON u.id = a.url_id | |
| 705 | + JOIN domains d ON d.id = u.domain_id | |
| 706 | + WHERE a.outcome = 'error' AND a.fetched_at >= $1 AND a.fetched_at < $2 | |
| 707 | + GROUP BY 1 ORDER BY n DESC LIMIT 30 | |
| 708 | + """, | |
| 709 | + start, end, | |
| 710 | + ) | |
| 711 | + if err_dom: | |
| 712 | + tables.append({ | |
| 713 | + "id": "errdom", "title": f"Erreurs de crawl par domaine — {label}", | |
| 714 | + "columns": ["Domaine", "Erreurs", "Dernière erreur"], | |
| 715 | + "rows": [[r["domain"], r["n"], | |
| 716 | + r["last_at"].astimezone(TZ).strftime("%Y-%m-%d %H:%M")] for r in err_dom], | |
| 717 | + }) | |
| 383 | 718 | err_types = await db.pool.fetch( |
| 384 | 719 | """ |
| 385 | 720 | SELECT coalesce(error_code, 'inconnu') AS code, count(*)::int AS n, max(fetched_at) AS last_at |
@@ -413,20 +748,40 @@ async def _build(db, period: str, from_s: str | None, to_s: str | None) -> dict: | ||
| 413 | 748 | r["code"], r["url"][:120]] for r in last_errors], |
| 414 | 749 | }) |
| 415 | 750 | |
| 416 | − # ---- Heatmap & records (réels, jamais inventés) ---- | |
| 751 | + # ---- Heatmap calendrier & records (réels, jamais inventés) -------------- | |
| 417 | 752 | cells = await _heatmap_cells(db) |
| 418 | 753 | records = [] |
| 419 | 754 | if cells: |
| 420 | 755 | best = max(cells, key=lambda c: c["value"]) |
| 421 | 756 | records.append({"label": "Jour record d'indexation", |
| 422 | 757 | "value": f"{_fr_int(best['value'])} pages", "date": best["date"]}) |
| 758 | + hr_rec = await _crawl_hour_record(db) | |
| 759 | + if hr_rec: | |
| 760 | + records.append({"label": "Heure record de crawl (30 derniers jours)", | |
| 761 | + "value": f"{_fr_int(hr_rec['n'])} pages", | |
| 762 | + "date": hr_rec["hour"].strftime("%Y-%m-%d %Hh")}) | |
| 423 | 763 | if top_domains: |
| 424 | 764 | records.append({"label": "Domaine le plus fourni", |
| 425 | 765 | "value": f"{top_domains[0]['domain']} — {_fr_int(top_domains[0]['page_count'])} pages"}) |
| 426 | − deepest = await _deepest_domain(db) | |
| 427 | 766 | if deepest: |
| 428 | 767 | records.append({"label": "Domaine exploré le plus profondément", |
| 429 | 768 | "value": f"{deepest['domain']} (profondeur {deepest['depth']})"}) |
| 769 | + if bytes_max: | |
| 770 | + bm_val, bm_unit = _mb(bytes_max) | |
| 771 | + records.append({"label": f"Page la plus lourde téléchargée — {label}", | |
| 772 | + "value": f"{str(bm_val).replace('.', ',')} {bm_unit}"}) | |
| 773 | + if dur_max: | |
| 774 | + records.append({"label": f"Plus longue tentative de crawl — {label}", | |
| 775 | + "value": f"{str(round(dur_max / 1000, 1)).replace('.', ',')} s"}) | |
| 776 | + if prof["avg_qs"] is not None: | |
| 777 | + records.append({"label": "Score Québec moyen des pages indexées", | |
| 778 | + "value": str(prof["avg_qs"]).replace(".", ",")}) | |
| 779 | + if top_q: | |
| 780 | + records.append({"label": f"Requête la plus fréquente — {label}", | |
| 781 | + "value": f"« {top_q[0]['q'][:40]} » — {_fr_int(top_q[0]['n'])} fois"}) | |
| 782 | + if sq["n"] and sq["took_avg"] is not None: | |
| 783 | + records.append({"label": f"Temps de réponse moyen des recherches — {label}", | |
| 784 | + "value": f"{_fr_int(sq['took_avg'])} ms"}) | |
| 430 | 785 | if sq["n"]: |
| 431 | 786 | best_sq = await db.pool.fetchrow( |
| 432 | 787 | """ |
@@ -439,14 +794,24 @@ async def _build(db, period: str, from_s: str | None, to_s: str | None) -> dict: | ||
| 439 | 794 | "value": f"{_fr_int(best_sq['n'])} recherches", |
| 440 | 795 | "date": best_sq["d"].isoformat()}) |
| 441 | 796 | |
| 442 | − return { | |
| 797 | + out = { | |
| 443 | 798 | "updated": now.isoformat(), |
| 444 | 799 | "period": {"from": start.astimezone(TZ).date().isoformat(), |
| 445 | 800 | "to": end.astimezone(TZ).date().isoformat(), "label": label}, |
| 446 | 801 | "kpis": kpis, |
| 447 | 802 | "series": series, |
| 803 | + "multiseries": multiseries, | |
| 448 | 804 | "breakdowns": breakdowns, |
| 449 | 805 | "heatmap": {"title": "Indexations par jour (26 dernières semaines)", "cells": cells}, |
| 450 | 806 | "tables": tables, |
| 451 | 807 | "records": records, |
| 452 | 808 | } |
| 809 | + if gauges: | |
| 810 | + out["gauges"] = gauges | |
| 811 | + if stacked: | |
| 812 | + out["stacked"] = stacked | |
| 813 | + if distributions: | |
| 814 | + out["distributions"] = distributions | |
| 815 | + if hourly: | |
| 816 | + out["hourly"] = hourly | |
| 817 | + return out | |
modified
apps/web/app/stats/stats-panel.tsx
+69 −19
@@ -1,7 +1,12 @@ | ||
| 1 | 1 | /** |
| 2 | − * Trouve-KA — panneau client /stats (kit ka-ui/stats, contrat SPEC.md) | |
| 2 | + * Trouve-KA — panneau client /stats (kit ka-ui/stats v2, contrat SPEC.md) | |
| 3 | 3 | * Author: Simon-Pierre Boucher |
| 4 | 4 | * Contact: contact@spboucher.ai |
| 5 | + * | |
| 6 | + * Ordre des sections (SPEC §1) : KPI → période → jauges → évolutions | |
| 7 | + * (séries + stats, multi-courbes, empilées) → répartitions → distributions → | |
| 8 | + * calendriers (heatmap 26 sem. + horaire 7×24) → tableaux → records → | |
| 9 | + * fraîcheur. PdfButton v2 = menu des 5 rapports. | |
| 5 | 10 | */ |
| 6 | 11 | |
| 7 | 12 | "use client"; |
@@ -14,31 +19,50 @@ import { | ||
| 14 | 19 | Donut, |
| 15 | 20 | EmptyBlock, |
| 16 | 21 | Fraicheur, |
| 22 | + GaugeCard, | |
| 23 | + Histogram, | |
| 24 | + HourHeatmap, | |
| 17 | 25 | KpiCard, |
| 18 | 26 | LineChart, |
| 27 | + MultiLineChart, | |
| 19 | 28 | PdfButton, |
| 20 | 29 | PeriodSelector, |
| 21 | 30 | RecordCard, |
| 31 | + StackedBarChart, | |
| 32 | + StatSummary, | |
| 22 | 33 | type BreakItem, |
| 34 | + type Distribution, | |
| 35 | + type Gauge, | |
| 36 | + type HourCell, | |
| 23 | 37 | type Kpi, |
| 38 | + type MultiSerie, | |
| 24 | 39 | type RecordFact, |
| 25 | 40 | type Serie, |
| 41 | + type StackedSerie, | |
| 26 | 42 | type TableSpec, |
| 27 | 43 | } from "@/ka/stats/kacharts"; |
| 28 | 44 | |
| 29 | −type Breakdown = { id: string; title: string; kind?: "donut" | "bar"; items: BreakItem[] }; | |
| 45 | +type Breakdown = { id: string; title: string; kind?: "donut" | "bar" | "bars"; items: BreakItem[] }; | |
| 30 | 46 | |
| 31 | 47 | type Dashboard = { |
| 32 | 48 | updated: string; |
| 33 | 49 | period: { from: string; to: string; label: string }; |
| 34 | 50 | kpis: Kpi[]; |
| 51 | + gauges?: Gauge[]; | |
| 35 | 52 | series: Serie[]; |
| 53 | + multiseries?: MultiSerie[]; | |
| 54 | + stacked?: StackedSerie[]; | |
| 36 | 55 | breakdowns: Breakdown[]; |
| 56 | + distributions?: Distribution[]; | |
| 37 | 57 | heatmap?: { title: string; cells: { date: string; value: number }[] }; |
| 58 | + hourly?: { title: string; cells: HourCell[] }; | |
| 38 | 59 | tables: TableSpec[]; |
| 39 | 60 | records: RecordFact[]; |
| 40 | 61 | }; |
| 41 | 62 | |
| 63 | +/** Les séries clés reçoivent un résumé min/max/moy/méd/σ sous la courbe. */ | |
| 64 | +const STAT_SERIES = new Set(["cumul", "crawlees", "indexees", "recherches"]); | |
| 65 | + | |
| 42 | 66 | export function StatsPanel() { |
| 43 | 67 | const [period, setPeriod] = useState("30j"); |
| 44 | 68 | const [custom, setCustom] = useState<{ from: string; to: string }>({ from: "", to: "" }); |
@@ -125,34 +149,46 @@ export function StatsPanel() { | ||
| 125 | 149 | |
| 126 | 150 | {data && ( |
| 127 | 151 | <div style={{ opacity: loading ? 0.55 : 1, transition: "opacity 0.15s" }}> |
| 128 | − {/* 1. Bandeau KPI */} | |
| 152 | + {/* 1. Bandeau KPI (+ sparklines) */} | |
| 129 | 153 | <section aria-label="Indicateurs clés" className="mt-6 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4"> |
| 130 | 154 | {data.kpis.map((k) => ( |
| 131 | 155 | <KpiCard key={k.id} k={k} /> |
| 132 | 156 | ))} |
| 133 | 157 | </section> |
| 134 | 158 | |
| 135 | − {/* 3. Courbes d'évolution */} | |
| 159 | + {/* 3. Jauges : taux & couvertures */} | |
| 160 | + {data.gauges && data.gauges.length > 0 && ( | |
| 161 | + <section aria-label="Taux et couvertures" className="mt-8 grid grid-cols-2 gap-3 md:grid-cols-4"> | |
| 162 | + {data.gauges.map((g) => ( | |
| 163 | + <GaugeCard key={g.id} g={g} /> | |
| 164 | + ))} | |
| 165 | + </section> | |
| 166 | + )} | |
| 167 | + | |
| 168 | + {/* 4. Évolutions : séries, multi-courbes, empilées */} | |
| 136 | 169 | <section aria-label="Évolution" className="mt-8 grid grid-cols-1 gap-4 xl:grid-cols-2"> |
| 137 | 170 | {data.series.map((s, i) => ( |
| 138 | 171 | <div key={s.id} className={i === 0 ? "xl:col-span-2" : undefined}> |
| 139 | − {s.kind === "bar" ? ( | |
| 140 | − <BarChart | |
| 141 | − title={s.title} | |
| 142 | − items={s.points.map((p) => ({ label: p.t, value: p.v }))} | |
| 143 | − unit={s.unit} | |
| 144 | − /> | |
| 145 | − ) : ( | |
| 146 | − <LineChart serie={s} /> | |
| 147 | − )} | |
| 172 | + <LineChart serie={s} /> | |
| 173 | + {STAT_SERIES.has(s.id) && <StatSummary serie={s} />} | |
| 174 | + </div> | |
| 175 | + ))} | |
| 176 | + {(data.multiseries ?? []).map((ms) => ( | |
| 177 | + <div key={ms.id} className="xl:col-span-2"> | |
| 178 | + <MultiLineChart ms={ms} /> | |
| 179 | + </div> | |
| 180 | + ))} | |
| 181 | + {(data.stacked ?? []).map((st) => ( | |
| 182 | + <div key={st.id} className="xl:col-span-2"> | |
| 183 | + <StackedBarChart st={st} /> | |
| 148 | 184 | </div> |
| 149 | 185 | ))} |
| 150 | 186 | </section> |
| 151 | 187 | |
| 152 | − {/* Répartitions */} | |
| 188 | + {/* 5. Répartitions */} | |
| 153 | 189 | <section aria-label="Répartitions" className="mt-8 grid grid-cols-1 gap-4 md:grid-cols-2"> |
| 154 | 190 | {data.breakdowns.map((b) => |
| 155 | − b.kind === "bar" ? ( | |
| 191 | + b.kind === "bar" || b.kind === "bars" ? ( | |
| 156 | 192 | <BarChart key={b.id} title={b.title} items={b.items} unit="pages" /> |
| 157 | 193 | ) : ( |
| 158 | 194 | <Donut key={b.id} title={b.title} items={b.items} /> |
@@ -160,14 +196,28 @@ export function StatsPanel() { | ||
| 160 | 196 | )} |
| 161 | 197 | </section> |
| 162 | 198 | |
| 163 | − {/* Calendrier de chaleur */} | |
| 199 | + {/* Distributions / histogrammes */} | |
| 200 | + {data.distributions && data.distributions.length > 0 && ( | |
| 201 | + <section aria-label="Distributions" className="mt-8 grid grid-cols-1 gap-4 xl:grid-cols-2"> | |
| 202 | + {data.distributions.map((d) => ( | |
| 203 | + <Histogram key={d.id} dist={d} /> | |
| 204 | + ))} | |
| 205 | + </section> | |
| 206 | + )} | |
| 207 | + | |
| 208 | + {/* 7. Calendriers : 26 semaines + activité horaire 7×24 */} | |
| 164 | 209 | {data.heatmap && ( |
| 165 | 210 | <section aria-label="Calendrier d'activité" className="mt-8"> |
| 166 | 211 | <CalendarHeatmap title={data.heatmap.title} cells={data.heatmap.cells} /> |
| 167 | 212 | </section> |
| 168 | 213 | )} |
| 214 | + {data.hourly && ( | |
| 215 | + <section aria-label="Activité horaire" className="mt-4"> | |
| 216 | + <HourHeatmap title={data.hourly.title} cells={data.hourly.cells} /> | |
| 217 | + </section> | |
| 218 | + )} | |
| 169 | 219 | |
| 170 | − {/* 5. Tableaux détaillés */} | |
| 220 | + {/* 8. Tableaux détaillés */} | |
| 171 | 221 | <section aria-label="Tableaux détaillés" className="mt-8 grid grid-cols-1 gap-4"> |
| 172 | 222 | {topQueries ? ( |
| 173 | 223 | <DataTable spec={topQueries} /> |
@@ -179,7 +229,7 @@ export function StatsPanel() { | ||
| 179 | 229 | ))} |
| 180 | 230 | </section> |
| 181 | 231 | |
| 182 | − {/* 6. Records & faits marquants */} | |
| 232 | + {/* 9. Records & faits marquants */} | |
| 183 | 233 | {data.records.length > 0 && ( |
| 184 | 234 | <section aria-label="Records et faits marquants" className="mt-8"> |
| 185 | 235 | <h2 className="text-lg font-bold tracking-[-0.02em] text-ink"> |
@@ -193,7 +243,7 @@ export function StatsPanel() { | ||
| 193 | 243 | </section> |
| 194 | 244 | )} |
| 195 | 245 | |
| 196 | − {/* 7. Fraîcheur (rappel en bas de page) */} | |
| 246 | + {/* 10. Fraîcheur (rappel en bas de page) */} | |
| 197 | 247 | <div className="mt-10"> |
| 198 | 248 | <Fraicheur updated={data.updated} onRefresh={() => void load()} /> |
| 199 | 249 | </div> |
modified
apps/web/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
apps/web/ka/stats/kacharts.tsx
+393 −31
@@ -1,24 +1,40 @@ | ||
| 1 | −"use client"; | |
| 2 | 1 | // Auteur : Simon-Pierre Boucher — contact@spboucher.ai |
| 3 | 2 | // ka-ui/stats/kacharts.tsx — kit de graphiques SVG du module Stats commun |
| 4 | 3 | // Groupe KA (zéro dépendance, React 18+). Style : design system ka-ui |
| 5 | 4 | // (bordures encre, accent de la plateforme via var(--accent)). |
| 6 | −// Composants : KpiCard, PeriodSelector, LineChart (infobulle + légende | |
| 7 | −// cliquable + comparaison N-1), BarChart, Donut, CalendarHeatmap, DataTable | |
| 8 | −// (tri/recherche/pagination), RecordCard, PdfButton, EmptyBlock, Fraicheur. | |
| 9 | −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"; | |
| 10 | 13 | |
| 11 | −/* ---------- types (contrat SPEC.md) ---------- */ | |
| 14 | +/* ---------- types (contrat SPEC.md v2) ---------- */ | |
| 12 | 15 | export type Kpi = { |
| 13 | 16 | id: string; label: string; value: number | string; unit?: string; |
| 14 | 17 | delta_pct?: number | null; direction?: "up" | "down"; |
| 18 | + spark?: Point[]; help?: string; | |
| 15 | 19 | }; |
| 16 | 20 | export type Point = { t: string; v: number }; |
| 17 | 21 | export type Serie = { |
| 18 | − id: string; title: string; unit?: string; kind?: "line" | "bar"; | |
| 22 | + id: string; title: string; unit?: string; | |
| 23 | + kind?: "line" | "bar" | "area"; | |
| 19 | 24 | points: Point[]; compare?: Point[]; |
| 20 | 25 | }; |
| 21 | −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 | |
| 22 | 38 | export type TableSpec = { id: string; title: string; columns: string[]; rows: (string | number)[][] }; |
| 23 | 39 | export type RecordFact = { label: string; value: string; date?: string }; |
| 24 | 40 | |
@@ -33,25 +49,63 @@ export const PERIODS: { id: string; label: string }[] = [ | ||
| 33 | 49 | { id: "tout", label: "Tout" }, |
| 34 | 50 | ]; |
| 35 | 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 | + | |
| 36 | 60 | export const fmtInt = (n: number) => n.toLocaleString("fr-CA"); |
| 37 | 61 | export const fmtNum = (n: number) => |
| 38 | 62 | Number.isInteger(n) ? fmtInt(n) : n.toLocaleString("fr-CA", { maximumFractionDigits: 2 }); |
| 63 | +const fmtPct = (n: number) => `${n >= 0 ? "+" : ""}${fmtNum(n)} %`; | |
| 39 | 64 | |
| 40 | −/* ---------- 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) ---------- */ | |
| 41 | 75 | export function KpiCard({ k }: { k: Kpi }) { |
| 42 | 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]); | |
| 43 | 89 | return ( |
| 44 | − <article className="card" style={{ padding: "14px 16px", minWidth: 0 }}> | |
| 90 | + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={k.help}> | |
| 45 | 91 | <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px,2.4vw,30px)", letterSpacing: "-0.02em" }}> |
| 46 | 92 | {typeof k.value === "number" ? fmtNum(k.value) : k.value} |
| 47 | 93 | {k.unit ? <span style={{ fontSize: "0.6em", color: "var(--ink-2)" }}> {k.unit}</span> : null} |
| 48 | 94 | </p> |
| 49 | 95 | <p className="klabel" style={{ margin: "6px 0 0" }}>{k.label}</p> |
| 50 | − {k.delta_pct !== undefined && k.delta_pct !== null && ( | |
| 51 | − <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}> | |
| 52 | − {up ? "▲" : "▼"} {k.delta_pct >= 0 ? "+" : ""}{fmtNum(k.delta_pct)} % <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span> | |
| 53 | − </p> | |
| 54 | − )} | |
| 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> | |
| 55 | 109 | </article> |
| 56 | 110 | ); |
| 57 | 111 | } |
@@ -85,12 +139,13 @@ export function PeriodSelector({ | ||
| 85 | 139 | ); |
| 86 | 140 | } |
| 87 | 141 | |
| 88 | −/* ---------- Courbe ---------- */ | |
| 142 | +/* ---------- Courbe / aire ---------- */ | |
| 89 | 143 | export function LineChart({ serie, height = 240 }: { serie: Serie; height?: number }) { |
| 90 | 144 | const [hide, setHide] = useState<{ cur: boolean; cmp: boolean }>({ cur: false, cmp: false }); |
| 91 | 145 | const [hover, setHover] = useState<number | null>(null); |
| 92 | 146 | const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26; |
| 93 | 147 | const pts = serie.points ?? []; |
| 148 | + if (serie.kind === "bar") return <VBarChart serie={serie} height={height} />; | |
| 94 | 149 | if (pts.length < 2) return <EmptyBlock title={serie.title} />; |
| 95 | 150 | const all = [...(hide.cur ? [] : pts), ...(!hide.cmp && serie.compare ? serie.compare : [])]; |
| 96 | 151 | const vmax = Math.max(...all.map((p) => p.v), 1); |
@@ -128,6 +183,9 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb | ||
| 128 | 183 | {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => ( |
| 129 | 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> |
| 130 | 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 | + )} | |
| 131 | 189 | {!hide.cmp && serie.compare && serie.compare.length > 1 && ( |
| 132 | 190 | <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" /> |
| 133 | 191 | )} |
@@ -149,17 +207,211 @@ export function LineChart({ serie, height = 240 }: { serie: Serie; height?: numb | ||
| 149 | 207 | ); |
| 150 | 208 | } |
| 151 | 209 | |
| 152 | −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 }) { | |
| 153 | 211 | return ( |
| 154 | − <button type="button" onClick={onClick} aria-pressed={!off} | |
| 155 | − 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 }}> | |
| 156 | 214 | <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} /> |
| 157 | 215 | {label} |
| 158 | 216 | </button> |
| 159 | 217 | ); |
| 160 | 218 | } |
| 161 | 219 | |
| 162 | −/* ---------- 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 ---------- */ | |
| 163 | 415 | export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) { |
| 164 | 416 | const rows = (items ?? []).slice(0, 14); |
| 165 | 417 | if (!rows.length) return <EmptyBlock title={title} />; |
@@ -170,9 +422,16 @@ export function BarChart({ title, items, unit }: { title: string; items: BreakIt | ||
| 170 | 422 | <div style={{ marginTop: 12, display: "grid", gap: 9 }}> |
| 171 | 423 | {rows.map((r) => ( |
| 172 | 424 | <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}> |
| 173 | − <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}> | |
| 425 | + <div style={{ display: "flex", justifyContent: "space-between", gap: 8, fontSize: 12.5 }}> | |
| 174 | 426 | <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span> |
| 175 | − <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> | |
| 176 | 435 | </div> |
| 177 | 436 | <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}> |
| 178 | 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" }} /> |
@@ -225,6 +484,26 @@ export function Donut({ title, items }: { title: string; items: BreakItem[] }) { | ||
| 225 | 484 | ); |
| 226 | 485 | } |
| 227 | 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 | + | |
| 228 | 507 | /* ---------- Calendrier de chaleur ---------- */ |
| 229 | 508 | export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) { |
| 230 | 509 | if (!cells?.length) return <EmptyBlock title={title} />; |
@@ -262,6 +541,64 @@ export function CalendarHeatmap({ title, cells }: { title: string; cells: { date | ||
| 262 | 541 | ); |
| 263 | 542 | } |
| 264 | 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 | + | |
| 265 | 602 | /* ---------- Tableau : tri, recherche, pagination ---------- */ |
| 266 | 603 | export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) { |
| 267 | 604 | const [q, setQ] = useState(""); |
@@ -339,9 +676,19 @@ export function RecordCard({ r }: { r: RecordFact }) { | ||
| 339 | 676 | ); |
| 340 | 677 | } |
| 341 | 678 | |
| 342 | −/* ---------- Bouton PDF ---------- */ | |
| 679 | +/* ---------- Menu de rapports PDF (5 rapports) ---------- */ | |
| 343 | 680 | export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) { |
| 344 | − 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]); | |
| 345 | 692 | const url = (mode: string) => { |
| 346 | 693 | const p = new URLSearchParams({ period, mode }); |
| 347 | 694 | if (from) p.set("from", from); |
@@ -349,23 +696,38 @@ export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: | ||
| 349 | 696 | return `${endpoint}?${p}`; |
| 350 | 697 | }; |
| 351 | 698 | const dl = (mode: string) => { |
| 352 | − setBusy(true); | |
| 699 | + setBusy(mode); | |
| 700 | + setOpen(false); | |
| 353 | 701 | const a = document.createElement("a"); |
| 354 | 702 | a.href = url(mode); |
| 355 | 703 | a.download = ""; |
| 356 | 704 | document.body.appendChild(a); |
| 357 | 705 | a.click(); |
| 358 | 706 | a.remove(); |
| 359 | − setTimeout(() => setBusy(false), 2500); | |
| 707 | + setTimeout(() => setBusy(null), 3000); | |
| 360 | 708 | }; |
| 361 | 709 | return ( |
| 362 | − <span style={{ display: "inline-flex", gap: 8, flexWrap: "wrap" }}> | |
| 363 | − <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={busy}> | |
| 364 | − {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"} | |
| 365 | 713 | </button> |
| 366 | − <button type="button" className="btn btn-ghost" onClick={() => dl("synthese")} disabled={busy}> | |
| 367 | − 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 ▾ | |
| 368 | 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 | + )} | |
| 369 | 731 | </span> |
| 370 | 732 | ); |
| 371 | 733 | } |
modified
apps/web/ka/stats/kapdf.py
+390 −71
@@ -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: | |
| 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,7 +111,9 @@ class _PDF(FPDF): | ||
| 95 | 111 | self.set_y(20) |
| 96 | 112 | |
| 97 | 113 | def footer(self): |
| 98 | − if self.cover_mode: | |
| 114 | + # page 1 = couverture (le flag cover_mode est déjà retombé quand | |
| 115 | + # add_page() clôt la page 1 → tester aussi le numéro de page) | |
| 116 | + if self.cover_mode or self.page_no() == 1: | |
| 99 | 117 | return |
| 100 | 118 | self.set_y(-15) |
| 101 | 119 | self.set_draw_color(*INK3) |
@@ -112,7 +130,7 @@ class GroupeKAReport: | ||
| 112 | 130 | def __init__(self, site: dict, dashboard: dict, mode: str = "complet"): |
| 113 | 131 | self.site = site |
| 114 | 132 | self.d = dashboard |
| 115 | − self.mode = mode | |
| 133 | + self.mode = mode if mode in REPORT_MODES else "complet" | |
| 116 | 134 | self.accent = _hex(site.get("accent", "#d9f26b")) |
| 117 | 135 | period = dashboard.get("period", {}) or {} |
| 118 | 136 | self.period_label = period.get("label") or "toute la période" |
@@ -127,6 +145,11 @@ class GroupeKAReport: | ||
| 127 | 145 | p.set_fill_color(*fill) |
| 128 | 146 | p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2) |
| 129 | 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 | + | |
| 130 | 153 | def _kicker(self, text): |
| 131 | 154 | p = self.pdf |
| 132 | 155 | p.set_font("helvetica", "B", 8) |
@@ -150,6 +173,14 @@ class GroupeKAReport: | ||
| 150 | 173 | self.toc.append((title, self.pdf.page_no())) |
| 151 | 174 | self.pdf.ln(11) |
| 152 | 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 | + | |
| 153 | 184 | # ---------- pages ---------- |
| 154 | 185 | def _cover(self): |
| 155 | 186 | p = self.pdf |
@@ -161,12 +192,10 @@ class GroupeKAReport: | ||
| 161 | 192 | p.set_draw_color(*INK) |
| 162 | 193 | p.set_line_width(1.0) |
| 163 | 194 | p.rect(10, 10, 190, 277) |
| 164 | − # kicker | |
| 165 | 195 | p.set_font("helvetica", "B", 10) |
| 166 | 196 | p.set_text_color(*GREEN) |
| 167 | 197 | p.set_xy(24, 34) |
| 168 | 198 | p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE") |
| 169 | − # wordmark : partie gauche + boîte encre/accent | |
| 170 | 199 | wm = self.site.get("wordmark", "") |
| 171 | 200 | left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None) |
| 172 | 201 | p.set_xy(24, 70) |
@@ -184,7 +213,7 @@ class GroupeKAReport: | ||
| 184 | 213 | p.set_xy(24, 100) |
| 185 | 214 | p.set_font("helvetica", "", 13) |
| 186 | 215 | p.set_text_color(*INK2) |
| 187 | − p.multi_cell(150, 7, f"Rapport statistique — {wm}") | |
| 216 | + p.multi_cell(150, 7, f"{REPORT_MODES[self.mode]} — {wm}") | |
| 188 | 217 | now = datetime.now(ZoneInfo("America/Toronto")) |
| 189 | 218 | per = self.d.get("period", {}) or {} |
| 190 | 219 | p.set_xy(24, 125) |
@@ -193,7 +222,7 @@ class GroupeKAReport: | ||
| 193 | 222 | ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")), |
| 194 | 223 | ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"), |
| 195 | 224 | ("Plateforme", "https://" + self.site.get("domain", "")), |
| 196 | − ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"), | |
| 225 | + ("Type de rapport", REPORT_MODES[self.mode]), | |
| 197 | 226 | ] |
| 198 | 227 | y = 128 |
| 199 | 228 | for k, v in rows: |
@@ -205,7 +234,6 @@ class GroupeKAReport: | ||
| 205 | 234 | p.cell(0, 6, str(v)) |
| 206 | 235 | p.set_font("helvetica", "", 10.5) |
| 207 | 236 | y += 8 |
| 208 | − # bande encre au pied | |
| 209 | 237 | p.set_fill_color(*INK) |
| 210 | 238 | p.rect(10, 262, 190, 25, style="F") |
| 211 | 239 | p.set_xy(24, 270) |
@@ -230,7 +258,7 @@ class GroupeKAReport: | ||
| 230 | 258 | p = self.pdf |
| 231 | 259 | cols, gw, gh, gap = 3, 56, 26, 3 |
| 232 | 260 | x0, y = p.l_margin, p.get_y() |
| 233 | − for i, k in enumerate(kpis[:9]): | |
| 261 | + for i, k in enumerate(kpis[:12]): | |
| 234 | 262 | x = x0 + (i % cols) * (gw + gap) |
| 235 | 263 | if i and i % cols == 0: |
| 236 | 264 | y += gh + gap |
@@ -252,20 +280,81 @@ class GroupeKAReport: | ||
| 252 | 280 | p.set_font("helvetica", "B", 8) |
| 253 | 281 | p.set_text_color(*(GREEN if up else DANGER)) |
| 254 | 282 | arrow = "+" if k["delta_pct"] >= 0 else "" |
| 255 | − 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.") | |
| 256 | 286 | p.set_y(y + gh + 8) |
| 257 | 287 | |
| 258 | − def _line_chart(self, s): | |
| 288 | + def _gauges(self): | |
| 289 | + gs = self.d.get("gauges") or [] | |
| 290 | + gs = [g for g in gs if isinstance(g.get("value"), (int, float)) and g.get("max")] | |
| 291 | + if not gs: | |
| 292 | + return | |
| 293 | + self._section_title("Taux & couvertures") | |
| 294 | + p = self.pdf | |
| 295 | + cols, gw, gh, gap = 3, 56, 34, 3 | |
| 296 | + x0, y = p.l_margin, p.get_y() | |
| 297 | + for i, g in enumerate(gs[:9]): | |
| 298 | + x = x0 + (i % cols) * (gw + gap) | |
| 299 | + if i and i % cols == 0: | |
| 300 | + y += gh + gap | |
| 301 | + if y > 240: | |
| 302 | + p.add_page(); y = p.get_y() | |
| 303 | + self._card(x, y, gw, gh) | |
| 304 | + frac = max(0.0, min(1.0, g["value"] / g["max"])) | |
| 305 | + cx, cy, r = x + gw / 2, y + 20, 14 | |
| 306 | + # arc de fond + arc de valeur (demi-cercle en petits segments) | |
| 307 | + for pass_col, pass_frac, lw in (((225, 223, 217), 1.0, 2.6), (self.accent, frac, 2.6)): | |
| 308 | + p.set_draw_color(*pass_col) | |
| 309 | + p.set_line_width(lw) | |
| 310 | + steps = max(2, int(60 * pass_frac)) | |
| 311 | + last = None | |
| 312 | + for st in range(steps + 1): | |
| 313 | + a = math.pi + math.pi * pass_frac * st / steps | |
| 314 | + pt = (cx + r * math.cos(a), cy + r * math.sin(a)) | |
| 315 | + if last: | |
| 316 | + p.line(last[0], last[1], pt[0], pt[1]) | |
| 317 | + last = pt | |
| 318 | + p.set_font("helvetica", "B", 11) | |
| 319 | + p.set_text_color(*INK) | |
| 320 | + p.set_xy(x + 4, cy - 5) | |
| 321 | + p.cell(gw - 8, 6, f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}", align="C") | |
| 322 | + p.set_font("helvetica", "", 6.6) | |
| 323 | + p.set_text_color(*INK3) | |
| 324 | + p.set_xy(x + 4, cy + 1.5) | |
| 325 | + p.cell(gw - 8, 4, f"{frac * 100:.0f} % de {_fr(g['max'])}", align="C") | |
| 326 | + p.set_xy(x + 3, y + gh - 7) | |
| 327 | + p.set_font("helvetica", "", 7) | |
| 328 | + p.set_text_color(*INK2) | |
| 329 | + p.multi_cell(gw - 6, 3.3, str(g.get("label", ""))[:60], align="C") | |
| 330 | + p.set_y(y + gh + 8) | |
| 331 | + | |
| 332 | + def _serie_stats_row(self, s): | |
| 333 | + """Ligne min/max/moyenne/médiane sous un graphique de série.""" | |
| 334 | + p = self.pdf | |
| 335 | + vs = [pt["v"] for pt in (s.get("points") or []) if isinstance(pt.get("v"), (int, float))] | |
| 336 | + if len(vs) < 2: | |
| 337 | + return | |
| 338 | + sv = sorted(vs) | |
| 339 | + mean = sum(vs) / len(vs) | |
| 340 | + med = sv[len(sv) // 2] | |
| 341 | + sd = math.sqrt(sum((v - mean) ** 2 for v in vs) / len(vs)) | |
| 342 | + p.set_font("helvetica", "", 6.8) | |
| 343 | + p.set_text_color(*INK3) | |
| 344 | + p.cell(0, 4, f"min {_fr(sv[0])} · max {_fr(sv[-1])} · moyenne {_fr(round(mean, 2))} · médiane {_fr(med)} · écart-type {_fr(round(sd, 2))}") | |
| 345 | + p.ln(5.5) | |
| 346 | + | |
| 347 | + def _line_chart(self, s, with_stats=False): | |
| 259 | 348 | p = self.pdf |
| 260 | 349 | pts = s.get("points") or [] |
| 261 | 350 | if len(pts) < 2: |
| 262 | 351 | return |
| 352 | + if s.get("kind") == "bar": | |
| 353 | + self._vbars(s) | |
| 354 | + return | |
| 263 | 355 | if p.get_y() > 200: |
| 264 | 356 | p.add_page() |
| 265 | − p.set_font("helvetica", "B", 10) | |
| 266 | − p.set_text_color(*INK) | |
| 267 | − p.cell(0, 6, s.get("title", "")) | |
| 268 | − p.ln(7) | |
| 357 | + self._chart_title(s.get("title", "")) | |
| 269 | 358 | x0, y0, w, h = p.l_margin, p.get_y(), 174, 52 |
| 270 | 359 | self._card(x0, y0, w, h, fill=WHITE) |
| 271 | 360 | cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16 |
@@ -273,7 +362,6 @@ class GroupeKAReport: | ||
| 273 | 362 | vmax = max(vals) or 1 |
| 274 | 363 | vmin = min(0, min(vals)) |
| 275 | 364 | rng = (vmax - vmin) or 1 |
| 276 | − # grille + graduations | |
| 277 | 365 | p.set_font("helvetica", "", 6.3) |
| 278 | 366 | p.set_text_color(*INK3) |
| 279 | 367 | p.set_draw_color(200, 200, 195) |
@@ -284,6 +372,20 @@ class GroupeKAReport: | ||
| 284 | 372 | p.set_xy(x0 + 1, gy - 1.6) |
| 285 | 373 | p.cell(10, 3, _fr(vmin + rng * g / 4), align="R") |
| 286 | 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 | + | |
| 287 | 389 | def draw(series, color, width, dash=None): |
| 288 | 390 | n = len(series) |
| 289 | 391 | p.set_draw_color(*color) |
@@ -292,8 +394,7 @@ class GroupeKAReport: | ||
| 292 | 394 | p.set_dash_pattern(dash=1.2, gap=1.2) |
| 293 | 395 | last = None |
| 294 | 396 | for i, pt in enumerate(series): |
| 295 | − px = cx + cw * (i / (n - 1)) | |
| 296 | − py = cy + ch - ch * ((pt["v"] - vmin) / rng) | |
| 397 | + px, py = xy(i, n, pt["v"]) | |
| 297 | 398 | if last: |
| 298 | 399 | p.line(last[0], last[1], px, py) |
| 299 | 400 | last = (px, py) |
@@ -302,7 +403,6 @@ class GroupeKAReport: | ||
| 302 | 403 | if s.get("compare"): |
| 303 | 404 | draw(s["compare"], INK3, 0.35, dash=True) |
| 304 | 405 | draw(pts, self.accent, 0.7) |
| 305 | − # libellés d'axe X (premier / milieu / dernier) | |
| 306 | 406 | p.set_text_color(*INK3) |
| 307 | 407 | for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)): |
| 308 | 408 | p.set_xy(cx + cw * frac - 9, cy + ch + 1.5) |
@@ -312,9 +412,166 @@ class GroupeKAReport: | ||
| 312 | 412 | p.set_font("helvetica", "", 6.8) |
| 313 | 413 | p.set_text_color(*INK3) |
| 314 | 414 | p.cell(0, 4, "— période courante (accent) · ---- période comparée") |
| 315 | − p.ln(6) | |
| 316 | − else: | |
| 317 | − 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) | |
| 318 | 575 | |
| 319 | 576 | def _bars(self, title, items, unit=""): |
| 320 | 577 | p = self.pdf |
@@ -324,10 +581,8 @@ class GroupeKAReport: | ||
| 324 | 581 | need = 10 + len(items) * 7 |
| 325 | 582 | if p.get_y() + need > 265: |
| 326 | 583 | p.add_page() |
| 327 | − p.set_font("helvetica", "B", 10) | |
| 328 | − p.set_text_color(*INK) | |
| 329 | − p.cell(0, 6, title) | |
| 330 | − p.ln(8) | |
| 584 | + self._chart_title(title) | |
| 585 | + p.ln(1) | |
| 331 | 586 | vmax = max(it["value"] for it in items) or 1 |
| 332 | 587 | for it in items: |
| 333 | 588 | y = p.get_y() |
@@ -335,19 +590,23 @@ class GroupeKAReport: | ||
| 335 | 590 | p.set_text_color(*INK) |
| 336 | 591 | p.set_x(p.l_margin) |
| 337 | 592 | p.cell(46, 5, str(it["label"])[:34]) |
| 338 | − bw = 96 * (it["value"] / vmax) | |
| 593 | + bw = 86 * (it["value"] / vmax) | |
| 339 | 594 | p.set_fill_color(*self.accent) |
| 340 | 595 | p.set_draw_color(*INK) |
| 341 | 596 | p.set_line_width(0.25) |
| 342 | 597 | p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF") |
| 343 | − p.set_xy(p.l_margin + 148, y) | |
| 598 | + p.set_xy(p.l_margin + 136, y) | |
| 344 | 599 | p.set_font("helvetica", "B", 7.6) |
| 345 | − 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") | |
| 346 | 606 | p.ln(6.4) |
| 347 | 607 | p.ln(3) |
| 348 | 608 | |
| 349 | 609 | def _donut(self, b): |
| 350 | − # anneau vectoriel simple (arcs) + légende | |
| 351 | 610 | p = self.pdf |
| 352 | 611 | items = [it for it in (b.get("items") or []) if it.get("value")][:8] |
| 353 | 612 | total = sum(it["value"] for it in items) |
@@ -355,17 +614,13 @@ class GroupeKAReport: | ||
| 355 | 614 | return |
| 356 | 615 | if p.get_y() > 210: |
| 357 | 616 | p.add_page() |
| 358 | − p.set_font("helvetica", "B", 10) | |
| 359 | − p.set_text_color(*INK) | |
| 360 | − p.cell(0, 6, b.get("title", "")) | |
| 361 | − p.ln(8) | |
| 617 | + self._chart_title(b.get("title", "")) | |
| 618 | + p.ln(1) | |
| 362 | 619 | cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20 |
| 363 | − shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10] | |
| 364 | 620 | start = -90.0 |
| 365 | 621 | for i, it in enumerate(items): |
| 366 | 622 | frac = it["value"] / total |
| 367 | − f = shades[i % len(shades)] | |
| 368 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 623 | + col = self._shade(i) | |
| 369 | 624 | steps = max(2, int(72 * frac)) |
| 370 | 625 | p.set_fill_color(*col) |
| 371 | 626 | p.set_draw_color(*col) |
@@ -384,11 +639,9 @@ class GroupeKAReport: | ||
| 384 | 639 | p.set_line_width(0.4) |
| 385 | 640 | p.ellipse(cx - 11, cy - 11, 22, 22, style="DF") |
| 386 | 641 | p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D") |
| 387 | − # légende | |
| 388 | 642 | ly = cy - 22 |
| 389 | 643 | for i, it in enumerate(items): |
| 390 | − f = shades[i % len(shades)] | |
| 391 | − col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) | |
| 644 | + col = self._shade(i) | |
| 392 | 645 | p.set_fill_color(*col) |
| 393 | 646 | p.set_draw_color(*INK) |
| 394 | 647 | p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF") |
@@ -400,7 +653,39 @@ class GroupeKAReport: | ||
| 400 | 653 | ly += 5.6 |
| 401 | 654 | p.set_y(max(cy + r, ly) + 6) |
| 402 | 655 | |
| 403 | − 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): | |
| 404 | 689 | p = self.pdf |
| 405 | 690 | cols = t.get("columns") or [] |
| 406 | 691 | rows = t.get("rows") or [] |
@@ -417,7 +702,7 @@ class GroupeKAReport: | ||
| 417 | 702 | p.ln(6) |
| 418 | 703 | head() |
| 419 | 704 | p.set_text_color(*INK) |
| 420 | − for i, row in enumerate(rows[:200]): | |
| 705 | + for i, row in enumerate(rows[:max_rows]): | |
| 421 | 706 | if p.get_y() > 262: |
| 422 | 707 | p.add_page() |
| 423 | 708 | head() |
@@ -428,10 +713,10 @@ class GroupeKAReport: | ||
| 428 | 713 | txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell) |
| 429 | 714 | p.cell(w, 5.4, " " + txt[:34], fill=True) |
| 430 | 715 | p.ln(5.4) |
| 431 | − if len(rows) > 200: | |
| 716 | + if len(rows) > max_rows: | |
| 432 | 717 | p.set_font("helvetica", "", 7) |
| 433 | 718 | p.set_text_color(*INK3) |
| 434 | − 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") | |
| 435 | 720 | p.ln(6) |
| 436 | 721 | |
| 437 | 722 | def _records(self): |
@@ -440,7 +725,7 @@ class GroupeKAReport: | ||
| 440 | 725 | return |
| 441 | 726 | self._section_title("Records & faits marquants") |
| 442 | 727 | p = self.pdf |
| 443 | − for r in recs[:10]: | |
| 728 | + for r in recs[:14]: | |
| 444 | 729 | if p.get_y() > 258: |
| 445 | 730 | p.add_page() |
| 446 | 731 | y = p.get_y() |
@@ -498,43 +783,76 @@ class GroupeKAReport: | ||
| 498 | 783 | "groupe-ka.com/conditions · /confidentialite · /loi-25.", |
| 499 | 784 | ) |
| 500 | 785 | |
| 501 | − def _toc_page(self): | |
| 502 | − # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en | |
| 503 | − # page 2 en réservant la page lors du build (voir build()). | |
| 504 | − 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() | |
| 505 | 807 | |
| 506 | 808 | def build(self) -> bytes: |
| 507 | 809 | p = self.pdf |
| 508 | 810 | p.alias_nb_pages() |
| 509 | 811 | self._cover() |
| 812 | + with_toc = self.mode in ("complet", "donnees") | |
| 813 | + toc_page_no = None | |
| 510 | 814 | if self.mode == "synthese": |
| 511 | 815 | p.add_page() |
| 512 | 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) | |
| 513 | 825 | self._records() |
| 514 | 826 | self._final_page() |
| 515 | − 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 | |
| 516 | 839 | p.add_page() |
| 517 | 840 | toc_page_no = p.page_no() |
| 518 | 841 | p.add_page() |
| 519 | 842 | self._kpis() |
| 520 | − for s in self.d.get("series") or []: | |
| 521 | − if s.get("kind") == "bar": | |
| 522 | − self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", "")) | |
| 523 | − else: | |
| 524 | − self._line_chart(s) | |
| 525 | − for b in self.d.get("breakdowns") or []: | |
| 526 | − if b.get("kind") == "donut": | |
| 527 | − self._donut(b) | |
| 528 | − else: | |
| 529 | − self._bars(b.get("title", ""), b.get("items")) | |
| 530 | − geo = self.d.get("geo") | |
| 531 | − if geo: | |
| 532 | − 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() | |
| 533 | 850 | for t in self.d.get("tables") or []: |
| 534 | 851 | self._table(t) |
| 535 | 852 | self._records() |
| 536 | 853 | self._final_page() |
| 537 | − # 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: | |
| 538 | 856 | last_page = p.page |
| 539 | 857 | p.page = toc_page_no |
| 540 | 858 | p.set_y(22) |
@@ -553,6 +871,7 @@ class GroupeKAReport: | ||
| 553 | 871 | return bytes(p.output()) |
| 554 | 872 | |
| 555 | 873 | |
| 556 | −def filename(platform_id: str, period: str) -> str: | |
| 874 | +def filename(platform_id: str, period: str, mode: str = "complet") -> str: | |
| 557 | 875 | today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d") |
| 558 | − 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
apps/web/public/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")); |
| 218 | 347 | |