Page /stats refaite : tableau de bord analytique ka-stats + rapport PDF Groupe-KA
- fabrika/statsdash.py : GET /api/stats/dashboard?period=… (contrat SPEC ka-stats) — KPI avec deltas reconstruits via first_seen, séries quotidiennes (nouveautés/jour, cumul), donut plateformes, top catégories, fourchettes de prix, géo par région, heatmap 26 semaines, tables (top boutiques, catégories), records ; cache 5 min. - fabrika/kapdf.py + GET /api/stats/report?period=&mode= : PDF GroupeKAReport (fpdf2, graphiques vectoriels), wordmark Fabri·Ka, accent #c4532e, modes complet/synthese, filename kapdf.filename. - frontend : /stats réécrite sur le kit ka/stats/kacharts.tsx (PdfButton, KPI, PeriodSelector avec plage personnalisée, LineChart/Donut/BarChart/Heatmap, DataTable, RecordCard, Fraicheur) — mobile 360/768/1440 sans débordement. - garde-fou : prix aberrants (> 500 000 $) exclus des moyennes et du record. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
7 changed files +2,144 −785
added
fabrika/kapdf.py
+558 −0
@@ -0,0 +1,558 @@ | ||
| 1 | +# Auteur : Simon-Pierre Boucher — contact@spboucher.ai | |
| 2 | +# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2). | |
| 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. | |
| 6 | +# Usage : | |
| 7 | +# from kapdf import GroupeKAReport | |
| 8 | +# pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00", | |
| 9 | +# "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json, | |
| 10 | +# mode="complet").build() | |
| 11 | +# Dépendance : pip install fpdf2 (aucune autre) | |
| 12 | +from __future__ import annotations | |
| 13 | + | |
| 14 | +import math | |
| 15 | +from datetime import datetime | |
| 16 | +from zoneinfo import ZoneInfo | |
| 17 | + | |
| 18 | +from fpdf import FPDF | |
| 19 | + | |
| 20 | +INK = (20, 24, 20) | |
| 21 | +INK2 = (77, 85, 81) | |
| 22 | +INK3 = (139, 146, 140) | |
| 23 | +PAPER = (245, 243, 238) | |
| 24 | +SURFACE2 = (250, 249, 245) | |
| 25 | +GREEN = (28, 92, 65) | |
| 26 | +DANGER = (179, 66, 58) | |
| 27 | +WHITE = (255, 255, 255) | |
| 28 | + | |
| 29 | +EMAILS = [ | |
| 30 | + ("contact@groupe-ka.com", "Projets, partenariats & données"), | |
| 31 | + ("info@groupe-ka.com", "Médias & questions générales"), | |
| 32 | + ("admin@groupe-ka.com", "Légal, vie privée & Loi 25"), | |
| 33 | +] | |
| 34 | +DISCLAIMER = ( | |
| 35 | + "Groupe KA est un agrégateur de contenu : nous ne vendons rien, ne louons " | |
| 36 | + "rien et ne sommes partie à aucune transaction. Données lues à la source, " | |
| 37 | + "rien d'inventé, tout est traçable." | |
| 38 | +) | |
| 39 | + | |
| 40 | + | |
| 41 | +def _hex(c: str) -> tuple[int, int, int]: | |
| 42 | + c = c.lstrip("#") | |
| 43 | + return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore | |
| 44 | + | |
| 45 | + | |
| 46 | +def _fr(n) -> str: | |
| 47 | + if isinstance(n, float) and not n.is_integer(): | |
| 48 | + return f"{n:,.2f}".replace(",", " ").replace(".", ",") | |
| 49 | + return f"{int(n):,}".replace(",", " ") | |
| 50 | + | |
| 51 | + | |
| 52 | +_SUBST = { | |
| 53 | + "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-", | |
| 54 | + "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"', | |
| 55 | + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", | |
| 56 | +} | |
| 57 | + | |
| 58 | + | |
| 59 | +def _latin1(s: str) -> str: | |
| 60 | + for k, v in _SUBST.items(): | |
| 61 | + s = s.replace(k, v) | |
| 62 | + return s.encode("latin-1", "replace").decode("latin-1") | |
| 63 | + | |
| 64 | + | |
| 65 | +class _PDF(FPDF): | |
| 66 | + """FPDF avec en-tête/pied Groupe-KA sur chaque page (sauf couverture). | |
| 67 | + Les polices core sont latin-1 : normalize_text sanitise en amont.""" | |
| 68 | + | |
| 69 | + def normalize_text(self, text): | |
| 70 | + return super().normalize_text(_latin1(text)) | |
| 71 | + | |
| 72 | + def __init__(self, brand: str, accent: tuple, period_label: str): | |
| 73 | + super().__init__(orientation="P", unit="mm", format="A4") | |
| 74 | + self.brand = brand | |
| 75 | + self.accent = accent | |
| 76 | + self.period_label = period_label | |
| 77 | + self.cover_mode = False | |
| 78 | + self.set_margins(18, 20, 18) | |
| 79 | + self.set_auto_page_break(True, margin=22) | |
| 80 | + | |
| 81 | + def header(self): | |
| 82 | + if self.cover_mode: | |
| 83 | + return | |
| 84 | + self.set_font("helvetica", "B", 8.5) | |
| 85 | + self.set_text_color(*INK) | |
| 86 | + self.set_xy(18, 9) | |
| 87 | + self.cell(0, 5, f"Groupe KA · {self.brand}") | |
| 88 | + self.set_font("helvetica", "", 8) | |
| 89 | + self.set_text_color(*INK3) | |
| 90 | + self.set_xy(18, 9) | |
| 91 | + self.cell(0, 5, "Rapport statistique", align="R") | |
| 92 | + self.set_draw_color(*INK) | |
| 93 | + self.set_line_width(0.5) | |
| 94 | + self.line(18, 15.5, 192, 15.5) | |
| 95 | + self.set_y(20) | |
| 96 | + | |
| 97 | + def footer(self): | |
| 98 | + if self.cover_mode: | |
| 99 | + return | |
| 100 | + self.set_y(-15) | |
| 101 | + self.set_draw_color(*INK3) | |
| 102 | + self.set_line_width(0.2) | |
| 103 | + self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5) | |
| 104 | + self.set_font("helvetica", "", 7.5) | |
| 105 | + self.set_text_color(*INK3) | |
| 106 | + year = datetime.now(ZoneInfo("America/Toronto")).year | |
| 107 | + self.cell(130, 5, f"© Groupe-KA — {year} — groupe-ka.com · {self.period_label}") | |
| 108 | + self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R") | |
| 109 | + | |
| 110 | + | |
| 111 | +class GroupeKAReport: | |
| 112 | + def __init__(self, site: dict, dashboard: dict, mode: str = "complet"): | |
| 113 | + self.site = site | |
| 114 | + self.d = dashboard | |
| 115 | + self.mode = mode | |
| 116 | + self.accent = _hex(site.get("accent", "#d9f26b")) | |
| 117 | + period = dashboard.get("period", {}) or {} | |
| 118 | + self.period_label = period.get("label") or "toute la période" | |
| 119 | + self.pdf = _PDF(site.get("wordmark", ""), self.accent, self.period_label) | |
| 120 | + self.toc: list[tuple[str, int]] = [] | |
| 121 | + | |
| 122 | + # ---------- primitives ---------- | |
| 123 | + def _card(self, x, y, w, h, fill=WHITE): | |
| 124 | + p = self.pdf | |
| 125 | + p.set_draw_color(*INK) | |
| 126 | + p.set_line_width(0.45) | |
| 127 | + p.set_fill_color(*fill) | |
| 128 | + p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2) | |
| 129 | + | |
| 130 | + def _kicker(self, text): | |
| 131 | + p = self.pdf | |
| 132 | + p.set_font("helvetica", "B", 8) | |
| 133 | + p.set_text_color(*GREEN) | |
| 134 | + p.set_draw_color(*GREEN) | |
| 135 | + p.set_line_width(0.6) | |
| 136 | + y = p.get_y() + 2 | |
| 137 | + p.line(p.l_margin, y, p.l_margin + 7, y) | |
| 138 | + p.set_xy(p.l_margin + 9, y - 2.5) | |
| 139 | + p.cell(0, 5, text.upper()) | |
| 140 | + p.ln(8) | |
| 141 | + | |
| 142 | + def _section_title(self, title): | |
| 143 | + if self.pdf.get_y() > 240: | |
| 144 | + self.pdf.add_page() | |
| 145 | + self._kicker("Groupe KA · " + self.site.get("wordmark", "")) | |
| 146 | + self.pdf.set_font("helvetica", "B", 15) | |
| 147 | + self.pdf.set_text_color(*INK) | |
| 148 | + self.pdf.set_x(self.pdf.l_margin) | |
| 149 | + self.pdf.cell(0, 8, title) | |
| 150 | + self.toc.append((title, self.pdf.page_no())) | |
| 151 | + self.pdf.ln(11) | |
| 152 | + | |
| 153 | + # ---------- pages ---------- | |
| 154 | + def _cover(self): | |
| 155 | + p = self.pdf | |
| 156 | + p.cover_mode = True | |
| 157 | + p.set_auto_page_break(False) | |
| 158 | + p.add_page() | |
| 159 | + p.set_fill_color(*PAPER) | |
| 160 | + p.rect(0, 0, 210, 297, style="F") | |
| 161 | + p.set_draw_color(*INK) | |
| 162 | + p.set_line_width(1.0) | |
| 163 | + p.rect(10, 10, 190, 277) | |
| 164 | + # kicker | |
| 165 | + p.set_font("helvetica", "B", 10) | |
| 166 | + p.set_text_color(*GREEN) | |
| 167 | + p.set_xy(24, 34) | |
| 168 | + p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE") | |
| 169 | + # wordmark : partie gauche + boîte encre/accent | |
| 170 | + wm = self.site.get("wordmark", "") | |
| 171 | + left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None) | |
| 172 | + p.set_xy(24, 70) | |
| 173 | + p.set_font("helvetica", "B", 40) | |
| 174 | + p.set_text_color(*INK) | |
| 175 | + p.cell(p.get_string_width(left) + 2, 20, left) | |
| 176 | + if boxed: | |
| 177 | + bw = p.get_string_width(boxed) + 12 | |
| 178 | + x = p.get_x() + 2 | |
| 179 | + p.set_fill_color(*INK) | |
| 180 | + p.rect(x, 68, bw, 22, style="F", round_corners=True, corner_radius=3) | |
| 181 | + p.set_text_color(*self.accent) | |
| 182 | + p.set_xy(x + 6, 70) | |
| 183 | + p.cell(bw - 12, 18, boxed) | |
| 184 | + p.set_xy(24, 100) | |
| 185 | + p.set_font("helvetica", "", 13) | |
| 186 | + p.set_text_color(*INK2) | |
| 187 | + p.multi_cell(150, 7, f"Rapport statistique — {wm}") | |
| 188 | + now = datetime.now(ZoneInfo("America/Toronto")) | |
| 189 | + per = self.d.get("period", {}) or {} | |
| 190 | + p.set_xy(24, 125) | |
| 191 | + p.set_font("helvetica", "", 10.5) | |
| 192 | + rows = [ | |
| 193 | + ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")), | |
| 194 | + ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"), | |
| 195 | + ("Plateforme", "https://" + self.site.get("domain", "")), | |
| 196 | + ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"), | |
| 197 | + ] | |
| 198 | + y = 128 | |
| 199 | + for k, v in rows: | |
| 200 | + p.set_xy(24, y) | |
| 201 | + p.set_text_color(*INK3) | |
| 202 | + p.cell(40, 6, k) | |
| 203 | + p.set_text_color(*INK) | |
| 204 | + p.set_font("helvetica", "B", 10.5) | |
| 205 | + p.cell(0, 6, str(v)) | |
| 206 | + p.set_font("helvetica", "", 10.5) | |
| 207 | + y += 8 | |
| 208 | + # bande encre au pied | |
| 209 | + p.set_fill_color(*INK) | |
| 210 | + p.rect(10, 262, 190, 25, style="F") | |
| 211 | + p.set_xy(24, 270) | |
| 212 | + p.set_font("helvetica", "B", 12) | |
| 213 | + p.set_text_color(*WHITE) | |
| 214 | + p.cell(60, 8, "par Groupe ") | |
| 215 | + p.set_text_color(*self.accent) | |
| 216 | + p.set_xy(24 + p.get_string_width("par Groupe ") + 1, 270) | |
| 217 | + p.cell(20, 8, "KA") | |
| 218 | + p.set_font("helvetica", "B", 10) | |
| 219 | + p.set_xy(24, 270) | |
| 220 | + p.set_text_color(*self.accent) | |
| 221 | + p.cell(162, 8, "groupe-ka.com", align="R") | |
| 222 | + p.set_auto_page_break(True, margin=22) | |
| 223 | + p.cover_mode = False | |
| 224 | + | |
| 225 | + def _kpis(self): | |
| 226 | + kpis = self.d.get("kpis") or [] | |
| 227 | + if not kpis: | |
| 228 | + return | |
| 229 | + self._section_title("Synthèse des indicateurs") | |
| 230 | + p = self.pdf | |
| 231 | + cols, gw, gh, gap = 3, 56, 26, 3 | |
| 232 | + x0, y = p.l_margin, p.get_y() | |
| 233 | + for i, k in enumerate(kpis[:9]): | |
| 234 | + x = x0 + (i % cols) * (gw + gap) | |
| 235 | + if i and i % cols == 0: | |
| 236 | + y += gh + gap | |
| 237 | + if y > 250: | |
| 238 | + p.add_page(); y = p.get_y() | |
| 239 | + self._card(x, y, gw, gh) | |
| 240 | + p.set_xy(x + 4, y + 4) | |
| 241 | + p.set_font("helvetica", "B", 14) | |
| 242 | + p.set_text_color(*INK) | |
| 243 | + val = k.get("value") | |
| 244 | + p.cell(gw - 8, 7, (_fr(val) if isinstance(val, (int, float)) else str(val)) + (" " + k["unit"] if k.get("unit") else "")) | |
| 245 | + p.set_xy(x + 4, y + 12) | |
| 246 | + p.set_font("helvetica", "", 7.6) | |
| 247 | + p.set_text_color(*INK2) | |
| 248 | + p.multi_cell(gw - 8, 3.6, str(k.get("label", ""))[:70]) | |
| 249 | + if k.get("delta_pct") is not None: | |
| 250 | + up = (k.get("direction") or ("up" if k["delta_pct"] >= 0 else "down")) == "up" | |
| 251 | + p.set_xy(x + 4, y + gh - 6.5) | |
| 252 | + p.set_font("helvetica", "B", 8) | |
| 253 | + p.set_text_color(*(GREEN if up else DANGER)) | |
| 254 | + 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.") | |
| 256 | + p.set_y(y + gh + 8) | |
| 257 | + | |
| 258 | + def _line_chart(self, s): | |
| 259 | + p = self.pdf | |
| 260 | + pts = s.get("points") or [] | |
| 261 | + if len(pts) < 2: | |
| 262 | + return | |
| 263 | + if p.get_y() > 200: | |
| 264 | + 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) | |
| 269 | + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52 | |
| 270 | + self._card(x0, y0, w, h, fill=WHITE) | |
| 271 | + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16 | |
| 272 | + vals = [pt["v"] for pt in pts] + [c["v"] for c in (s.get("compare") or [])] | |
| 273 | + vmax = max(vals) or 1 | |
| 274 | + vmin = min(0, min(vals)) | |
| 275 | + rng = (vmax - vmin) or 1 | |
| 276 | + # grille + graduations | |
| 277 | + p.set_font("helvetica", "", 6.3) | |
| 278 | + p.set_text_color(*INK3) | |
| 279 | + p.set_draw_color(200, 200, 195) | |
| 280 | + p.set_line_width(0.15) | |
| 281 | + for g in range(5): | |
| 282 | + gy = cy + ch - ch * g / 4 | |
| 283 | + p.line(cx, gy, cx + cw, gy) | |
| 284 | + p.set_xy(x0 + 1, gy - 1.6) | |
| 285 | + p.cell(10, 3, _fr(vmin + rng * g / 4), align="R") | |
| 286 | + | |
| 287 | + def draw(series, color, width, dash=None): | |
| 288 | + n = len(series) | |
| 289 | + p.set_draw_color(*color) | |
| 290 | + p.set_line_width(width) | |
| 291 | + if dash: | |
| 292 | + p.set_dash_pattern(dash=1.2, gap=1.2) | |
| 293 | + last = None | |
| 294 | + for i, pt in enumerate(series): | |
| 295 | + px = cx + cw * (i / (n - 1)) | |
| 296 | + py = cy + ch - ch * ((pt["v"] - vmin) / rng) | |
| 297 | + if last: | |
| 298 | + p.line(last[0], last[1], px, py) | |
| 299 | + last = (px, py) | |
| 300 | + p.set_dash_pattern() | |
| 301 | + | |
| 302 | + if s.get("compare"): | |
| 303 | + draw(s["compare"], INK3, 0.35, dash=True) | |
| 304 | + draw(pts, self.accent, 0.7) | |
| 305 | + # libellés d'axe X (premier / milieu / dernier) | |
| 306 | + p.set_text_color(*INK3) | |
| 307 | + for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)): | |
| 308 | + p.set_xy(cx + cw * frac - 9, cy + ch + 1.5) | |
| 309 | + p.cell(18, 3, str(pts[idx].get("t", ""))[:10], align="C") | |
| 310 | + p.set_y(y0 + h + 4) | |
| 311 | + if s.get("compare"): | |
| 312 | + p.set_font("helvetica", "", 6.8) | |
| 313 | + p.set_text_color(*INK3) | |
| 314 | + p.cell(0, 4, "— période courante (accent) · ---- période comparée") | |
| 315 | + p.ln(6) | |
| 316 | + else: | |
| 317 | + p.ln(2) | |
| 318 | + | |
| 319 | + def _bars(self, title, items, unit=""): | |
| 320 | + p = self.pdf | |
| 321 | + items = [it for it in (items or []) if isinstance(it.get("value"), (int, float))][:12] | |
| 322 | + if not items: | |
| 323 | + return | |
| 324 | + need = 10 + len(items) * 7 | |
| 325 | + if p.get_y() + need > 265: | |
| 326 | + 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) | |
| 331 | + vmax = max(it["value"] for it in items) or 1 | |
| 332 | + for it in items: | |
| 333 | + y = p.get_y() | |
| 334 | + p.set_font("helvetica", "", 7.6) | |
| 335 | + p.set_text_color(*INK) | |
| 336 | + p.set_x(p.l_margin) | |
| 337 | + p.cell(46, 5, str(it["label"])[:34]) | |
| 338 | + bw = 96 * (it["value"] / vmax) | |
| 339 | + p.set_fill_color(*self.accent) | |
| 340 | + p.set_draw_color(*INK) | |
| 341 | + p.set_line_width(0.25) | |
| 342 | + 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) | |
| 344 | + p.set_font("helvetica", "B", 7.6) | |
| 345 | + p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R") | |
| 346 | + p.ln(6.4) | |
| 347 | + p.ln(3) | |
| 348 | + | |
| 349 | + def _donut(self, b): | |
| 350 | + # anneau vectoriel simple (arcs) + légende | |
| 351 | + p = self.pdf | |
| 352 | + items = [it for it in (b.get("items") or []) if it.get("value")][:8] | |
| 353 | + total = sum(it["value"] for it in items) | |
| 354 | + if not items or not total: | |
| 355 | + return | |
| 356 | + if p.get_y() > 210: | |
| 357 | + 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) | |
| 362 | + 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 | + start = -90.0 | |
| 365 | + for i, it in enumerate(items): | |
| 366 | + 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)) | |
| 369 | + steps = max(2, int(72 * frac)) | |
| 370 | + p.set_fill_color(*col) | |
| 371 | + p.set_draw_color(*col) | |
| 372 | + for st in range(steps): | |
| 373 | + a0 = math.radians(start + 360 * frac * st / steps) | |
| 374 | + a1 = math.radians(start + 360 * frac * (st + 1) / steps) | |
| 375 | + p.polygon( | |
| 376 | + [(cx, cy), | |
| 377 | + (cx + r * math.cos(a0), cy + r * math.sin(a0)), | |
| 378 | + (cx + r * math.cos(a1), cy + r * math.sin(a1))], | |
| 379 | + style="DF", | |
| 380 | + ) | |
| 381 | + start += 360 * frac | |
| 382 | + p.set_fill_color(*WHITE) | |
| 383 | + p.set_draw_color(*INK) | |
| 384 | + p.set_line_width(0.4) | |
| 385 | + p.ellipse(cx - 11, cy - 11, 22, 22, style="DF") | |
| 386 | + p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D") | |
| 387 | + # légende | |
| 388 | + ly = cy - 22 | |
| 389 | + 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)) | |
| 392 | + p.set_fill_color(*col) | |
| 393 | + p.set_draw_color(*INK) | |
| 394 | + p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF") | |
| 395 | + p.set_xy(p.l_margin + 66, ly) | |
| 396 | + p.set_font("helvetica", "", 7.6) | |
| 397 | + p.set_text_color(*INK) | |
| 398 | + pct = 100 * it["value"] / total | |
| 399 | + p.cell(0, 5.6, f"{str(it['label'])[:40]} — {_fr(it['value'])} ({pct:.1f} %)".replace(".", ",")) | |
| 400 | + ly += 5.6 | |
| 401 | + p.set_y(max(cy + r, ly) + 6) | |
| 402 | + | |
| 403 | + def _table(self, t): | |
| 404 | + p = self.pdf | |
| 405 | + cols = t.get("columns") or [] | |
| 406 | + rows = t.get("rows") or [] | |
| 407 | + if not cols or not rows: | |
| 408 | + return | |
| 409 | + self._section_title(t.get("title", "Tableau")) | |
| 410 | + w = 174 / len(cols) | |
| 411 | + def head(): | |
| 412 | + p.set_font("helvetica", "B", 7.6) | |
| 413 | + p.set_fill_color(*INK) | |
| 414 | + p.set_text_color(*WHITE) | |
| 415 | + for c in cols: | |
| 416 | + p.cell(w, 6, " " + str(c)[:30], fill=True) | |
| 417 | + p.ln(6) | |
| 418 | + head() | |
| 419 | + p.set_text_color(*INK) | |
| 420 | + for i, row in enumerate(rows[:200]): | |
| 421 | + if p.get_y() > 262: | |
| 422 | + p.add_page() | |
| 423 | + head() | |
| 424 | + p.set_text_color(*INK) | |
| 425 | + p.set_font("helvetica", "", 7.4) | |
| 426 | + p.set_fill_color(*(SURFACE2 if i % 2 else WHITE)) | |
| 427 | + for cell in row: | |
| 428 | + txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell) | |
| 429 | + p.cell(w, 5.4, " " + txt[:34], fill=True) | |
| 430 | + p.ln(5.4) | |
| 431 | + if len(rows) > 200: | |
| 432 | + p.set_font("helvetica", "", 7) | |
| 433 | + p.set_text_color(*INK3) | |
| 434 | + p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées") | |
| 435 | + p.ln(6) | |
| 436 | + | |
| 437 | + def _records(self): | |
| 438 | + recs = self.d.get("records") or [] | |
| 439 | + if not recs: | |
| 440 | + return | |
| 441 | + self._section_title("Records & faits marquants") | |
| 442 | + p = self.pdf | |
| 443 | + for r in recs[:10]: | |
| 444 | + if p.get_y() > 258: | |
| 445 | + p.add_page() | |
| 446 | + y = p.get_y() | |
| 447 | + self._card(p.l_margin, y, 174, 11, fill=SURFACE2) | |
| 448 | + p.set_xy(p.l_margin + 4, y + 2) | |
| 449 | + p.set_font("helvetica", "", 8.6) | |
| 450 | + p.set_text_color(*INK2) | |
| 451 | + p.cell(96, 7, str(r.get("label", ""))[:70]) | |
| 452 | + p.set_font("helvetica", "B", 9) | |
| 453 | + p.set_text_color(*INK) | |
| 454 | + p.cell(52, 7, str(r.get("value", ""))[:36], align="R") | |
| 455 | + p.set_font("helvetica", "", 7.6) | |
| 456 | + p.set_text_color(*INK3) | |
| 457 | + p.cell(20, 7, str(r.get("date", "") or ""), align="R") | |
| 458 | + p.set_y(y + 13.5) | |
| 459 | + p.ln(4) | |
| 460 | + | |
| 461 | + def _final_page(self): | |
| 462 | + p = self.pdf | |
| 463 | + p.add_page() | |
| 464 | + self._kicker("Groupe KA · contact") | |
| 465 | + p.set_font("helvetica", "B", 15) | |
| 466 | + p.set_text_color(*INK) | |
| 467 | + p.cell(0, 8, "Coordonnées du Groupe KA") | |
| 468 | + p.ln(12) | |
| 469 | + for email, role in EMAILS: | |
| 470 | + p.set_font("helvetica", "B", 10.5) | |
| 471 | + p.set_text_color(*INK) | |
| 472 | + p.cell(0, 6, email) | |
| 473 | + p.ln(5.5) | |
| 474 | + p.set_font("helvetica", "", 8.6) | |
| 475 | + p.set_text_color(*INK3) | |
| 476 | + p.cell(0, 5, role) | |
| 477 | + p.ln(8) | |
| 478 | + p.ln(2) | |
| 479 | + p.set_font("helvetica", "B", 10) | |
| 480 | + p.set_text_color(*GREEN) | |
| 481 | + p.cell(0, 6, "groupe-ka.com — le portail de l'écosystème ·Ka") | |
| 482 | + p.ln(10) | |
| 483 | + p.set_draw_color(*self.accent) | |
| 484 | + p.set_line_width(0.8) | |
| 485 | + p.line(p.l_margin, p.get_y(), p.l_margin + 30, p.get_y()) | |
| 486 | + p.ln(4) | |
| 487 | + p.set_font("helvetica", "", 8.6) | |
| 488 | + p.set_text_color(*INK2) | |
| 489 | + p.multi_cell(160, 4.6, DISCLAIMER) | |
| 490 | + p.ln(4) | |
| 491 | + p.set_font("helvetica", "", 7.6) | |
| 492 | + p.set_text_color(*INK3) | |
| 493 | + p.multi_cell( | |
| 494 | + 160, 4.2, | |
| 495 | + "Mentions : rapport généré automatiquement à partir des données réelles de la " | |
| 496 | + "plateforme au moment indiqué en couverture. Conditions d'utilisation, politique " | |
| 497 | + "de confidentialité et protection des renseignements personnels (Loi 25) : " | |
| 498 | + "groupe-ka.com/conditions · /confidentialite · /loi-25.", | |
| 499 | + ) | |
| 500 | + | |
| 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 | |
| 505 | + | |
| 506 | + def build(self) -> bytes: | |
| 507 | + p = self.pdf | |
| 508 | + p.alias_nb_pages() | |
| 509 | + self._cover() | |
| 510 | + if self.mode == "synthese": | |
| 511 | + p.add_page() | |
| 512 | + self._kpis() | |
| 513 | + self._records() | |
| 514 | + self._final_page() | |
| 515 | + else: | |
| 516 | + p.add_page() | |
| 517 | + toc_page_no = p.page_no() | |
| 518 | + p.add_page() | |
| 519 | + 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")) | |
| 533 | + for t in self.d.get("tables") or []: | |
| 534 | + self._table(t) | |
| 535 | + self._records() | |
| 536 | + self._final_page() | |
| 537 | + # sommaire écrit sur la page réservée (page 2) | |
| 538 | + last_page = p.page | |
| 539 | + p.page = toc_page_no | |
| 540 | + p.set_y(22) | |
| 541 | + p.set_font("helvetica", "B", 15) | |
| 542 | + p.set_text_color(*INK) | |
| 543 | + p.cell(0, 8, "Sommaire") | |
| 544 | + p.ln(12) | |
| 545 | + p.set_font("helvetica", "", 9.5) | |
| 546 | + for title, page_no in self.toc: | |
| 547 | + p.set_text_color(*INK) | |
| 548 | + p.cell(140, 6.5, title[:80]) | |
| 549 | + p.set_text_color(*INK3) | |
| 550 | + p.cell(0, 6.5, str(page_no), align="R") | |
| 551 | + p.ln(6.5) | |
| 552 | + p.page = last_page | |
| 553 | + return bytes(p.output()) | |
| 554 | + | |
| 555 | + | |
| 556 | +def filename(platform_id: str, period: str) -> str: | |
| 557 | + today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d") | |
| 558 | + return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf" | |
added
fabrika/statsdash.py
+300 −0
@@ -0,0 +1,300 @@ | ||
| 1 | +# ----------------------------------------------------------------------------- | |
| 2 | +# Fabri-Ka — Agrégateur de produits québécois | |
| 3 | +# Auteur : Simon-Pierre Boucher — contact@spboucher.ai | |
| 4 | +# statsdash.py : tableau de bord /api/stats/dashboard (contrat ka-stats SPEC.md) | |
| 5 | +# ----------------------------------------------------------------------------- | |
| 6 | +"""Toutes les valeurs viennent de la base réelle (products / stores) : | |
| 7 | +- volumes et nouveautés par jour via `first_seen` (epoch) ; | |
| 8 | +- prix moyen/médian sur les produits actifs avec prix (> 0, plafond 500 000 $ | |
| 9 | + pour la moyenne, même garde-fou que /api/stats/extended) ; | |
| 10 | +- deltas des KPI de stock = état à la fin vs état au DÉBUT de la période | |
| 11 | + (reconstruit avec first_seen) ; delta des nouveautés = fenêtre précédente | |
| 12 | + de même longueur. Aucun chiffre inventé : indisponible => None (le front | |
| 13 | + masque). Cache mémoire 5 min par période.""" | |
| 14 | +from __future__ import annotations | |
| 15 | + | |
| 16 | +import sqlite3 | |
| 17 | +import time | |
| 18 | +from datetime import date, datetime, timedelta | |
| 19 | +from zoneinfo import ZoneInfo | |
| 20 | + | |
| 21 | +from . import db | |
| 22 | +from .schema import CATEGORIES | |
| 23 | + | |
| 24 | +TZ = ZoneInfo("America/Toronto") | |
| 25 | +PRICE_CAP = 500_000 # prix aberrants exclus de la moyenne | |
| 26 | +CACHE_TTL = 300 # ≥ 5 min (SPEC) | |
| 27 | + | |
| 28 | +PLATFORM_LABELS = { | |
| 29 | + "shopify": "Shopify", "woocommerce": "WooCommerce", "wix": "Wix", | |
| 30 | + "squarespace": "Squarespace", "lightspeed": "Lightspeed", | |
| 31 | + "prestashop": "PrestaShop", "snipcart": "Snipcart", | |
| 32 | + "wordpress": "WordPress", "generic": "Site générique", "": "Inconnue", | |
| 33 | +} | |
| 34 | + | |
| 35 | +BUCKETS = [ | |
| 36 | + ("0-10", "Moins de 10 $"), ("10-25", "10 – 25 $"), ("25-50", "25 – 50 $"), | |
| 37 | + ("50-100", "50 – 100 $"), ("100-250", "100 – 250 $"), | |
| 38 | + ("250-1000", "250 – 1 000 $"), ("1000+", "1 000 $ et plus"), | |
| 39 | +] | |
| 40 | + | |
| 41 | + | |
| 42 | +def _cat_label(key: str | None) -> str: | |
| 43 | + return CATEGORIES.get(key or "", (key or "Autre", []))[0] | |
| 44 | + | |
| 45 | + | |
| 46 | +def _price(v) -> str: | |
| 47 | + if v is None: | |
| 48 | + return "—" | |
| 49 | + return f"{v:,.2f}".replace(",", " ").replace(".", ",") + " $" | |
| 50 | + | |
| 51 | + | |
| 52 | +def _delta(cur, prev) -> float | None: | |
| 53 | + """% de variation, None si la base de comparaison est vide (rien d'inventé).""" | |
| 54 | + if prev is None or cur is None or prev <= 0: | |
| 55 | + return None | |
| 56 | + return round(100.0 * (cur - prev) / prev, 1) | |
| 57 | + | |
| 58 | + | |
| 59 | +def _ts(d: date) -> float: | |
| 60 | + return datetime(d.year, d.month, d.day, tzinfo=TZ).timestamp() | |
| 61 | + | |
| 62 | + | |
| 63 | +def _bounds(con: sqlite3.Connection, period: str, from_: str | None, | |
| 64 | + to: str | None) -> tuple[date, date, str]: | |
| 65 | + today = datetime.now(TZ).date() | |
| 66 | + if from_ and to: | |
| 67 | + start, end = date.fromisoformat(from_), date.fromisoformat(to) | |
| 68 | + if end < start: | |
| 69 | + start, end = end, start | |
| 70 | + return start, min(end, today), f"du {start} au {min(end, today)}" | |
| 71 | + days = {"7j": (7, "7 jours"), "30j": (30, "30 jours"), "3m": (90, "3 mois"), | |
| 72 | + "6m": (180, "6 mois"), "12m": (365, "12 mois")} | |
| 73 | + if period == "auj": | |
| 74 | + return today, today, "aujourd'hui" | |
| 75 | + if period == "annee": | |
| 76 | + return date(today.year, 1, 1), today, f"année {today.year}" | |
| 77 | + if period == "tout": | |
| 78 | + row = con.execute("SELECT MIN(first_seen) FROM products").fetchone() | |
| 79 | + start = (datetime.fromtimestamp(row[0], TZ).date() | |
| 80 | + if row and row[0] else today) | |
| 81 | + return start, today, "toute la période" | |
| 82 | + n, label = days.get(period, days["30j"]) | |
| 83 | + return today - timedelta(days=n - 1), today, label | |
| 84 | + | |
| 85 | + | |
| 86 | +def _daily(con, t0: float, t1: float) -> dict[str, int]: | |
| 87 | + """Nouveaux produits par jour (date locale) dans [t0, t1).""" | |
| 88 | + rows = con.execute( | |
| 89 | + """SELECT date(first_seen,'unixepoch','localtime') AS d, COUNT(*) AS n | |
| 90 | + FROM products WHERE first_seen>=? AND first_seen<? GROUP BY d""", | |
| 91 | + (t0, t1)).fetchall() | |
| 92 | + return {r[0]: r[1] for r in rows} | |
| 93 | + | |
| 94 | + | |
| 95 | +def _median(con, extra_where: str = "", args: tuple = ()) -> float | None: | |
| 96 | + n = con.execute( | |
| 97 | + f"SELECT COUNT(*) FROM products WHERE active=1 AND price>0{extra_where}", | |
| 98 | + args).fetchone()[0] | |
| 99 | + if not n: | |
| 100 | + return None | |
| 101 | + row = con.execute( | |
| 102 | + f"""SELECT price FROM products WHERE active=1 AND price>0{extra_where} | |
| 103 | + ORDER BY price LIMIT 1 OFFSET ?""", args + (n // 2,)).fetchone() | |
| 104 | + return round(row[0], 2) if row else None | |
| 105 | + | |
| 106 | + | |
| 107 | +def _build(period: str, from_: str | None, to: str | None) -> dict: | |
| 108 | + con = db.connect() | |
| 109 | + try: | |
| 110 | + start, end, label = _bounds(con, period, from_, to) | |
| 111 | + ndays = (end - start).days + 1 | |
| 112 | + t0, t1 = _ts(start), _ts(end + timedelta(days=1)) | |
| 113 | + p_start, p_end = start - timedelta(days=ndays), start - timedelta(days=1) | |
| 114 | + pt0, pt1 = _ts(p_start), _ts(p_end + timedelta(days=1)) | |
| 115 | + one = lambda sql, a=(): con.execute(sql, a).fetchone()[0] # noqa: E731 | |
| 116 | + | |
| 117 | + # ----- KPI : état courant vs état au début de la période ------------- | |
| 118 | + total = one("SELECT COUNT(*) FROM products WHERE active=1") | |
| 119 | + total_t0 = one("SELECT COUNT(*) FROM products WHERE active=1 AND first_seen<?", (t0,)) | |
| 120 | + stores_live = one("SELECT COUNT(*) FROM stores WHERE product_count>0") | |
| 121 | + stores_t0 = one("""SELECT COUNT(DISTINCT store_id) FROM products | |
| 122 | + WHERE active=1 AND first_seen<?""", (t0,)) | |
| 123 | + new_cur = one("SELECT COUNT(*) FROM products WHERE first_seen>=? AND first_seen<?", (t0, t1)) | |
| 124 | + new_prev = one("SELECT COUNT(*) FROM products WHERE first_seen>=? AND first_seen<?", (pt0, pt1)) | |
| 125 | + avg_now = one("""SELECT ROUND(AVG(price),2) FROM products | |
| 126 | + WHERE active=1 AND price>0 AND price<=?""", (PRICE_CAP,)) | |
| 127 | + avg_t0 = one("""SELECT ROUND(AVG(price),2) FROM products | |
| 128 | + WHERE active=1 AND price>0 AND price<=? AND first_seen<?""", | |
| 129 | + (PRICE_CAP, t0)) | |
| 130 | + med_now = _median(con) | |
| 131 | + cats = one("SELECT COUNT(DISTINCT category) FROM products WHERE active=1 AND category<>''") | |
| 132 | + cats_t0 = one("""SELECT COUNT(DISTINCT category) FROM products | |
| 133 | + WHERE active=1 AND category<>'' AND first_seen<?""", (t0,)) | |
| 134 | + regions = one("""SELECT COUNT(DISTINCT region) FROM stores | |
| 135 | + WHERE region<>'' AND product_count>0""") | |
| 136 | + regions_t0 = one("""SELECT COUNT(DISTINCT s.region) FROM stores s | |
| 137 | + JOIN products p ON p.store_id=s.id | |
| 138 | + WHERE s.region<>'' AND p.active=1 AND p.first_seen<?""", (t0,)) | |
| 139 | + | |
| 140 | + def kpi(id_, lab, value, prev=None, unit="", raw_delta=None): | |
| 141 | + d = raw_delta if raw_delta is not None else _delta(value, prev) | |
| 142 | + return {"id": id_, "label": lab, "value": value, "unit": unit, | |
| 143 | + "delta_pct": d, | |
| 144 | + "direction": None if d is None else ("up" if d >= 0 else "down")} | |
| 145 | + | |
| 146 | + kpis = [ | |
| 147 | + kpi("produits", "Produits actifs au catalogue", total, total_t0), | |
| 148 | + kpi("boutiques", "Boutiques en ligne avec produits", stores_live, stores_t0), | |
| 149 | + kpi("nouveautes", f"Nouveaux produits ({label})", new_cur, new_prev), | |
| 150 | + kpi("prix_moyen", "Prix moyen (produits actifs)", avg_now, avg_t0, unit="$"), | |
| 151 | + kpi("prix_median", "Prix médian (produits actifs)", med_now, unit="$"), | |
| 152 | + kpi("categories", "Catégories couvertes", cats, cats_t0), | |
| 153 | + kpi("regions", "Régions avec boutiques actives", regions, regions_t0), | |
| 154 | + ] | |
| 155 | + | |
| 156 | + # ----- séries quotidiennes ------------------------------------------- | |
| 157 | + cur_daily = _daily(con, t0, t1) | |
| 158 | + prev_daily = _daily(con, pt0, pt1) | |
| 159 | + days = [start + timedelta(days=i) for i in range(min(ndays, 400))] | |
| 160 | + new_points = [{"t": d.isoformat(), "v": cur_daily.get(d.isoformat(), 0)} | |
| 161 | + for d in days] | |
| 162 | + compare = None | |
| 163 | + if sum(prev_daily.values()): | |
| 164 | + pdays = [p_start + timedelta(days=i) for i in range(min(ndays, 400))] | |
| 165 | + compare = [{"t": d.isoformat(), "v": prev_daily.get(d.isoformat(), 0)} | |
| 166 | + for d in pdays] | |
| 167 | + base = one("SELECT COUNT(*) FROM products WHERE first_seen<?", (t0,)) | |
| 168 | + cum_points, acc = [], base | |
| 169 | + for pt in new_points: | |
| 170 | + acc += pt["v"] | |
| 171 | + cum_points.append({"t": pt["t"], "v": acc}) | |
| 172 | + series = [ | |
| 173 | + {"id": "nouveautes_jour", "title": "Nouveaux produits détectés par jour", | |
| 174 | + "unit": "produits", "kind": "line", "points": new_points, | |
| 175 | + **({"compare": compare} if compare else {})}, | |
| 176 | + {"id": "cumul", "title": "Produits détectés — cumul du catalogue", | |
| 177 | + "unit": "produits", "kind": "line", "points": cum_points}, | |
| 178 | + ] | |
| 179 | + | |
| 180 | + # ----- répartitions --------------------------------------------------- | |
| 181 | + plat = con.execute("""SELECT platform, COUNT(*) FROM stores | |
| 182 | + WHERE product_count>0 GROUP BY platform | |
| 183 | + ORDER BY 2 DESC""").fetchall() | |
| 184 | + top_cats = con.execute("""SELECT category, COUNT(*) FROM products | |
| 185 | + WHERE active=1 GROUP BY category | |
| 186 | + ORDER BY 2 DESC LIMIT 12""").fetchall() | |
| 187 | + buckets = dict(con.execute("""SELECT CASE | |
| 188 | + WHEN price < 10 THEN '0-10' WHEN price < 25 THEN '10-25' | |
| 189 | + WHEN price < 50 THEN '25-50' WHEN price < 100 THEN '50-100' | |
| 190 | + WHEN price < 250 THEN '100-250' WHEN price < 1000 THEN '250-1000' | |
| 191 | + ELSE '1000+' END AS b, COUNT(*) FROM products | |
| 192 | + WHERE active=1 AND price>0 GROUP BY b""").fetchall()) | |
| 193 | + breakdowns = [ | |
| 194 | + {"id": "plateformes", "title": "Boutiques par plateforme e-commerce", | |
| 195 | + "kind": "donut", | |
| 196 | + "items": [{"label": PLATFORM_LABELS.get(p or "", p or "Inconnue"), | |
| 197 | + "value": n} for p, n in plat]}, | |
| 198 | + {"id": "categories", "title": "Top catégories (produits actifs)", | |
| 199 | + "kind": "bar", | |
| 200 | + "items": [{"label": _cat_label(c), "value": n} for c, n in top_cats]}, | |
| 201 | + {"id": "prix", "title": "Fourchettes de prix (produits actifs)", | |
| 202 | + "kind": "bar", | |
| 203 | + "items": [{"label": lab, "value": buckets[k]} | |
| 204 | + for k, lab in BUCKETS if buckets.get(k)]}, | |
| 205 | + ] | |
| 206 | + | |
| 207 | + geo_rows = con.execute("""SELECT s.region, COUNT(p.uid) FROM stores s | |
| 208 | + JOIN products p ON p.store_id=s.id AND p.active=1 | |
| 209 | + WHERE s.region<>'' GROUP BY s.region | |
| 210 | + ORDER BY 2 DESC""").fetchall() | |
| 211 | + geo = {"title": "Produits actifs par région", | |
| 212 | + "items": [{"label": r, "value": n} for r, n in geo_rows]} | |
| 213 | + | |
| 214 | + # ----- heatmap : nouveautés/jour sur 26 semaines ---------------------- | |
| 215 | + h_start = datetime.now(TZ).date() - timedelta(days=181) | |
| 216 | + hm = _daily(con, _ts(h_start), _ts(datetime.now(TZ).date() + timedelta(days=1))) | |
| 217 | + heatmap = {"title": "Nouveaux produits par jour", | |
| 218 | + "cells": [{"date": d, "value": v} for d, v in sorted(hm.items())]} | |
| 219 | + | |
| 220 | + # ----- tableaux -------------------------------------------------------- | |
| 221 | + shop_rows = con.execute(""" | |
| 222 | + SELECT s.name, s.region, s.product_count, | |
| 223 | + (SELECT COUNT(*) FROM products p WHERE p.store_id=s.id | |
| 224 | + AND p.first_seen>=? AND p.first_seen<?) AS nouv, | |
| 225 | + (SELECT ROUND(AVG(p.price),2) FROM products p | |
| 226 | + WHERE p.store_id=s.id AND p.active=1 AND p.price>0 | |
| 227 | + AND p.price<=?) AS pavg | |
| 228 | + FROM stores s WHERE s.product_count>0 | |
| 229 | + ORDER BY s.product_count DESC LIMIT 50""", (t0, t1, PRICE_CAP)).fetchall() | |
| 230 | + cat_rows = con.execute(""" | |
| 231 | + SELECT category, COUNT(*) AS n, COUNT(DISTINCT store_id) AS st, | |
| 232 | + ROUND(AVG(CASE WHEN price>0 AND price<=? THEN price END),2) | |
| 233 | + FROM products WHERE active=1 GROUP BY category | |
| 234 | + ORDER BY n DESC""", (PRICE_CAP,)).fetchall() | |
| 235 | + tables = [ | |
| 236 | + {"id": "top_boutiques", "title": "Top boutiques", | |
| 237 | + "columns": ["Boutique", "Région", "Produits", "Nouveautés (période)", "Prix moyen"], | |
| 238 | + "rows": [[name or "—", reg or "—", n, nouv, _price(pavg)] | |
| 239 | + for name, reg, n, nouv, pavg in shop_rows]}, | |
| 240 | + {"id": "categories", "title": "Catégories en détail", | |
| 241 | + "columns": ["Catégorie", "Produits", "Boutiques", "Prix moyen", "Prix médian"], | |
| 242 | + "rows": [[_cat_label(c), n, st, _price(pavg), | |
| 243 | + _price(_median(con, " AND category=?", (c,)))] | |
| 244 | + for c, n, st, pavg in cat_rows]}, | |
| 245 | + ] | |
| 246 | + | |
| 247 | + # ----- records & faits marquants -------------------------------------- | |
| 248 | + records = [] | |
| 249 | + if cur_daily: | |
| 250 | + day, v = max(cur_daily.items(), key=lambda kv: kv[1]) | |
| 251 | + records.append({"label": "Jour record de nouveautés (période)", | |
| 252 | + "value": f"{v:,}".replace(",", " ") + " produits", "date": day}) | |
| 253 | + top_shop = con.execute("""SELECT s.name, COUNT(*) FROM products p | |
| 254 | + JOIN stores s ON s.id=p.store_id WHERE p.first_seen>=? AND p.first_seen<? | |
| 255 | + GROUP BY p.store_id ORDER BY 2 DESC LIMIT 1""", (t0, t1)).fetchone() | |
| 256 | + if top_shop: | |
| 257 | + records.append({"label": f"Boutique la plus prolifique (période) — {(top_shop[0] or '')[:40]}", | |
| 258 | + "value": f"{top_shop[1]:,}".replace(",", " ") + " nouveautés"}) | |
| 259 | + top_region = con.execute("""SELECT s.region, COUNT(*) FROM products p | |
| 260 | + JOIN stores s ON s.id=p.store_id WHERE s.region<>'' | |
| 261 | + AND p.first_seen>=? AND p.first_seen<? GROUP BY s.region | |
| 262 | + ORDER BY 2 DESC LIMIT 1""", (t0, t1)).fetchone() | |
| 263 | + if top_region: | |
| 264 | + records.append({"label": "Région la plus active (période)", | |
| 265 | + "value": f"{top_region[0]} — " + f"{top_region[1]:,}".replace(",", " ") + " nouveautés"}) | |
| 266 | + if top_cats: | |
| 267 | + records.append({"label": "Catégorie la plus fournie", | |
| 268 | + "value": f"{_cat_label(top_cats[0][0])} — " | |
| 269 | + + f"{top_cats[0][1]:,}".replace(",", " ") + " produits"}) | |
| 270 | + dear = con.execute("""SELECT p.title, p.price, s.name FROM products p | |
| 271 | + JOIN stores s ON s.id=p.store_id WHERE p.active=1 AND p.price>0 | |
| 272 | + AND p.price<=? ORDER BY p.price DESC LIMIT 1""", (PRICE_CAP,)).fetchone() | |
| 273 | + if dear: | |
| 274 | + records.append({"label": f"Produit le plus cher au catalogue — {(dear[0] or '')[:34]} ({dear[2]})", | |
| 275 | + "value": _price(dear[1])}) | |
| 276 | + | |
| 277 | + return { | |
| 278 | + "updated": datetime.now(TZ).isoformat(timespec="seconds"), | |
| 279 | + "period": {"from": start.isoformat(), "to": end.isoformat(), "label": label}, | |
| 280 | + "kpis": kpis, "series": series, "breakdowns": breakdowns, | |
| 281 | + "geo": geo, "heatmap": heatmap, "tables": tables, "records": records, | |
| 282 | + } | |
| 283 | + finally: | |
| 284 | + con.close() | |
| 285 | + | |
| 286 | + | |
| 287 | +_cache: dict[tuple, tuple[float, dict]] = {} | |
| 288 | + | |
| 289 | + | |
| 290 | +def dashboard(period: str = "30j", from_: str | None = None, | |
| 291 | + to: str | None = None) -> dict: | |
| 292 | + key = (period, from_ or "", to or "") | |
| 293 | + hit = _cache.get(key) | |
| 294 | + if hit and time.time() - hit[0] < CACHE_TTL: | |
| 295 | + return hit[1] | |
| 296 | + data = _build(period, from_, to) | |
| 297 | + if len(_cache) > 64: | |
| 298 | + _cache.clear() | |
| 299 | + _cache[key] = (time.time(), data) | |
| 300 | + return data | |
modified
fabrika/web.py
+38 −0
@@ -327,6 +327,44 @@ def report_pdf(): | ||
| 327 | 327 | headers={"Content-Disposition": f'attachment; filename="{fname}"'}) |
| 328 | 328 | |
| 329 | 329 | |
| 330 | +# ---- module Stats commun Groupe KA (contrat ka-stats SPEC.md) --------------- | |
| 331 | +@app.get("/api/stats/dashboard") | |
| 332 | +def stats_dashboard(period: str = "30j", | |
| 333 | + from_: str | None = Query(None, alias="from"), | |
| 334 | + to: str | None = None): | |
| 335 | + """Tableau de bord analytique (KPI, séries, répartitions, geo, heatmap, | |
| 336 | + tableaux, records) — données réelles, cache 5 min par période.""" | |
| 337 | + from . import statsdash | |
| 338 | + try: | |
| 339 | + return statsdash.dashboard(period, from_, to) | |
| 340 | + except ValueError: | |
| 341 | + raise HTTPException(400, "Dates invalides (format attendu YYYY-MM-DD)") | |
| 342 | + | |
| 343 | + | |
| 344 | +@app.get("/api/stats/report") | |
| 345 | +def stats_report(period: str = "30j", | |
| 346 | + from_: str | None = Query(None, alias="from"), | |
| 347 | + to: str | None = None, | |
| 348 | + mode: str = "complet"): | |
| 349 | + """Rapport statistique PDF estampillé Groupe-KA (gabarit kapdf/fpdf2).""" | |
| 350 | + from fastapi.responses import Response | |
| 351 | + | |
| 352 | + from . import kapdf, statsdash | |
| 353 | + try: | |
| 354 | + dash = statsdash.dashboard(period, from_, to) | |
| 355 | + except ValueError: | |
| 356 | + raise HTTPException(400, "Dates invalides (format attendu YYYY-MM-DD)") | |
| 357 | + site = {"wordmark": "Fabri·Ka", "accent": "#c4532e", | |
| 358 | + "domain": "www.fabri-ka.com", | |
| 359 | + "tagline": "Tous les produits québécois. Un seul endroit."} | |
| 360 | + pdf = kapdf.GroupeKAReport( | |
| 361 | + site=site, dashboard=dash, | |
| 362 | + mode="synthese" if mode == "synthese" else "complet").build() | |
| 363 | + fname = kapdf.filename("fabri-ka", period) | |
| 364 | + return Response(content=pdf, media_type="application/pdf", | |
| 365 | + headers={"Content-Disposition": f'attachment; filename="{fname}"'}) | |
| 366 | + | |
| 367 | + | |
| 330 | 368 | @app.get("/api/stats") |
| 331 | 369 | def stats(): |
| 332 | 370 | con = db.connect() |
added
frontend/src/ka/stats/SPEC.md
+123 −0
@@ -0,0 +1,123 @@ | ||
| 1 | +# ka-stats — module Stats commun Groupe KA (spec v1) | |
| 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. | |
| 6 | + | |
| 7 | +## 1. Page /stats — structure obligatoire (dans cet ordre) | |
| 8 | + | |
| 9 | +1. **Bandeau KPI** : 4–6 grandes cartes (`KpiCard`) — valeur, libellé, | |
| 10 | + variation vs période précédente (▲/▼ + %, vert `--green` / rouge `--danger`). | |
| 11 | +2. **Sélecteur de période global** (`PeriodSelector`) : `aujourd'hui · 7 j · | |
| 12 | + 30 j · 3 m · 6 m · 12 m · année en cours · tout` + plage personnalisée | |
| 13 | + (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 | + 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. | |
| 28 | + | |
| 29 | +Responsive : KPI empilés < 768 px, graphiques pleine largeur redimensionnés | |
| 30 | +(SVG viewBox), tableaux en défilement horizontal contenu, tactile ≥ 44 px. | |
| 31 | +AUCUNE donnée inventée : une stat indisponible = bloc « Pas encore mesuré » | |
| 32 | +(carte grise propre), jamais un faux chiffre. | |
| 33 | + | |
| 34 | +## 2. API — contrat commun | |
| 35 | + | |
| 36 | +`GET /api/stats/dashboard?period=7j|30j|3m|6m|12m|annee|tout|auj&from=YYYY-MM-DD&to=YYYY-MM-DD` | |
| 37 | + | |
| 38 | +```jsonc | |
| 39 | +{ | |
| 40 | + "updated": "2026-08-17T21:04:00-04:00", | |
| 41 | + "period": { "from": "2026-07-18", "to": "2026-08-17", "label": "30 jours" }, | |
| 42 | + "kpis": [ { "id": "total", "label": "Annonces actives", "value": 33744, | |
| 43 | + "unit": "", "delta_pct": 4.2, "direction": "up" } ], | |
| 44 | + "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 }] } ], | |
| 49 | + "geo": { "title": "Par région", "items": [{ "label": "Montréal", "value": 15680 }] }, | |
| 50 | + "heatmap": { "title": "Activité", "cells": [{ "date": "2026-08-01", "value": 210 }] }, | |
| 51 | + "tables": [ { "id": "top", "title": "Top villes", "columns": ["Ville", "Annonces", "Δ 30 j"], | |
| 52 | + "rows": [["Montréal", 15680, "+3,1 %"]] } ], | |
| 53 | + "records": [ { "label": "Jour record d'ajouts", "value": "412 annonces", "date": "2026-08-09" } ] | |
| 54 | +} | |
| 55 | +``` | |
| 56 | + | |
| 57 | +Champs absents = section masquée. Cache serveur recommandé (≥ 5 min par | |
| 58 | +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…). | |
| 60 | + | |
| 61 | +`GET /api/stats/report?period=…&from=&to=&mode=complet|synthese` | |
| 62 | +→ `application/pdf`, en-tête `Content-Disposition: attachment; filename= | |
| 63 | +groupe-ka_<plateforme>_stats_<periode>_<YYYY-MM-DD>.pdf`. | |
| 64 | + | |
| 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) | |
| 67 | + | |
| 68 | +- **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 | |
| 71 | + « 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é). | |
| 74 | +- **Graphiques VECTORIELS** (dessinés en primitives, jamais de capture) : | |
| 75 | + courbes, barres, anneaux — accent de la plateforme, axes/graduations encre. | |
| 76 | +- **Tableaux** paginés proprement (lignes zébrées `--surface-2`, jamais | |
| 77 | + coupés en deux à cheval sur une ligne). | |
| 78 | +- **Records** puis **page de fin** : coordonnées Groupe KA (3 courriels + | |
| 79 | + rôles d'ecosystem.json, groupe-ka.com), avertissement d'agrégateur, | |
| 80 | + mentions légales courtes. | |
| 81 | +- **Chaque page** : en-tête discret (« Groupe KA · {Plateforme} », filet | |
| 82 | + encre) + pied (« © Groupe-KA — {année} — groupe-ka.com · {période} · p. X/Y »). | |
| 83 | +- 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. | |
| 85 | + | |
| 86 | +## 4. Spécifique par plateforme (sections métier attendues) | |
| 87 | + | |
| 88 | +- **groupe-ka** : tableau de bord maître — consolidation des 12 (volume total, | |
| 89 | + croissance), classement des plateformes, bloc résumé par plateforme + lien | |
| 90 | + vers sa page /stats ; « Rapport écosystème complet » = PDF consolidé. | |
| 91 | +- **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é. | |
| 95 | +- **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. | |
| 105 | +- **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. | |
| 117 | + | |
| 118 | +## 5. Ajouter une métrique / un graphique / une plateforme | |
| 119 | + | |
| 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. | |
added
frontend/src/ka/stats/kacharts.tsx
+389 −0
@@ -0,0 +1,389 @@ | ||
| 1 | +// Auteur : Simon-Pierre Boucher — contact@spboucher.ai | |
| 2 | +// ka-ui/stats/kacharts.tsx — kit de graphiques SVG du module Stats commun | |
| 3 | +// Groupe KA (zéro dépendance, React 18+). Style : design system ka-ui | |
| 4 | +// (bordures encre, accent de la plateforme via var(--accent)). | |
| 5 | +// Composants : KpiCard, PeriodSelector, LineChart (infobulle + légende | |
| 6 | +// cliquable + comparaison N-1), BarChart, Donut, CalendarHeatmap, DataTable | |
| 7 | +// (tri/recherche/pagination), RecordCard, PdfButton, EmptyBlock, Fraicheur. | |
| 8 | +import { useMemo, useState } from "react"; | |
| 9 | + | |
| 10 | +/* ---------- types (contrat SPEC.md) ---------- */ | |
| 11 | +export type Kpi = { | |
| 12 | + id: string; label: string; value: number | string; unit?: string; | |
| 13 | + delta_pct?: number | null; direction?: "up" | "down"; | |
| 14 | +}; | |
| 15 | +export type Point = { t: string; v: number }; | |
| 16 | +export type Serie = { | |
| 17 | + id: string; title: string; unit?: string; kind?: "line" | "bar"; | |
| 18 | + points: Point[]; compare?: Point[]; | |
| 19 | +}; | |
| 20 | +export type BreakItem = { label: string; value: number }; | |
| 21 | +export type TableSpec = { id: string; title: string; columns: string[]; rows: (string | number)[][] }; | |
| 22 | +export type RecordFact = { label: string; value: string; date?: string }; | |
| 23 | + | |
| 24 | +export const PERIODS: { id: string; label: string }[] = [ | |
| 25 | + { id: "auj", label: "Aujourd'hui" }, | |
| 26 | + { id: "7j", label: "7 jours" }, | |
| 27 | + { id: "30j", label: "30 jours" }, | |
| 28 | + { id: "3m", label: "3 mois" }, | |
| 29 | + { id: "6m", label: "6 mois" }, | |
| 30 | + { id: "12m", label: "12 mois" }, | |
| 31 | + { id: "annee", label: "Année en cours" }, | |
| 32 | + { id: "tout", label: "Tout" }, | |
| 33 | +]; | |
| 34 | + | |
| 35 | +export const fmtInt = (n: number) => n.toLocaleString("fr-CA"); | |
| 36 | +export const fmtNum = (n: number) => | |
| 37 | + Number.isInteger(n) ? fmtInt(n) : n.toLocaleString("fr-CA", { maximumFractionDigits: 2 }); | |
| 38 | + | |
| 39 | +/* ---------- KPI ---------- */ | |
| 40 | +export function KpiCard({ k }: { k: Kpi }) { | |
| 41 | + const up = (k.direction ?? ((k.delta_pct ?? 0) >= 0 ? "up" : "down")) === "up"; | |
| 42 | + return ( | |
| 43 | + <article className="card" style={{ padding: "14px 16px", minWidth: 0 }}> | |
| 44 | + <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px,2.4vw,30px)", letterSpacing: "-0.02em" }}> | |
| 45 | + {typeof k.value === "number" ? fmtNum(k.value) : k.value} | |
| 46 | + {k.unit ? <span style={{ fontSize: "0.6em", color: "var(--ink-2)" }}> {k.unit}</span> : null} | |
| 47 | + </p> | |
| 48 | + <p className="klabel" style={{ margin: "6px 0 0" }}>{k.label}</p> | |
| 49 | + {k.delta_pct !== undefined && k.delta_pct !== null && ( | |
| 50 | + <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}> | |
| 51 | + {up ? "▲" : "▼"} {k.delta_pct >= 0 ? "+" : ""}{fmtNum(k.delta_pct)} % <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span> | |
| 52 | + </p> | |
| 53 | + )} | |
| 54 | + </article> | |
| 55 | + ); | |
| 56 | +} | |
| 57 | + | |
| 58 | +/* ---------- Sélecteur de période ---------- */ | |
| 59 | +export function PeriodSelector({ | |
| 60 | + value, onChange, custom, onCustom, | |
| 61 | +}: { | |
| 62 | + value: string; onChange: (p: string) => void; | |
| 63 | + custom?: { from: string; to: string }; onCustom?: (from: string, to: string) => void; | |
| 64 | +}) { | |
| 65 | + return ( | |
| 66 | + <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}> | |
| 67 | + {PERIODS.map((p) => ( | |
| 68 | + <button key={p.id} type="button" onClick={() => onChange(p.id)} | |
| 69 | + className="chip" aria-pressed={value === p.id} | |
| 70 | + style={{ cursor: "pointer", minHeight: 44, background: value === p.id ? "var(--accent)" : "var(--surface)", color: value === p.id ? "var(--on-accent)" : "var(--ink)" }}> | |
| 71 | + {p.label} | |
| 72 | + </button> | |
| 73 | + ))} | |
| 74 | + {onCustom && ( | |
| 75 | + <span style={{ display: "inline-flex", gap: 6, alignItems: "center" }}> | |
| 76 | + <input className="input" type="date" style={{ width: 150 }} value={custom?.from ?? ""} aria-label="Du" | |
| 77 | + onChange={(e) => onCustom(e.target.value, custom?.to ?? "")} /> | |
| 78 | + <span className="klabel">au</span> | |
| 79 | + <input className="input" type="date" style={{ width: 150 }} value={custom?.to ?? ""} aria-label="Au" | |
| 80 | + onChange={(e) => onCustom(custom?.from ?? "", e.target.value)} /> | |
| 81 | + </span> | |
| 82 | + )} | |
| 83 | + </div> | |
| 84 | + ); | |
| 85 | +} | |
| 86 | + | |
| 87 | +/* ---------- Courbe ---------- */ | |
| 88 | +export function LineChart({ serie, height = 240 }: { serie: Serie; height?: number }) { | |
| 89 | + const [hide, setHide] = useState<{ cur: boolean; cmp: boolean }>({ cur: false, cmp: false }); | |
| 90 | + const [hover, setHover] = useState<number | null>(null); | |
| 91 | + const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26; | |
| 92 | + const pts = serie.points ?? []; | |
| 93 | + if (pts.length < 2) return <EmptyBlock title={serie.title} />; | |
| 94 | + const all = [...(hide.cur ? [] : pts), ...(!hide.cmp && serie.compare ? serie.compare : [])]; | |
| 95 | + const vmax = Math.max(...all.map((p) => p.v), 1); | |
| 96 | + const vmin = Math.min(0, ...all.map((p) => p.v)); | |
| 97 | + const X = (i: number, n: number) => PL + ((W - PL - PR) * i) / (n - 1); | |
| 98 | + const Y = (v: number) => PT + (H - PT - PB) * (1 - (v - vmin) / (vmax - vmin || 1)); | |
| 99 | + const path = (s: Point[]) => s.map((p, i) => `${i ? "L" : "M"}${X(i, s.length)},${Y(p.v)}`).join(""); | |
| 100 | + const hi = hover !== null ? Math.min(pts.length - 1, Math.max(0, hover)) : null; | |
| 101 | + return ( | |
| 102 | + <figure className="card" style={{ margin: 0, padding: 16 }}> | |
| 103 | + <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}> | |
| 104 | + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{serie.title}</b> | |
| 105 | + <span style={{ display: "flex", gap: 10 }}> | |
| 106 | + <LegendChip label="Période courante" color="var(--accent)" off={hide.cur} onClick={() => setHide((h) => ({ ...h, cur: !h.cur }))} /> | |
| 107 | + {serie.compare && <LegendChip label="Période comparée" color="var(--ink-3)" dashed off={hide.cmp} onClick={() => setHide((h) => ({ ...h, cmp: !h.cmp }))} />} | |
| 108 | + </span> | |
| 109 | + </figcaption> | |
| 110 | + <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10, touchAction: "pan-y" }} role="img" aria-label={serie.title} | |
| 111 | + onMouseMove={(e) => { | |
| 112 | + const r = (e.currentTarget as SVGSVGElement).getBoundingClientRect(); | |
| 113 | + const fx = ((e.clientX - r.left) / r.width) * W; | |
| 114 | + setHover(Math.round(((fx - PL) / (W - PL - PR)) * (pts.length - 1))); | |
| 115 | + }} | |
| 116 | + onMouseLeave={() => setHover(null)}> | |
| 117 | + {[0, 1, 2, 3, 4].map((g) => { | |
| 118 | + const y = PT + ((H - PT - PB) * g) / 4; | |
| 119 | + const v = vmax - ((vmax - vmin) * g) / 4; | |
| 120 | + return ( | |
| 121 | + <g key={g}> | |
| 122 | + <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} /> | |
| 123 | + <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text> | |
| 124 | + </g> | |
| 125 | + ); | |
| 126 | + })} | |
| 127 | + {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => ( | |
| 128 | + <text key={i} x={X(i, pts.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text> | |
| 129 | + ))} | |
| 130 | + {!hide.cmp && serie.compare && serie.compare.length > 1 && ( | |
| 131 | + <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" /> | |
| 132 | + )} | |
| 133 | + {!hide.cur && <path d={path(pts)} fill="none" stroke="var(--accent)" strokeWidth={2.4} />} | |
| 134 | + {hi !== null && ( | |
| 135 | + <g> | |
| 136 | + <line x1={X(hi, pts.length)} x2={X(hi, pts.length)} y1={PT} y2={H - PB} stroke="var(--ink)" strokeWidth={1} strokeDasharray="2 3" /> | |
| 137 | + <circle cx={X(hi, pts.length)} cy={Y(pts[hi].v)} r={4} fill="var(--accent)" stroke="var(--ink)" strokeWidth={1.5} /> | |
| 138 | + </g> | |
| 139 | + )} | |
| 140 | + </svg> | |
| 141 | + {hi !== null && ( | |
| 142 | + <p className="chip" style={{ marginTop: 8 }}> | |
| 143 | + {pts[hi].t} — <b>{fmtNum(pts[hi].v)}{serie.unit ? ` ${serie.unit}` : ""}</b> | |
| 144 | + {serie.compare?.[hi] && !hide.cmp ? <span style={{ color: "var(--ink-3)" }}> · N-1 : {fmtNum(serie.compare[hi].v)}</span> : null} | |
| 145 | + </p> | |
| 146 | + )} | |
| 147 | + </figure> | |
| 148 | + ); | |
| 149 | +} | |
| 150 | + | |
| 151 | +function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off: boolean; dashed?: boolean; onClick: () => void }) { | |
| 152 | + return ( | |
| 153 | + <button type="button" onClick={onClick} aria-pressed={!off} | |
| 154 | + style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: "pointer", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}> | |
| 155 | + <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} /> | |
| 156 | + {label} | |
| 157 | + </button> | |
| 158 | + ); | |
| 159 | +} | |
| 160 | + | |
| 161 | +/* ---------- Barres horizontales (répartitions, géo) ---------- */ | |
| 162 | +export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) { | |
| 163 | + const rows = (items ?? []).slice(0, 14); | |
| 164 | + if (!rows.length) return <EmptyBlock title={title} />; | |
| 165 | + const max = Math.max(...rows.map((r) => r.value), 1); | |
| 166 | + return ( | |
| 167 | + <figure className="card" style={{ margin: 0, padding: 16 }}> | |
| 168 | + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b></figcaption> | |
| 169 | + <div style={{ marginTop: 12, display: "grid", gap: 9 }}> | |
| 170 | + {rows.map((r) => ( | |
| 171 | + <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}> | |
| 172 | + <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}> | |
| 173 | + <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span> | |
| 174 | + <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b> | |
| 175 | + </div> | |
| 176 | + <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}> | |
| 177 | + <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" }} /> | |
| 178 | + </div> | |
| 179 | + </div> | |
| 180 | + ))} | |
| 181 | + </div> | |
| 182 | + </figure> | |
| 183 | + ); | |
| 184 | +} | |
| 185 | + | |
| 186 | +/* ---------- Anneau ---------- */ | |
| 187 | +export function Donut({ title, items }: { title: string; items: BreakItem[] }) { | |
| 188 | + const rows = (items ?? []).filter((i) => i.value > 0).slice(0, 8); | |
| 189 | + const total = rows.reduce((s, r) => s + r.value, 0); | |
| 190 | + if (!total) return <EmptyBlock title={title} />; | |
| 191 | + const R = 74, C = 2 * Math.PI * R; | |
| 192 | + let acc = 0; | |
| 193 | + const shades = [1, 0.78, 0.58, 0.42, 0.3, 0.22, 0.15, 0.1]; | |
| 194 | + return ( | |
| 195 | + <figure className="card" style={{ margin: 0, padding: 16 }}> | |
| 196 | + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b></figcaption> | |
| 197 | + <div style={{ display: "flex", flexWrap: "wrap", gap: 18, alignItems: "center", marginTop: 12 }}> | |
| 198 | + <svg viewBox="0 0 200 200" style={{ width: 180, maxWidth: "100%" }} role="img" aria-label={title}> | |
| 199 | + {rows.map((r, i) => { | |
| 200 | + const frac = r.value / total; | |
| 201 | + const off = acc; acc += frac; | |
| 202 | + return ( | |
| 203 | + <circle key={r.label} cx={100} cy={100} r={R} fill="none" | |
| 204 | + stroke="var(--accent)" strokeOpacity={shades[i % shades.length]} | |
| 205 | + strokeWidth={30} strokeDasharray={`${frac * C} ${C}`} strokeDashoffset={-off * C} | |
| 206 | + transform="rotate(-90 100 100)"> | |
| 207 | + <title>{`${r.label} — ${fmtNum(r.value)} (${((100 * r.value) / total).toFixed(1)} %)`}</title> | |
| 208 | + </circle> | |
| 209 | + ); | |
| 210 | + })} | |
| 211 | + <circle cx={100} cy={100} r={R} fill="none" stroke="var(--ink)" strokeWidth={1} opacity={0.5} /> | |
| 212 | + </svg> | |
| 213 | + <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "grid", gap: 6, minWidth: 200, flex: 1 }}> | |
| 214 | + {rows.map((r, i) => ( | |
| 215 | + <li key={r.label} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}> | |
| 216 | + <span style={{ width: 11, height: 11, borderRadius: 3, border: "1px solid var(--ink)", background: "var(--accent)", opacity: shades[i % shades.length] }} /> | |
| 217 | + <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span> | |
| 218 | + <b style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}>{((100 * r.value) / total).toFixed(1)} %</b> | |
| 219 | + </li> | |
| 220 | + ))} | |
| 221 | + </ul> | |
| 222 | + </div> | |
| 223 | + </figure> | |
| 224 | + ); | |
| 225 | +} | |
| 226 | + | |
| 227 | +/* ---------- Calendrier de chaleur ---------- */ | |
| 228 | +export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) { | |
| 229 | + if (!cells?.length) return <EmptyBlock title={title} />; | |
| 230 | + const byDate = new Map(cells.map((c) => [c.date, c.value])); | |
| 231 | + const dates = cells.map((c) => c.date).sort(); | |
| 232 | + const end = new Date(dates[dates.length - 1] + "T12:00:00"); | |
| 233 | + const max = Math.max(...cells.map((c) => c.value), 1); | |
| 234 | + const weeks = 26, cols: { date: string; v: number }[][] = []; | |
| 235 | + const cur = new Date(end); | |
| 236 | + cur.setDate(cur.getDate() - (weeks * 7 - 1)); | |
| 237 | + for (let w = 0; w < weeks; w++) { | |
| 238 | + const col: { date: string; v: number }[] = []; | |
| 239 | + for (let d = 0; d < 7; d++) { | |
| 240 | + const iso = cur.toISOString().slice(0, 10); | |
| 241 | + col.push({ date: iso, v: byDate.get(iso) ?? 0 }); | |
| 242 | + cur.setDate(cur.getDate() + 1); | |
| 243 | + } | |
| 244 | + cols.push(col); | |
| 245 | + } | |
| 246 | + return ( | |
| 247 | + <figure className="card" style={{ margin: 0, padding: 16 }}> | |
| 248 | + <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b> <span className="klabel">26 dernières semaines</span></figcaption> | |
| 249 | + <div className="tbl-wrap" style={{ marginTop: 12 }}> | |
| 250 | + <svg viewBox={`0 0 ${weeks * 14} ${7 * 14}`} style={{ minWidth: 480, width: "100%", height: "auto" }} role="img" aria-label={title}> | |
| 251 | + {cols.map((col, w) => col.map((c, d) => ( | |
| 252 | + <rect key={c.date} x={w * 14} y={d * 14} width={12} height={12} rx={2.5} | |
| 253 | + fill={c.v ? "var(--accent)" : "rgba(20,24,20,0.07)"} fillOpacity={c.v ? 0.25 + 0.75 * (c.v / max) : 1} | |
| 254 | + stroke="rgba(20,24,20,0.15)" strokeWidth={0.5}> | |
| 255 | + <title>{`${c.date} — ${fmtNum(c.v)}`}</title> | |
| 256 | + </rect> | |
| 257 | + )))} | |
| 258 | + </svg> | |
| 259 | + </div> | |
| 260 | + </figure> | |
| 261 | + ); | |
| 262 | +} | |
| 263 | + | |
| 264 | +/* ---------- Tableau : tri, recherche, pagination ---------- */ | |
| 265 | +export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) { | |
| 266 | + const [q, setQ] = useState(""); | |
| 267 | + const [sort, setSort] = useState<{ col: number; dir: 1 | -1 } | null>(null); | |
| 268 | + const [page, setPage] = useState(0); | |
| 269 | + const rows = useMemo(() => { | |
| 270 | + let r = spec.rows ?? []; | |
| 271 | + if (q) r = r.filter((row) => row.some((c) => String(c).toLowerCase().includes(q.toLowerCase()))); | |
| 272 | + if (sort) r = [...r].sort((a, b) => { | |
| 273 | + const x = a[sort.col], y = b[sort.col]; | |
| 274 | + const nx = typeof x === "number" ? x : parseFloat(String(x).replace(/[^\d.,-]/g, "").replace(",", ".")); | |
| 275 | + const ny = typeof y === "number" ? y : parseFloat(String(y).replace(/[^\d.,-]/g, "").replace(",", ".")); | |
| 276 | + if (!Number.isNaN(nx) && !Number.isNaN(ny)) return (nx - ny) * sort.dir; | |
| 277 | + return String(x).localeCompare(String(y), "fr") * sort.dir; | |
| 278 | + }); | |
| 279 | + return r; | |
| 280 | + }, [spec.rows, q, sort]); | |
| 281 | + const pages = Math.max(1, Math.ceil(rows.length / pageSize)); | |
| 282 | + const cur = Math.min(page, pages - 1); | |
| 283 | + return ( | |
| 284 | + <section className="card" style={{ padding: 16 }}> | |
| 285 | + <div style={{ display: "flex", flexWrap: "wrap", gap: 10, justifyContent: "space-between", alignItems: "center" }}> | |
| 286 | + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{spec.title}</b> | |
| 287 | + <input className="input" style={{ maxWidth: 240 }} placeholder="Rechercher…" value={q} | |
| 288 | + onChange={(e) => { setQ(e.target.value); setPage(0); }} aria-label={`Rechercher dans ${spec.title}`} /> | |
| 289 | + </div> | |
| 290 | + <div className="tbl-wrap" style={{ marginTop: 10 }}> | |
| 291 | + <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}> | |
| 292 | + <thead> | |
| 293 | + <tr> | |
| 294 | + {spec.columns.map((c, i) => ( | |
| 295 | + <th key={c} onClick={() => setSort((s) => ({ col: i, dir: s?.col === i && s.dir === 1 ? -1 : 1 }))} | |
| 296 | + style={{ cursor: "pointer", textAlign: "left", padding: "8px 10px", background: "var(--ink)", color: "var(--paper)", fontFamily: "var(--font-mono)", fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", whiteSpace: "nowrap", userSelect: "none" }} | |
| 297 | + aria-sort={sort?.col === i ? (sort.dir === 1 ? "ascending" : "descending") : "none"}> | |
| 298 | + {c} {sort?.col === i ? (sort.dir === 1 ? "▲" : "▼") : "↕"} | |
| 299 | + </th> | |
| 300 | + ))} | |
| 301 | + </tr> | |
| 302 | + </thead> | |
| 303 | + <tbody> | |
| 304 | + {rows.slice(cur * pageSize, (cur + 1) * pageSize).map((row, ri) => ( | |
| 305 | + <tr key={ri} style={{ background: ri % 2 ? "var(--surface-2)" : "var(--surface)" }}> | |
| 306 | + {row.map((c, ci) => ( | |
| 307 | + <td key={ci} style={{ padding: "7px 10px", borderBottom: "1px solid var(--line)", whiteSpace: "nowrap" }}> | |
| 308 | + {typeof c === "number" ? fmtNum(c) : c} | |
| 309 | + </td> | |
| 310 | + ))} | |
| 311 | + </tr> | |
| 312 | + ))} | |
| 313 | + </tbody> | |
| 314 | + </table> | |
| 315 | + </div> | |
| 316 | + <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10, flexWrap: "wrap", gap: 8 }}> | |
| 317 | + <span className="klabel">{fmtInt(rows.length)} lignes</span> | |
| 318 | + <span style={{ display: "flex", gap: 6 }}> | |
| 319 | + <button type="button" className="btn btn-ghost" disabled={cur === 0} onClick={() => setPage(cur - 1)}>←</button> | |
| 320 | + <span className="chip">{cur + 1} / {pages}</span> | |
| 321 | + <button type="button" className="btn btn-ghost" disabled={cur >= pages - 1} onClick={() => setPage(cur + 1)}>→</button> | |
| 322 | + </span> | |
| 323 | + </div> | |
| 324 | + </section> | |
| 325 | + ); | |
| 326 | +} | |
| 327 | + | |
| 328 | +/* ---------- Records / faits marquants ---------- */ | |
| 329 | +export function RecordCard({ r }: { r: RecordFact }) { | |
| 330 | + return ( | |
| 331 | + <article className="card" style={{ padding: "12px 16px", display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline", background: "var(--surface-2)" }}> | |
| 332 | + <span style={{ fontSize: 13, color: "var(--ink-2)" }}>{r.label}</span> | |
| 333 | + <span style={{ textAlign: "right" }}> | |
| 334 | + <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{r.value}</b> | |
| 335 | + {r.date && <span className="klabel" style={{ display: "block" }}>{r.date}</span>} | |
| 336 | + </span> | |
| 337 | + </article> | |
| 338 | + ); | |
| 339 | +} | |
| 340 | + | |
| 341 | +/* ---------- Bouton PDF ---------- */ | |
| 342 | +export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) { | |
| 343 | + const [busy, setBusy] = useState(false); | |
| 344 | + const url = (mode: string) => { | |
| 345 | + const p = new URLSearchParams({ period, mode }); | |
| 346 | + if (from) p.set("from", from); | |
| 347 | + if (to) p.set("to", to); | |
| 348 | + return `${endpoint}?${p}`; | |
| 349 | + }; | |
| 350 | + const dl = (mode: string) => { | |
| 351 | + setBusy(true); | |
| 352 | + const a = document.createElement("a"); | |
| 353 | + a.href = url(mode); | |
| 354 | + a.download = ""; | |
| 355 | + document.body.appendChild(a); | |
| 356 | + a.click(); | |
| 357 | + a.remove(); | |
| 358 | + setTimeout(() => setBusy(false), 2500); | |
| 359 | + }; | |
| 360 | + return ( | |
| 361 | + <span style={{ display: "inline-flex", gap: 8, flexWrap: "wrap" }}> | |
| 362 | + <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={busy}> | |
| 363 | + {busy ? "Génération…" : "⬇ Télécharger le rapport PDF"} | |
| 364 | + </button> | |
| 365 | + <button type="button" className="btn btn-ghost" onClick={() => dl("synthese")} disabled={busy}> | |
| 366 | + Synthèse (2 p.) | |
| 367 | + </button> | |
| 368 | + </span> | |
| 369 | + ); | |
| 370 | +} | |
| 371 | + | |
| 372 | +/* ---------- États ---------- */ | |
| 373 | +export function EmptyBlock({ title }: { title: string }) { | |
| 374 | + return ( | |
| 375 | + <div className="card" style={{ padding: 20, background: "var(--surface-2)", borderStyle: "dashed" }}> | |
| 376 | + <b style={{ fontFamily: "var(--font-display)", fontSize: 14 }}>{title}</b> | |
| 377 | + <p className="klabel" style={{ margin: "6px 0 0" }}>Pas encore mesuré — aucune donnée disponible pour cette période.</p> | |
| 378 | + </div> | |
| 379 | + ); | |
| 380 | +} | |
| 381 | + | |
| 382 | +export function Fraicheur({ updated, onRefresh }: { updated: string; onRefresh: () => void }) { | |
| 383 | + return ( | |
| 384 | + <p style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap", margin: 0 }}> | |
| 385 | + <span className="klabel">Mis à jour le {new Date(updated).toLocaleString("fr-CA", { dateStyle: "medium", timeStyle: "short" })}</span> | |
| 386 | + <button type="button" className="btn btn-ghost" onClick={onRefresh}>↻ Rafraîchir</button> | |
| 387 | + </p> | |
| 388 | + ); | |
| 389 | +} | |
added
frontend/src/ka/stats/kapdf.py
+558 −0
@@ -0,0 +1,558 @@ | ||
| 1 | +# Auteur : Simon-Pierre Boucher — contact@spboucher.ai | |
| 2 | +# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2). | |
| 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. | |
| 6 | +# Usage : | |
| 7 | +# from kapdf import GroupeKAReport | |
| 8 | +# pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00", | |
| 9 | +# "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json, | |
| 10 | +# mode="complet").build() | |
| 11 | +# Dépendance : pip install fpdf2 (aucune autre) | |
| 12 | +from __future__ import annotations | |
| 13 | + | |
| 14 | +import math | |
| 15 | +from datetime import datetime | |
| 16 | +from zoneinfo import ZoneInfo | |
| 17 | + | |
| 18 | +from fpdf import FPDF | |
| 19 | + | |
| 20 | +INK = (20, 24, 20) | |
| 21 | +INK2 = (77, 85, 81) | |
| 22 | +INK3 = (139, 146, 140) | |
| 23 | +PAPER = (245, 243, 238) | |
| 24 | +SURFACE2 = (250, 249, 245) | |
| 25 | +GREEN = (28, 92, 65) | |
| 26 | +DANGER = (179, 66, 58) | |
| 27 | +WHITE = (255, 255, 255) | |
| 28 | + | |
| 29 | +EMAILS = [ | |
| 30 | + ("contact@groupe-ka.com", "Projets, partenariats & données"), | |
| 31 | + ("info@groupe-ka.com", "Médias & questions générales"), | |
| 32 | + ("admin@groupe-ka.com", "Légal, vie privée & Loi 25"), | |
| 33 | +] | |
| 34 | +DISCLAIMER = ( | |
| 35 | + "Groupe KA est un agrégateur de contenu : nous ne vendons rien, ne louons " | |
| 36 | + "rien et ne sommes partie à aucune transaction. Données lues à la source, " | |
| 37 | + "rien d'inventé, tout est traçable." | |
| 38 | +) | |
| 39 | + | |
| 40 | + | |
| 41 | +def _hex(c: str) -> tuple[int, int, int]: | |
| 42 | + c = c.lstrip("#") | |
| 43 | + return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore | |
| 44 | + | |
| 45 | + | |
| 46 | +def _fr(n) -> str: | |
| 47 | + if isinstance(n, float) and not n.is_integer(): | |
| 48 | + return f"{n:,.2f}".replace(",", " ").replace(".", ",") | |
| 49 | + return f"{int(n):,}".replace(",", " ") | |
| 50 | + | |
| 51 | + | |
| 52 | +_SUBST = { | |
| 53 | + "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-", | |
| 54 | + "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"', | |
| 55 | + "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", | |
| 56 | +} | |
| 57 | + | |
| 58 | + | |
| 59 | +def _latin1(s: str) -> str: | |
| 60 | + for k, v in _SUBST.items(): | |
| 61 | + s = s.replace(k, v) | |
| 62 | + return s.encode("latin-1", "replace").decode("latin-1") | |
| 63 | + | |
| 64 | + | |
| 65 | +class _PDF(FPDF): | |
| 66 | + """FPDF avec en-tête/pied Groupe-KA sur chaque page (sauf couverture). | |
| 67 | + Les polices core sont latin-1 : normalize_text sanitise en amont.""" | |
| 68 | + | |
| 69 | + def normalize_text(self, text): | |
| 70 | + return super().normalize_text(_latin1(text)) | |
| 71 | + | |
| 72 | + def __init__(self, brand: str, accent: tuple, period_label: str): | |
| 73 | + super().__init__(orientation="P", unit="mm", format="A4") | |
| 74 | + self.brand = brand | |
| 75 | + self.accent = accent | |
| 76 | + self.period_label = period_label | |
| 77 | + self.cover_mode = False | |
| 78 | + self.set_margins(18, 20, 18) | |
| 79 | + self.set_auto_page_break(True, margin=22) | |
| 80 | + | |
| 81 | + def header(self): | |
| 82 | + if self.cover_mode: | |
| 83 | + return | |
| 84 | + self.set_font("helvetica", "B", 8.5) | |
| 85 | + self.set_text_color(*INK) | |
| 86 | + self.set_xy(18, 9) | |
| 87 | + self.cell(0, 5, f"Groupe KA · {self.brand}") | |
| 88 | + self.set_font("helvetica", "", 8) | |
| 89 | + self.set_text_color(*INK3) | |
| 90 | + self.set_xy(18, 9) | |
| 91 | + self.cell(0, 5, "Rapport statistique", align="R") | |
| 92 | + self.set_draw_color(*INK) | |
| 93 | + self.set_line_width(0.5) | |
| 94 | + self.line(18, 15.5, 192, 15.5) | |
| 95 | + self.set_y(20) | |
| 96 | + | |
| 97 | + def footer(self): | |
| 98 | + if self.cover_mode: | |
| 99 | + return | |
| 100 | + self.set_y(-15) | |
| 101 | + self.set_draw_color(*INK3) | |
| 102 | + self.set_line_width(0.2) | |
| 103 | + self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5) | |
| 104 | + self.set_font("helvetica", "", 7.5) | |
| 105 | + self.set_text_color(*INK3) | |
| 106 | + year = datetime.now(ZoneInfo("America/Toronto")).year | |
| 107 | + self.cell(130, 5, f"© Groupe-KA — {year} — groupe-ka.com · {self.period_label}") | |
| 108 | + self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R") | |
| 109 | + | |
| 110 | + | |
| 111 | +class GroupeKAReport: | |
| 112 | + def __init__(self, site: dict, dashboard: dict, mode: str = "complet"): | |
| 113 | + self.site = site | |
| 114 | + self.d = dashboard | |
| 115 | + self.mode = mode | |
| 116 | + self.accent = _hex(site.get("accent", "#d9f26b")) | |
| 117 | + period = dashboard.get("period", {}) or {} | |
| 118 | + self.period_label = period.get("label") or "toute la période" | |
| 119 | + self.pdf = _PDF(site.get("wordmark", ""), self.accent, self.period_label) | |
| 120 | + self.toc: list[tuple[str, int]] = [] | |
| 121 | + | |
| 122 | + # ---------- primitives ---------- | |
| 123 | + def _card(self, x, y, w, h, fill=WHITE): | |
| 124 | + p = self.pdf | |
| 125 | + p.set_draw_color(*INK) | |
| 126 | + p.set_line_width(0.45) | |
| 127 | + p.set_fill_color(*fill) | |
| 128 | + p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2) | |
| 129 | + | |
| 130 | + def _kicker(self, text): | |
| 131 | + p = self.pdf | |
| 132 | + p.set_font("helvetica", "B", 8) | |
| 133 | + p.set_text_color(*GREEN) | |
| 134 | + p.set_draw_color(*GREEN) | |
| 135 | + p.set_line_width(0.6) | |
| 136 | + y = p.get_y() + 2 | |
| 137 | + p.line(p.l_margin, y, p.l_margin + 7, y) | |
| 138 | + p.set_xy(p.l_margin + 9, y - 2.5) | |
| 139 | + p.cell(0, 5, text.upper()) | |
| 140 | + p.ln(8) | |
| 141 | + | |
| 142 | + def _section_title(self, title): | |
| 143 | + if self.pdf.get_y() > 240: | |
| 144 | + self.pdf.add_page() | |
| 145 | + self._kicker("Groupe KA · " + self.site.get("wordmark", "")) | |
| 146 | + self.pdf.set_font("helvetica", "B", 15) | |
| 147 | + self.pdf.set_text_color(*INK) | |
| 148 | + self.pdf.set_x(self.pdf.l_margin) | |
| 149 | + self.pdf.cell(0, 8, title) | |
| 150 | + self.toc.append((title, self.pdf.page_no())) | |
| 151 | + self.pdf.ln(11) | |
| 152 | + | |
| 153 | + # ---------- pages ---------- | |
| 154 | + def _cover(self): | |
| 155 | + p = self.pdf | |
| 156 | + p.cover_mode = True | |
| 157 | + p.set_auto_page_break(False) | |
| 158 | + p.add_page() | |
| 159 | + p.set_fill_color(*PAPER) | |
| 160 | + p.rect(0, 0, 210, 297, style="F") | |
| 161 | + p.set_draw_color(*INK) | |
| 162 | + p.set_line_width(1.0) | |
| 163 | + p.rect(10, 10, 190, 277) | |
| 164 | + # kicker | |
| 165 | + p.set_font("helvetica", "B", 10) | |
| 166 | + p.set_text_color(*GREEN) | |
| 167 | + p.set_xy(24, 34) | |
| 168 | + p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE") | |
| 169 | + # wordmark : partie gauche + boîte encre/accent | |
| 170 | + wm = self.site.get("wordmark", "") | |
| 171 | + left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None) | |
| 172 | + p.set_xy(24, 70) | |
| 173 | + p.set_font("helvetica", "B", 40) | |
| 174 | + p.set_text_color(*INK) | |
| 175 | + p.cell(p.get_string_width(left) + 2, 20, left) | |
| 176 | + if boxed: | |
| 177 | + bw = p.get_string_width(boxed) + 12 | |
| 178 | + x = p.get_x() + 2 | |
| 179 | + p.set_fill_color(*INK) | |
| 180 | + p.rect(x, 68, bw, 22, style="F", round_corners=True, corner_radius=3) | |
| 181 | + p.set_text_color(*self.accent) | |
| 182 | + p.set_xy(x + 6, 70) | |
| 183 | + p.cell(bw - 12, 18, boxed) | |
| 184 | + p.set_xy(24, 100) | |
| 185 | + p.set_font("helvetica", "", 13) | |
| 186 | + p.set_text_color(*INK2) | |
| 187 | + p.multi_cell(150, 7, f"Rapport statistique — {wm}") | |
| 188 | + now = datetime.now(ZoneInfo("America/Toronto")) | |
| 189 | + per = self.d.get("period", {}) or {} | |
| 190 | + p.set_xy(24, 125) | |
| 191 | + p.set_font("helvetica", "", 10.5) | |
| 192 | + rows = [ | |
| 193 | + ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")), | |
| 194 | + ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"), | |
| 195 | + ("Plateforme", "https://" + self.site.get("domain", "")), | |
| 196 | + ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"), | |
| 197 | + ] | |
| 198 | + y = 128 | |
| 199 | + for k, v in rows: | |
| 200 | + p.set_xy(24, y) | |
| 201 | + p.set_text_color(*INK3) | |
| 202 | + p.cell(40, 6, k) | |
| 203 | + p.set_text_color(*INK) | |
| 204 | + p.set_font("helvetica", "B", 10.5) | |
| 205 | + p.cell(0, 6, str(v)) | |
| 206 | + p.set_font("helvetica", "", 10.5) | |
| 207 | + y += 8 | |
| 208 | + # bande encre au pied | |
| 209 | + p.set_fill_color(*INK) | |
| 210 | + p.rect(10, 262, 190, 25, style="F") | |
| 211 | + p.set_xy(24, 270) | |
| 212 | + p.set_font("helvetica", "B", 12) | |
| 213 | + p.set_text_color(*WHITE) | |
| 214 | + p.cell(60, 8, "par Groupe ") | |
| 215 | + p.set_text_color(*self.accent) | |
| 216 | + p.set_xy(24 + p.get_string_width("par Groupe ") + 1, 270) | |
| 217 | + p.cell(20, 8, "KA") | |
| 218 | + p.set_font("helvetica", "B", 10) | |
| 219 | + p.set_xy(24, 270) | |
| 220 | + p.set_text_color(*self.accent) | |
| 221 | + p.cell(162, 8, "groupe-ka.com", align="R") | |
| 222 | + p.set_auto_page_break(True, margin=22) | |
| 223 | + p.cover_mode = False | |
| 224 | + | |
| 225 | + def _kpis(self): | |
| 226 | + kpis = self.d.get("kpis") or [] | |
| 227 | + if not kpis: | |
| 228 | + return | |
| 229 | + self._section_title("Synthèse des indicateurs") | |
| 230 | + p = self.pdf | |
| 231 | + cols, gw, gh, gap = 3, 56, 26, 3 | |
| 232 | + x0, y = p.l_margin, p.get_y() | |
| 233 | + for i, k in enumerate(kpis[:9]): | |
| 234 | + x = x0 + (i % cols) * (gw + gap) | |
| 235 | + if i and i % cols == 0: | |
| 236 | + y += gh + gap | |
| 237 | + if y > 250: | |
| 238 | + p.add_page(); y = p.get_y() | |
| 239 | + self._card(x, y, gw, gh) | |
| 240 | + p.set_xy(x + 4, y + 4) | |
| 241 | + p.set_font("helvetica", "B", 14) | |
| 242 | + p.set_text_color(*INK) | |
| 243 | + val = k.get("value") | |
| 244 | + p.cell(gw - 8, 7, (_fr(val) if isinstance(val, (int, float)) else str(val)) + (" " + k["unit"] if k.get("unit") else "")) | |
| 245 | + p.set_xy(x + 4, y + 12) | |
| 246 | + p.set_font("helvetica", "", 7.6) | |
| 247 | + p.set_text_color(*INK2) | |
| 248 | + p.multi_cell(gw - 8, 3.6, str(k.get("label", ""))[:70]) | |
| 249 | + if k.get("delta_pct") is not None: | |
| 250 | + up = (k.get("direction") or ("up" if k["delta_pct"] >= 0 else "down")) == "up" | |
| 251 | + p.set_xy(x + 4, y + gh - 6.5) | |
| 252 | + p.set_font("helvetica", "B", 8) | |
| 253 | + p.set_text_color(*(GREEN if up else DANGER)) | |
| 254 | + 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.") | |
| 256 | + p.set_y(y + gh + 8) | |
| 257 | + | |
| 258 | + def _line_chart(self, s): | |
| 259 | + p = self.pdf | |
| 260 | + pts = s.get("points") or [] | |
| 261 | + if len(pts) < 2: | |
| 262 | + return | |
| 263 | + if p.get_y() > 200: | |
| 264 | + 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) | |
| 269 | + x0, y0, w, h = p.l_margin, p.get_y(), 174, 52 | |
| 270 | + self._card(x0, y0, w, h, fill=WHITE) | |
| 271 | + cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16 | |
| 272 | + vals = [pt["v"] for pt in pts] + [c["v"] for c in (s.get("compare") or [])] | |
| 273 | + vmax = max(vals) or 1 | |
| 274 | + vmin = min(0, min(vals)) | |
| 275 | + rng = (vmax - vmin) or 1 | |
| 276 | + # grille + graduations | |
| 277 | + p.set_font("helvetica", "", 6.3) | |
| 278 | + p.set_text_color(*INK3) | |
| 279 | + p.set_draw_color(200, 200, 195) | |
| 280 | + p.set_line_width(0.15) | |
| 281 | + for g in range(5): | |
| 282 | + gy = cy + ch - ch * g / 4 | |
| 283 | + p.line(cx, gy, cx + cw, gy) | |
| 284 | + p.set_xy(x0 + 1, gy - 1.6) | |
| 285 | + p.cell(10, 3, _fr(vmin + rng * g / 4), align="R") | |
| 286 | + | |
| 287 | + def draw(series, color, width, dash=None): | |
| 288 | + n = len(series) | |
| 289 | + p.set_draw_color(*color) | |
| 290 | + p.set_line_width(width) | |
| 291 | + if dash: | |
| 292 | + p.set_dash_pattern(dash=1.2, gap=1.2) | |
| 293 | + last = None | |
| 294 | + for i, pt in enumerate(series): | |
| 295 | + px = cx + cw * (i / (n - 1)) | |
| 296 | + py = cy + ch - ch * ((pt["v"] - vmin) / rng) | |
| 297 | + if last: | |
| 298 | + p.line(last[0], last[1], px, py) | |
| 299 | + last = (px, py) | |
| 300 | + p.set_dash_pattern() | |
| 301 | + | |
| 302 | + if s.get("compare"): | |
| 303 | + draw(s["compare"], INK3, 0.35, dash=True) | |
| 304 | + draw(pts, self.accent, 0.7) | |
| 305 | + # libellés d'axe X (premier / milieu / dernier) | |
| 306 | + p.set_text_color(*INK3) | |
| 307 | + for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)): | |
| 308 | + p.set_xy(cx + cw * frac - 9, cy + ch + 1.5) | |
| 309 | + p.cell(18, 3, str(pts[idx].get("t", ""))[:10], align="C") | |
| 310 | + p.set_y(y0 + h + 4) | |
| 311 | + if s.get("compare"): | |
| 312 | + p.set_font("helvetica", "", 6.8) | |
| 313 | + p.set_text_color(*INK3) | |
| 314 | + p.cell(0, 4, "— période courante (accent) · ---- période comparée") | |
| 315 | + p.ln(6) | |
| 316 | + else: | |
| 317 | + p.ln(2) | |
| 318 | + | |
| 319 | + def _bars(self, title, items, unit=""): | |
| 320 | + p = self.pdf | |
| 321 | + items = [it for it in (items or []) if isinstance(it.get("value"), (int, float))][:12] | |
| 322 | + if not items: | |
| 323 | + return | |
| 324 | + need = 10 + len(items) * 7 | |
| 325 | + if p.get_y() + need > 265: | |
| 326 | + 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) | |
| 331 | + vmax = max(it["value"] for it in items) or 1 | |
| 332 | + for it in items: | |
| 333 | + y = p.get_y() | |
| 334 | + p.set_font("helvetica", "", 7.6) | |
| 335 | + p.set_text_color(*INK) | |
| 336 | + p.set_x(p.l_margin) | |
| 337 | + p.cell(46, 5, str(it["label"])[:34]) | |
| 338 | + bw = 96 * (it["value"] / vmax) | |
| 339 | + p.set_fill_color(*self.accent) | |
| 340 | + p.set_draw_color(*INK) | |
| 341 | + p.set_line_width(0.25) | |
| 342 | + 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) | |
| 344 | + p.set_font("helvetica", "B", 7.6) | |
| 345 | + p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R") | |
| 346 | + p.ln(6.4) | |
| 347 | + p.ln(3) | |
| 348 | + | |
| 349 | + def _donut(self, b): | |
| 350 | + # anneau vectoriel simple (arcs) + légende | |
| 351 | + p = self.pdf | |
| 352 | + items = [it for it in (b.get("items") or []) if it.get("value")][:8] | |
| 353 | + total = sum(it["value"] for it in items) | |
| 354 | + if not items or not total: | |
| 355 | + return | |
| 356 | + if p.get_y() > 210: | |
| 357 | + 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) | |
| 362 | + 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 | + start = -90.0 | |
| 365 | + for i, it in enumerate(items): | |
| 366 | + 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)) | |
| 369 | + steps = max(2, int(72 * frac)) | |
| 370 | + p.set_fill_color(*col) | |
| 371 | + p.set_draw_color(*col) | |
| 372 | + for st in range(steps): | |
| 373 | + a0 = math.radians(start + 360 * frac * st / steps) | |
| 374 | + a1 = math.radians(start + 360 * frac * (st + 1) / steps) | |
| 375 | + p.polygon( | |
| 376 | + [(cx, cy), | |
| 377 | + (cx + r * math.cos(a0), cy + r * math.sin(a0)), | |
| 378 | + (cx + r * math.cos(a1), cy + r * math.sin(a1))], | |
| 379 | + style="DF", | |
| 380 | + ) | |
| 381 | + start += 360 * frac | |
| 382 | + p.set_fill_color(*WHITE) | |
| 383 | + p.set_draw_color(*INK) | |
| 384 | + p.set_line_width(0.4) | |
| 385 | + p.ellipse(cx - 11, cy - 11, 22, 22, style="DF") | |
| 386 | + p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D") | |
| 387 | + # légende | |
| 388 | + ly = cy - 22 | |
| 389 | + 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)) | |
| 392 | + p.set_fill_color(*col) | |
| 393 | + p.set_draw_color(*INK) | |
| 394 | + p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF") | |
| 395 | + p.set_xy(p.l_margin + 66, ly) | |
| 396 | + p.set_font("helvetica", "", 7.6) | |
| 397 | + p.set_text_color(*INK) | |
| 398 | + pct = 100 * it["value"] / total | |
| 399 | + p.cell(0, 5.6, f"{str(it['label'])[:40]} — {_fr(it['value'])} ({pct:.1f} %)".replace(".", ",")) | |
| 400 | + ly += 5.6 | |
| 401 | + p.set_y(max(cy + r, ly) + 6) | |
| 402 | + | |
| 403 | + def _table(self, t): | |
| 404 | + p = self.pdf | |
| 405 | + cols = t.get("columns") or [] | |
| 406 | + rows = t.get("rows") or [] | |
| 407 | + if not cols or not rows: | |
| 408 | + return | |
| 409 | + self._section_title(t.get("title", "Tableau")) | |
| 410 | + w = 174 / len(cols) | |
| 411 | + def head(): | |
| 412 | + p.set_font("helvetica", "B", 7.6) | |
| 413 | + p.set_fill_color(*INK) | |
| 414 | + p.set_text_color(*WHITE) | |
| 415 | + for c in cols: | |
| 416 | + p.cell(w, 6, " " + str(c)[:30], fill=True) | |
| 417 | + p.ln(6) | |
| 418 | + head() | |
| 419 | + p.set_text_color(*INK) | |
| 420 | + for i, row in enumerate(rows[:200]): | |
| 421 | + if p.get_y() > 262: | |
| 422 | + p.add_page() | |
| 423 | + head() | |
| 424 | + p.set_text_color(*INK) | |
| 425 | + p.set_font("helvetica", "", 7.4) | |
| 426 | + p.set_fill_color(*(SURFACE2 if i % 2 else WHITE)) | |
| 427 | + for cell in row: | |
| 428 | + txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell) | |
| 429 | + p.cell(w, 5.4, " " + txt[:34], fill=True) | |
| 430 | + p.ln(5.4) | |
| 431 | + if len(rows) > 200: | |
| 432 | + p.set_font("helvetica", "", 7) | |
| 433 | + p.set_text_color(*INK3) | |
| 434 | + p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées") | |
| 435 | + p.ln(6) | |
| 436 | + | |
| 437 | + def _records(self): | |
| 438 | + recs = self.d.get("records") or [] | |
| 439 | + if not recs: | |
| 440 | + return | |
| 441 | + self._section_title("Records & faits marquants") | |
| 442 | + p = self.pdf | |
| 443 | + for r in recs[:10]: | |
| 444 | + if p.get_y() > 258: | |
| 445 | + p.add_page() | |
| 446 | + y = p.get_y() | |
| 447 | + self._card(p.l_margin, y, 174, 11, fill=SURFACE2) | |
| 448 | + p.set_xy(p.l_margin + 4, y + 2) | |
| 449 | + p.set_font("helvetica", "", 8.6) | |
| 450 | + p.set_text_color(*INK2) | |
| 451 | + p.cell(96, 7, str(r.get("label", ""))[:70]) | |
| 452 | + p.set_font("helvetica", "B", 9) | |
| 453 | + p.set_text_color(*INK) | |
| 454 | + p.cell(52, 7, str(r.get("value", ""))[:36], align="R") | |
| 455 | + p.set_font("helvetica", "", 7.6) | |
| 456 | + p.set_text_color(*INK3) | |
| 457 | + p.cell(20, 7, str(r.get("date", "") or ""), align="R") | |
| 458 | + p.set_y(y + 13.5) | |
| 459 | + p.ln(4) | |
| 460 | + | |
| 461 | + def _final_page(self): | |
| 462 | + p = self.pdf | |
| 463 | + p.add_page() | |
| 464 | + self._kicker("Groupe KA · contact") | |
| 465 | + p.set_font("helvetica", "B", 15) | |
| 466 | + p.set_text_color(*INK) | |
| 467 | + p.cell(0, 8, "Coordonnées du Groupe KA") | |
| 468 | + p.ln(12) | |
| 469 | + for email, role in EMAILS: | |
| 470 | + p.set_font("helvetica", "B", 10.5) | |
| 471 | + p.set_text_color(*INK) | |
| 472 | + p.cell(0, 6, email) | |
| 473 | + p.ln(5.5) | |
| 474 | + p.set_font("helvetica", "", 8.6) | |
| 475 | + p.set_text_color(*INK3) | |
| 476 | + p.cell(0, 5, role) | |
| 477 | + p.ln(8) | |
| 478 | + p.ln(2) | |
| 479 | + p.set_font("helvetica", "B", 10) | |
| 480 | + p.set_text_color(*GREEN) | |
| 481 | + p.cell(0, 6, "groupe-ka.com — le portail de l'écosystème ·Ka") | |
| 482 | + p.ln(10) | |
| 483 | + p.set_draw_color(*self.accent) | |
| 484 | + p.set_line_width(0.8) | |
| 485 | + p.line(p.l_margin, p.get_y(), p.l_margin + 30, p.get_y()) | |
| 486 | + p.ln(4) | |
| 487 | + p.set_font("helvetica", "", 8.6) | |
| 488 | + p.set_text_color(*INK2) | |
| 489 | + p.multi_cell(160, 4.6, DISCLAIMER) | |
| 490 | + p.ln(4) | |
| 491 | + p.set_font("helvetica", "", 7.6) | |
| 492 | + p.set_text_color(*INK3) | |
| 493 | + p.multi_cell( | |
| 494 | + 160, 4.2, | |
| 495 | + "Mentions : rapport généré automatiquement à partir des données réelles de la " | |
| 496 | + "plateforme au moment indiqué en couverture. Conditions d'utilisation, politique " | |
| 497 | + "de confidentialité et protection des renseignements personnels (Loi 25) : " | |
| 498 | + "groupe-ka.com/conditions · /confidentialite · /loi-25.", | |
| 499 | + ) | |
| 500 | + | |
| 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 | |
| 505 | + | |
| 506 | + def build(self) -> bytes: | |
| 507 | + p = self.pdf | |
| 508 | + p.alias_nb_pages() | |
| 509 | + self._cover() | |
| 510 | + if self.mode == "synthese": | |
| 511 | + p.add_page() | |
| 512 | + self._kpis() | |
| 513 | + self._records() | |
| 514 | + self._final_page() | |
| 515 | + else: | |
| 516 | + p.add_page() | |
| 517 | + toc_page_no = p.page_no() | |
| 518 | + p.add_page() | |
| 519 | + 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")) | |
| 533 | + for t in self.d.get("tables") or []: | |
| 534 | + self._table(t) | |
| 535 | + self._records() | |
| 536 | + self._final_page() | |
| 537 | + # sommaire écrit sur la page réservée (page 2) | |
| 538 | + last_page = p.page | |
| 539 | + p.page = toc_page_no | |
| 540 | + p.set_y(22) | |
| 541 | + p.set_font("helvetica", "B", 15) | |
| 542 | + p.set_text_color(*INK) | |
| 543 | + p.cell(0, 8, "Sommaire") | |
| 544 | + p.ln(12) | |
| 545 | + p.set_font("helvetica", "", 9.5) | |
| 546 | + for title, page_no in self.toc: | |
| 547 | + p.set_text_color(*INK) | |
| 548 | + p.cell(140, 6.5, title[:80]) | |
| 549 | + p.set_text_color(*INK3) | |
| 550 | + p.cell(0, 6.5, str(page_no), align="R") | |
| 551 | + p.ln(6.5) | |
| 552 | + p.page = last_page | |
| 553 | + return bytes(p.output()) | |
| 554 | + | |
| 555 | + | |
| 556 | +def filename(platform_id: str, period: str) -> str: | |
| 557 | + today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d") | |
| 558 | + return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf" | |
modified
frontend/src/pages/Stats.tsx
+178 −785
@@ -1,824 +1,217 @@ | ||
| 1 | −import { useEffect, useMemo, useState } from 'react' | |
| 2 | −import { Link } from 'react-router-dom' | |
| 1 | +// ----------------------------------------------------------------------------- | |
| 2 | +// Fabri-Ka — page /stats : tableau de bord analytique (module ka-stats commun | |
| 3 | +// Groupe KA). Structure imposée par frontend/src/ka/stats/SPEC.md §1 : | |
| 4 | +// PDF en haut, bandeau KPI, sélecteur de période (refetch global), graphiques, | |
| 5 | +// géo, tableaux, records, fraîcheur. Données : GET /api/stats/dashboard. | |
| 6 | +// ----------------------------------------------------------------------------- | |
| 7 | +import { useCallback, useEffect, useState, type CSSProperties } from 'react' | |
| 3 | 8 | import { |
| 4 | − ExtendedStats, | |
| 5 | − fetchExtendedStats, | |
| 6 | − formatInt, | |
| 7 | − formatPrice, | |
| 8 | − formatPriceCompact, | |
| 9 | − GrowthPoint, | |
| 10 | − ORIGIN_KEYS, | |
| 11 | − ORIGIN_LABELS, | |
| 12 | − productPath, | |
| 13 | −} from '../api' | |
| 14 | −import CountUp from '../components/CountUp' | |
| 15 | −import EmptyState from '../components/EmptyState' | |
| 16 | −import { IconDownload } from '../components/Icons' | |
| 17 | −import OriginBadge from '../components/OriginBadge' | |
| 18 | −import Skeleton from '../components/Skeleton' | |
| 19 | −import StoreLogo from '../components/StoreLogo' | |
| 20 | − | |
| 21 | −const DEFAULT_TITLE = 'Fabri-Ka — Tous les produits québécois. Un seul endroit.' | |
| 22 | − | |
| 23 | −// --------------------------------------------------------------------------- | |
| 24 | −// Formatting helpers local to the stats page | |
| 25 | −// --------------------------------------------------------------------------- | |
| 26 | − | |
| 27 | −const percentFormatter = new Intl.NumberFormat('fr-CA', { | |
| 28 | − style: 'percent', | |
| 29 | − maximumFractionDigits: 1, | |
| 30 | −}) | |
| 31 | − | |
| 32 | −function formatShare(part: number, total: number): string { | |
| 33 | − if (!total) return '' | |
| 34 | − return percentFormatter.format(part / total) | |
| 35 | −} | |
| 36 | − | |
| 37 | −const dayFormatter = new Intl.DateTimeFormat('fr-CA', { | |
| 38 | − day: 'numeric', | |
| 39 | − month: 'short', | |
| 40 | −}) | |
| 41 | − | |
| 42 | −function formatDay(day: string): string { | |
| 43 | − const d = new Date(`${day}T00:00:00`) | |
| 44 | − return Number.isNaN(d.getTime()) ? day : dayFormatter.format(d) | |
| 9 | + BarChart, | |
| 10 | + BreakItem, | |
| 11 | + CalendarHeatmap, | |
| 12 | + DataTable, | |
| 13 | + Donut, | |
| 14 | + EmptyBlock, | |
| 15 | + Fraicheur, | |
| 16 | + Kpi, | |
| 17 | + KpiCard, | |
| 18 | + LineChart, | |
| 19 | + PdfButton, | |
| 20 | + PeriodSelector, | |
| 21 | + RecordCard, | |
| 22 | + RecordFact, | |
| 23 | + Serie, | |
| 24 | + TableSpec, | |
| 25 | +} from '../ka/stats/kacharts' | |
| 26 | + | |
| 27 | +type Breakdown = { id: string; title: string; kind?: 'donut' | 'bar'; items: BreakItem[] } | |
| 28 | +type Dashboard = { | |
| 29 | + updated: string | |
| 30 | + period: { from: string; to: string; label: string } | |
| 31 | + kpis: Kpi[] | |
| 32 | + series: Serie[] | |
| 33 | + breakdowns: Breakdown[] | |
| 34 | + geo?: { title: string; items: BreakItem[] } | |
| 35 | + heatmap?: { title: string; cells: { date: string; value: number }[] } | |
| 36 | + tables: TableSpec[] | |
| 37 | + records: RecordFact[] | |
| 45 | 38 | } |
| 46 | 39 | |
| 47 | −const BUCKET_LABELS: Record<string, string> = { | |
| 48 | − '0-10': 'Moins de 10 $', | |
| 49 | − '10-25': '10 – 25 $', | |
| 50 | − '25-50': '25 – 50 $', | |
| 51 | − '50-100': '50 – 100 $', | |
| 52 | − '100-250': '100 – 250 $', | |
| 53 | − '250-1000': '250 – 1 000 $', | |
| 54 | − '1000+': '1 000 $ et plus', | |
| 55 | −} | |
| 56 | − | |
| 57 | −const REPORT_URL = '/api/report.pdf' | |
| 58 | −const REPORT_HINT = 'Rapport de marché complet — PDF, mise à jour en continu' | |
| 59 | − | |
| 60 | −// Availability keys → French label + CSS slug (pine / muted / border) | |
| 61 | −const AVAILABILITY_META: Record< | |
| 62 | − string, | |
| 63 | − { label: string; slug: string; order: number } | |
| 64 | −> = { | |
| 65 | − 'en stock': { label: 'En stock', slug: 'stock', order: 0 }, | |
| 66 | − rupture: { label: 'En rupture', slug: 'rupture', order: 1 }, | |
| 67 | − inconnu: { label: 'Inconnu', slug: 'inconnu', order: 2 }, | |
| 40 | +const SECTION_TITLE: CSSProperties = { | |
| 41 | + fontFamily: 'var(--font-display)', | |
| 42 | + fontSize: 'clamp(18px, 2vw, 22px)', | |
| 43 | + letterSpacing: '-0.02em', | |
| 44 | + margin: '34px 0 14px', | |
| 68 | 45 | } |
| 69 | 46 | |
| 70 | −// --------------------------------------------------------------------------- | |
| 71 | −// Growth — hand-rolled SVG area chart (terracotta line on sand fill) | |
| 72 | −// --------------------------------------------------------------------------- | |
| 73 | − | |
| 74 | −function GrowthChart({ points }: { points: GrowthPoint[] }) { | |
| 75 | − // API returns the last 30 days DESC → plot ASC. | |
| 76 | − const asc = [...points].sort((a, b) => a.day.localeCompare(b.day)) | |
| 77 | − const W = 640 | |
| 78 | − const H = 200 | |
| 79 | − const PAD_X = 8 | |
| 80 | − const PAD_TOP = 26 | |
| 81 | − const PAD_BOTTOM = 26 | |
| 82 | − const innerW = W - PAD_X * 2 | |
| 83 | − const innerH = H - PAD_TOP - PAD_BOTTOM | |
| 84 | − const baseline = H - PAD_BOTTOM | |
| 85 | − | |
| 86 | − const max = Math.max(...asc.map((p) => p.n), 1) | |
| 87 | − const min = Math.min(...asc.map((p) => p.n)) | |
| 88 | − const x = (i: number) => | |
| 89 | − PAD_X + (asc.length > 1 ? (i * innerW) / (asc.length - 1) : innerW / 2) | |
| 90 | − const y = (n: number) => PAD_TOP + (1 - n / max) * innerH | |
| 91 | − | |
| 92 | − const line = asc | |
| 93 | − .map((p, i) => `${i === 0 ? 'M' : 'L'}${x(i).toFixed(1)},${y(p.n).toFixed(1)}`) | |
| 94 | − .join(' ') | |
| 95 | − const area = `${line} L${x(asc.length - 1).toFixed(1)},${baseline} L${x(0).toFixed(1)},${baseline} Z` | |
| 96 | − | |
| 97 | − const maxIdx = asc.findIndex((p) => p.n === max) | |
| 98 | − const minIdx = asc.findIndex((p) => p.n === min) | |
| 99 | − const clampX = (v: number) => Math.min(W - 30, Math.max(30, v)) | |
| 100 | − | |
| 101 | − return ( | |
| 102 | − <figure className="stats-growth-figure"> | |
| 103 | − <svg | |
| 104 | − viewBox={`0 0 ${W} ${H}`} | |
| 105 | − className="stats-growth-svg" | |
| 106 | − role="img" | |
| 107 | − aria-label={`Produits ajoutés par jour, du ${formatDay(asc[0].day)} au ${formatDay(asc[asc.length - 1].day)}. Maximum ${formatInt(max)}, minimum ${formatInt(min)}.`} | |
| 108 | − > | |
| 109 | − <line | |
| 110 | − x1={PAD_X} | |
| 111 | − y1={baseline} | |
| 112 | − x2={W - PAD_X} | |
| 113 | − y2={baseline} | |
| 114 | − className="stats-growth-baseline" | |
| 115 | − /> | |
| 116 | − <path d={area} className="stats-growth-area" /> | |
| 117 | − <path d={line} className="stats-growth-line" /> | |
| 118 | − | |
| 119 | − {/* min/max direct labels only — no axis machinery */} | |
| 120 | − <circle cx={x(maxIdx)} cy={y(max)} r={3.5} className="stats-growth-dot" /> | |
| 121 | − <text | |
| 122 | − x={clampX(x(maxIdx))} | |
| 123 | − y={y(max) - 9} | |
| 124 | − textAnchor="middle" | |
| 125 | − className="stats-growth-label" | |
| 126 | − > | |
| 127 | − {formatInt(max)} | |
| 128 | − </text> | |
| 129 | − {minIdx !== maxIdx && ( | |
| 130 | − <> | |
| 131 | − <circle | |
| 132 | − cx={x(minIdx)} | |
| 133 | − cy={y(min)} | |
| 134 | − r={3} | |
| 135 | − className="stats-growth-dot stats-growth-dot-min" | |
| 136 | − /> | |
| 137 | − <text | |
| 138 | − x={clampX(x(minIdx))} | |
| 139 | − y={Math.min(y(min) + 16, baseline - 4)} | |
| 140 | − textAnchor="middle" | |
| 141 | − className="stats-growth-label" | |
| 142 | − > | |
| 143 | − {formatInt(min)} | |
| 144 | − </text> | |
| 145 | − </> | |
| 146 | − )} | |
| 147 | − | |
| 148 | − <text x={PAD_X} y={H - 8} className="stats-growth-axis"> | |
| 149 | − {formatDay(asc[0].day)} | |
| 150 | − </text> | |
| 151 | − <text x={W - PAD_X} y={H - 8} textAnchor="end" className="stats-growth-axis"> | |
| 152 | − {formatDay(asc[asc.length - 1].day)} | |
| 153 | − </text> | |
| 154 | − | |
| 155 | − {/* hover layer: one generous hit target per point */} | |
| 156 | − {asc.map((p, i) => ( | |
| 157 | − <circle key={p.day} cx={x(i)} cy={y(p.n)} r={9} fill="transparent"> | |
| 158 | − <title>{`${formatDay(p.day)} — ${formatInt(p.n)} produit${p.n > 1 ? 's' : ''}`}</title> | |
| 159 | − </circle> | |
| 160 | − ))} | |
| 161 | − </svg> | |
| 162 | − </figure> | |
| 163 | − ) | |
| 164 | −} | |
| 165 | − | |
| 166 | −// --------------------------------------------------------------------------- | |
| 167 | −// Page | |
| 168 | −// --------------------------------------------------------------------------- | |
| 169 | − | |
| 170 | 47 | export default function Stats() { |
| 171 | − const [stats, setStats] = useState<ExtendedStats | null>(null) | |
| 48 | + const [period, setPeriod] = useState('30j') | |
| 49 | + const [custom, setCustom] = useState({ from: '', to: '' }) | |
| 50 | + const [dash, setDash] = useState<Dashboard | null>(null) | |
| 51 | + const [loading, setLoading] = useState(true) | |
| 172 | 52 | const [error, setError] = useState(false) |
| 173 | 53 | |
| 174 | − useEffect(() => { | |
| 175 | − const controller = new AbortController() | |
| 176 | − fetchExtendedStats(controller.signal) | |
| 177 | − .then(setStats) | |
| 178 | − .catch((err: unknown) => { | |
| 179 | − if (err instanceof DOMException && err.name === 'AbortError') return | |
| 180 | − setError(true) | |
| 181 | − }) | |
| 182 | − window.scrollTo({ top: 0 }) | |
| 183 | − return () => controller.abort() | |
| 184 | − }, []) | |
| 185 | − | |
| 186 | 54 | useEffect(() => { |
| 187 | 55 | document.title = 'Statistiques — Fabri-Ka' |
| 188 | 56 | return () => { |
| 189 | − document.title = DEFAULT_TITLE | |
| 57 | + document.title = 'Fabri-Ka — Tous les produits québécois. Un seul endroit.' | |
| 190 | 58 | } |
| 191 | 59 | }, []) |
| 192 | 60 | |
| 193 | − const generatedOn = useMemo( | |
| 194 | − () => | |
| 195 | − new Intl.DateTimeFormat('fr-CA', { dateStyle: 'long' }).format(new Date()), | |
| 196 | − [] | |
| 197 | − ) | |
| 61 | + const hasCustom = Boolean(custom.from && custom.to) | |
| 198 | 62 | |
| 199 | − if (error) { | |
| 200 | − return ( | |
| 201 | − <div className="page stats"> | |
| 202 | − <EmptyState | |
| 203 | − variant="error" | |
| 204 | − title="Statistiques indisponibles" | |
| 205 | − message="Impossible de charger les statistiques pour le moment. Réessayez dans quelques instants." | |
| 206 | − > | |
| 207 | − <Link className="btn btn-secondary" to="/"> | |
| 208 | − Retour à l'accueil | |
| 209 | − </Link> | |
| 210 | − </EmptyState> | |
| 211 | − </div> | |
| 212 | − ) | |
| 213 | − } | |
| 214 | − | |
| 215 | − const totals = stats?.totals | |
| 216 | − const bucketMax = stats | |
| 217 | − ? Math.max(...stats.price_buckets.map((b) => b.n), 1) | |
| 218 | − : 1 | |
| 219 | − const regionMax = stats | |
| 220 | − ? Math.max(...stats.by_region.map((r) => r.products), 1) | |
| 221 | − : 1 | |
| 222 | − // fixed A→E order (identity colors follow the entity, never its rank) | |
| 223 | − const originRows = stats | |
| 224 | − ? ORIGIN_KEYS.flatMap((key) => { | |
| 225 | − const stat = stats.by_origin.find((o) => o.key === key) | |
| 226 | − return stat && (stat.products > 0 || stat.stores > 0) | |
| 227 | − ? [{ key, stat }] | |
| 228 | − : [] | |
| 63 | + const load = useCallback(() => { | |
| 64 | + setLoading(true) | |
| 65 | + setError(false) | |
| 66 | + const p = new URLSearchParams({ period }) | |
| 67 | + if (hasCustom) { | |
| 68 | + p.set('from', custom.from) | |
| 69 | + p.set('to', custom.to) | |
| 70 | + } | |
| 71 | + fetch(`/api/stats/dashboard?${p}`) | |
| 72 | + .then((r) => { | |
| 73 | + if (!r.ok) throw new Error(String(r.status)) | |
| 74 | + return r.json() | |
| 229 | 75 | }) |
| 230 | − : [] | |
| 231 | − const originTotal = originRows.reduce((sum, r) => sum + r.stat.products, 0) | |
| 232 | − const catMax = stats | |
| 233 | − ? Math.max(...stats.by_category.map((c) => c.products), 1) | |
| 234 | − : 1 | |
| 76 | + .then((d: Dashboard) => setDash(d)) | |
| 77 | + .catch(() => setError(true)) | |
| 78 | + .finally(() => setLoading(false)) | |
| 79 | + }, [period, custom.from, custom.to, hasCustom]) | |
| 235 | 80 | |
| 236 | − const availabilityRows = stats | |
| 237 | − ? [...stats.availability] | |
| 238 | − .filter((a) => AVAILABILITY_META[a.key]) | |
| 239 | − .sort( | |
| 240 | − (a, b) => AVAILABILITY_META[a.key].order - AVAILABILITY_META[b.key].order | |
| 241 | − ) | |
| 242 | − : [] | |
| 243 | − const availabilityTotal = availabilityRows.reduce((sum, a) => sum + a.n, 0) | |
| 81 | + useEffect(() => { | |
| 82 | + load() | |
| 83 | + }, [load]) | |
| 244 | 84 | |
| 245 | − const coverageMeters = | |
| 246 | − stats && totals | |
| 247 | − ? [ | |
| 248 | − { | |
| 249 | − label: 'Produits avec image', | |
| 250 | − value: stats.coverage.with_image, | |
| 251 | − total: totals.products, | |
| 252 | − }, | |
| 253 | − { | |
| 254 | − label: 'Produits avec description', | |
| 255 | − value: stats.coverage.with_desc, | |
| 256 | − total: totals.products, | |
| 257 | − }, | |
| 258 | − { | |
| 259 | − label: 'Boutiques avec logo', | |
| 260 | − value: stats.coverage.with_logo, | |
| 261 | − total: totals.stores_registry, | |
| 262 | − }, | |
| 263 | − { | |
| 264 | − label: 'Boutiques géolocalisées', | |
| 265 | − value: stats.coverage.with_region, | |
| 266 | − total: totals.stores_registry, | |
| 267 | − }, | |
| 268 | − ].map((m) => ({ ...m, pct: m.total ? m.value / m.total : 0 })) | |
| 269 | − : [] | |
| 85 | + const donuts = dash?.breakdowns.filter((b) => b.kind === 'donut') ?? [] | |
| 86 | + const bars = dash?.breakdowns.filter((b) => b.kind !== 'donut') ?? [] | |
| 270 | 87 | |
| 271 | 88 | return ( |
| 272 | − <div className="page stats"> | |
| 273 | − {/* 1 — editorial header */} | |
| 274 | − <section className="stats-hero"> | |
| 275 | − <p className="hero-eyebrow">Statistiques</p> | |
| 276 | − <h1 className="stats-hero-title"> | |
| 277 | − Le Québec qui vend en ligne, <em>en chiffres.</em> | |
| 278 | − </h1> | |
| 279 | − <p className="stats-hero-sub"> | |
| 280 | − Portrait généré à partir des catalogues publics agrégés par Fabri-Ka — | |
| 281 | − données au {generatedOn}, recalculées en continu. Chaque chiffre est | |
| 282 | − vivant : il se met à jour à mesure que les boutiques se synchronisent. | |
| 283 | − Pour le détail complet, téléchargez le rapport de marché. | |
| 284 | − </p> | |
| 285 | − <div className="stats-hero-actions"> | |
| 286 | − <a | |
| 287 | − className="btn btn-primary stats-report-btn" | |
| 288 | − href={REPORT_URL} | |
| 289 | − download | |
| 290 | − > | |
| 291 | − <IconDownload size={18} /> | |
| 292 | − Télécharger le rapport PDF | |
| 293 | − </a> | |
| 294 | − <span className="stats-report-hint">{REPORT_HINT}</span> | |
| 89 | + <div className="page" style={{ maxWidth: 1160, margin: '0 auto', padding: '24px 16px 56px' }}> | |
| 90 | + {/* ---- en-tête : titre + bouton PDF bien visible (SPEC §1.8) ---- */} | |
| 91 | + <header | |
| 92 | + style={{ | |
| 93 | + display: 'flex', | |
| 94 | + flexWrap: 'wrap', | |
| 95 | + gap: 14, | |
| 96 | + alignItems: 'flex-end', | |
| 97 | + justifyContent: 'space-between', | |
| 98 | + marginBottom: 18, | |
| 99 | + }} | |
| 100 | + > | |
| 101 | + <div> | |
| 102 | + <p className="klabel" style={{ margin: 0 }}>Fabri·Ka · Groupe KA</p> | |
| 103 | + <h1 style={{ margin: '4px 0 0', fontSize: 'clamp(26px, 4vw, 38px)' }}>Statistiques</h1> | |
| 104 | + <p style={{ margin: '6px 0 0', color: 'var(--ink-2)', fontSize: 14 }}> | |
| 105 | + Le catalogue des produits québécois, mesuré en continu — volumes, prix, | |
| 106 | + catégories, régions et boutiques. | |
| 107 | + </p> | |
| 295 | 108 | </div> |
| 296 | − </section> | |
| 297 | − | |
| 298 | − {/* 2 — KPI tiles */} | |
| 299 | − <section className="stats-kpis" aria-label="Chiffres clés"> | |
| 300 | − {totals ? ( | |
| 301 | − <> | |
| 302 | − <div className="stats-kpi"> | |
| 303 | − <span className="stats-kpi-value"> | |
| 304 | − <CountUp value={totals.products} /> | |
| 305 | − </span> | |
| 306 | − <span className="stats-kpi-label">Produits</span> | |
| 307 | − <span className="stats-kpi-sub"> | |
| 308 | − {formatInt(totals.products_priced)} avec prix affiché | |
| 309 | − </span> | |
| 310 | − </div> | |
| 311 | − <div className="stats-kpi"> | |
| 312 | − <span className="stats-kpi-value"> | |
| 313 | − <CountUp value={totals.stores_live} /> | |
| 314 | − </span> | |
| 315 | − <span className="stats-kpi-label">Boutiques actives</span> | |
| 316 | − <span className="stats-kpi-sub"> | |
| 317 | − {formatShare(totals.stores_live, totals.stores_registry) || | |
| 318 | − '—'}{' '} | |
| 319 | − du registre | |
| 320 | − </span> | |
| 321 | − </div> | |
| 322 | − <div className="stats-kpi"> | |
| 323 | − <span className="stats-kpi-value"> | |
| 324 | − <CountUp value={totals.stores_registry} /> | |
| 325 | − </span> | |
| 326 | − <span className="stats-kpi-label">Boutiques au registre</span> | |
| 327 | − <span className="stats-kpi-sub">boutiques suivies</span> | |
| 328 | − </div> | |
| 329 | − <div className="stats-kpi"> | |
| 330 | − <span className="stats-kpi-value"> | |
| 331 | − <CountUp value={totals.regions} /> | |
| 332 | − </span> | |
| 333 | − <span className="stats-kpi-label">Régions</span> | |
| 334 | − <span className="stats-kpi-sub">du Québec couvertes</span> | |
| 335 | − </div> | |
| 336 | − <div className="stats-kpi"> | |
| 337 | − <span className="stats-kpi-value"> | |
| 338 | − {formatPrice(totals.price_median) || '—'} | |
| 339 | − </span> | |
| 340 | − <span className="stats-kpi-label">Prix médian</span> | |
| 341 | − <span className="stats-kpi-sub"> | |
| 342 | − sur {formatInt(totals.products_priced)} produits | |
| 343 | − </span> | |
| 344 | − </div> | |
| 345 | − <div className="stats-kpi"> | |
| 346 | − <span className="stats-kpi-value"> | |
| 347 | − {formatPrice(totals.price_avg) || '—'} | |
| 348 | − </span> | |
| 349 | − <span className="stats-kpi-label">Prix moyen</span> | |
| 350 | − <span className="stats-kpi-sub">panier type</span> | |
| 351 | − </div> | |
| 352 | − </> | |
| 353 | − ) : ( | |
| 354 | − Array.from({ length: 6 }, (_, i) => ( | |
| 355 | − <div className="stats-kpi" key={i}> | |
| 356 | − <Skeleton width="80px" height="2rem" /> | |
| 357 | − <Skeleton width="110px" height="0.8rem" /> | |
| 358 | − <Skeleton width="90px" height="0.7rem" /> | |
| 359 | − </div> | |
| 360 | − )) | |
| 361 | − )} | |
| 362 | − </section> | |
| 109 | + <PdfButton | |
| 110 | + period={period} | |
| 111 | + from={hasCustom ? custom.from : undefined} | |
| 112 | + to={hasCustom ? custom.to : undefined} | |
| 113 | + /> | |
| 114 | + </header> | |
| 363 | 115 | |
| 364 | − {!stats ? ( | |
| 365 | − <div className="stats-loading" aria-hidden="true"> | |
| 366 | − <Skeleton height="220px" radius="12px" /> | |
| 367 | − <Skeleton height="320px" radius="12px" /> | |
| 368 | − <Skeleton height="220px" radius="12px" /> | |
| 116 | + {loading && !dash && ( | |
| 117 | + <div style={{ display: 'grid', gap: 12, gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))' }}> | |
| 118 | + {[0, 1, 2, 3, 4, 5].map((i) => ( | |
| 119 | + <div key={i} className="card" style={{ height: 96, opacity: 0.45 }} aria-hidden="true" /> | |
| 120 | + ))} | |
| 369 | 121 | </div> |
| 370 | − ) : ( | |
| 371 | − <> | |
| 372 | − {/* 3 — nouveautés du marché */} | |
| 373 | − {stats.newest.length > 0 && ( | |
| 374 | − <section className="stats-section" aria-label="Nouveautés du marché"> | |
| 375 | − <header className="section-header"> | |
| 376 | − <h2>Nouveautés du marché</h2> | |
| 377 | − <Link className="section-see-all" to="/produits?sort=recent"> | |
| 378 | − Voir les récents | |
| 379 | − </Link> | |
| 380 | − </header> | |
| 381 | − <div className="stats-newest-rail"> | |
| 382 | − {stats.newest.map((p) => ( | |
| 383 | − <Link | |
| 384 | − key={p.uid} | |
| 385 | − className="card stats-newest-card" | |
| 386 | − to={productPath(p)} | |
| 387 | − > | |
| 388 | − <span className="stats-newest-chip"> | |
| 389 | − {p.category_label || 'Divers'} | |
| 390 | − </span> | |
| 391 | − <span className="stats-newest-title">{p.title}</span> | |
| 392 | − <span className="stats-newest-foot"> | |
| 393 | − <span className="stats-newest-price"> | |
| 394 | − {formatPrice(p.price) || 'Prix n.d.'} | |
| 395 | − </span> | |
| 396 | − <span className="stats-newest-store">{p.store_name}</span> | |
| 397 | − </span> | |
| 398 | − </Link> | |
| 399 | − ))} | |
| 400 | − </div> | |
| 401 | − </section> | |
| 402 | − )} | |
| 403 | − | |
| 404 | − {/* 4 — price histogram */} | |
| 405 | − {stats.price_buckets.length > 0 && totals && ( | |
| 406 | − <section className="stats-section" aria-label="Répartition des prix"> | |
| 407 | − <header className="section-header"> | |
| 408 | − <h2>Répartition des prix</h2> | |
| 409 | − </header> | |
| 410 | − <p className="stats-section-note"> | |
| 411 | − {formatInt(totals.products_priced)} produits avec prix affiché. | |
| 412 | − </p> | |
| 413 | − <div className="stats-bars"> | |
| 414 | − {stats.price_buckets.map((b) => ( | |
| 415 | − <div className="stats-bar-row" key={b.bucket}> | |
| 416 | − <span className="stats-bar-name"> | |
| 417 | − {BUCKET_LABELS[b.bucket] ?? b.bucket} | |
| 418 | − </span> | |
| 419 | − <span className="stats-bar-track"> | |
| 420 | − <span | |
| 421 | − className="stats-bar-fill stats-bar-fill-terracotta" | |
| 422 | − style={{ width: `${(b.n / bucketMax) * 100}%` }} | |
| 423 | − /> | |
| 424 | − </span> | |
| 425 | − <span className="stats-bar-value"> | |
| 426 | − {formatInt(b.n)} | |
| 427 | − <em>{formatShare(b.n, totals.products_priced)}</em> | |
| 428 | − </span> | |
| 429 | − </div> | |
| 430 | − ))} | |
| 431 | − </div> | |
| 432 | − <p className="stats-hist-caption"> | |
| 433 | − Prix médian{' '} | |
| 434 | − <strong>{formatPrice(totals.price_median) || '—'}</strong> · prix | |
| 435 | − moyen <strong>{formatPrice(totals.price_avg) || '—'}</strong> | |
| 436 | − </p> | |
| 437 | − </section> | |
| 438 | − )} | |
| 439 | − | |
| 440 | − {/* 4 — categories */} | |
| 441 | − {stats.by_category.length > 0 && ( | |
| 442 | − <section className="stats-section" aria-label="Catégories"> | |
| 443 | − <header className="section-header"> | |
| 444 | − <h2>Par catégorie</h2> | |
| 445 | − <Link className="section-see-all" to="/produits"> | |
| 446 | − Tout le catalogue | |
| 447 | − </Link> | |
| 448 | − </header> | |
| 449 | − | |
| 450 | − {/* desktop table */} | |
| 451 | − <div className="stats-cat-table-wrap"> | |
| 452 | − <table className="stats-cat-table"> | |
| 453 | − <thead> | |
| 454 | − <tr> | |
| 455 | − <th>Catégorie</th> | |
| 456 | − <th className="num">Produits ↓</th> | |
| 457 | − <th className="num">Boutiques</th> | |
| 458 | − <th className="num">Prix médian</th> | |
| 459 | − <th className="num">Prix moyen</th> | |
| 460 | − <th className="num">Fourchette</th> | |
| 461 | − </tr> | |
| 462 | − </thead> | |
| 463 | − <tbody> | |
| 464 | − {stats.by_category.map((c) => ( | |
| 465 | − <tr key={c.key}> | |
| 466 | − <td> | |
| 467 | − <Link | |
| 468 | − className="stats-cat-link" | |
| 469 | − to={`/produits?category=${encodeURIComponent(c.key)}`} | |
| 470 | − > | |
| 471 | − {c.label} | |
| 472 | − </Link> | |
| 473 | − </td> | |
| 474 | − <td className="num stats-cat-prod"> | |
| 475 | − <span className="stats-cat-prod-inner"> | |
| 476 | − <span | |
| 477 | − className="stats-cat-prod-bar" | |
| 478 | − aria-hidden="true" | |
| 479 | − > | |
| 480 | − <span | |
| 481 | − className="stats-cat-prod-fill" | |
| 482 | − style={{ | |
| 483 | − width: `${(c.products / catMax) * 100}%`, | |
| 484 | − }} | |
| 485 | − /> | |
| 486 | − </span> | |
| 487 | − <span className="stats-cat-prod-n"> | |
| 488 | − {formatInt(c.products)} | |
| 489 | − </span> | |
| 490 | − </span> | |
| 491 | − </td> | |
| 492 | − <td className="num">{formatInt(c.stores)}</td> | |
| 493 | − <td className="num">{formatPrice(c.price_median) || '—'}</td> | |
| 494 | − <td className="num">{formatPrice(c.price_avg) || '—'}</td> | |
| 495 | − <td className="num stats-cat-range"> | |
| 496 | − {c.price_min !== null && c.price_max !== null | |
| 497 | − ? `${formatPriceCompact(c.price_min)} – ${formatPriceCompact(c.price_max)}` | |
| 498 | − : '—'} | |
| 499 | − </td> | |
| 500 | − </tr> | |
| 501 | − ))} | |
| 502 | − </tbody> | |
| 503 | − </table> | |
| 504 | − </div> | |
| 505 | − | |
| 506 | − {/* mobile stacked cards */} | |
| 507 | − <div className="stats-cat-cards"> | |
| 508 | − {stats.by_category.map((c) => ( | |
| 509 | − <Link | |
| 510 | − key={c.key} | |
| 511 | − className="card stats-cat-card" | |
| 512 | − to={`/produits?category=${encodeURIComponent(c.key)}`} | |
| 513 | − > | |
| 514 | − <div className="stats-cat-card-head"> | |
| 515 | − <strong>{c.label}</strong> | |
| 516 | − <span className="stats-cat-card-count"> | |
| 517 | − {formatInt(c.products)} produits | |
| 518 | − </span> | |
| 519 | − </div> | |
| 520 | − <dl className="stats-cat-card-grid"> | |
| 521 | − <div> | |
| 522 | − <dt>Boutiques</dt> | |
| 523 | − <dd>{formatInt(c.stores)}</dd> | |
| 524 | − </div> | |
| 525 | − <div> | |
| 526 | − <dt>Prix médian</dt> | |
| 527 | − <dd>{formatPrice(c.price_median) || '—'}</dd> | |
| 528 | − </div> | |
| 529 | − <div> | |
| 530 | − <dt>Prix moyen</dt> | |
| 531 | − <dd>{formatPrice(c.price_avg) || '—'}</dd> | |
| 532 | − </div> | |
| 533 | − <div> | |
| 534 | − <dt>Fourchette</dt> | |
| 535 | − <dd> | |
| 536 | − {c.price_min !== null && c.price_max !== null | |
| 537 | − ? `${formatPriceCompact(c.price_min)} – ${formatPriceCompact(c.price_max)}` | |
| 538 | − : '—'} | |
| 539 | − </dd> | |
| 540 | − </div> | |
| 541 | − </dl> | |
| 542 | − </Link> | |
| 543 | − ))} | |
| 544 | − </div> | |
| 545 | − </section> | |
| 546 | − )} | |
| 122 | + )} | |
| 547 | 123 | |
| 548 | − {/* 5 — regions */} | |
| 549 | − {stats.by_region.length > 0 && ( | |
| 550 | − <section className="stats-section" aria-label="Régions"> | |
| 551 | − <header className="section-header"> | |
| 552 | − <h2>Par région</h2> | |
| 553 | − </header> | |
| 554 | − <div className="stats-regions"> | |
| 555 | − {stats.by_region.map((r) => ( | |
| 556 | − <div className="stats-region-row" key={r.key}> | |
| 557 | − <div className="stats-region-head"> | |
| 558 | − <Link | |
| 559 | − className="stats-region-name" | |
| 560 | − to={`/produits?region=${encodeURIComponent(r.key)}`} | |
| 561 | − > | |
| 562 | − {r.key} | |
| 563 | − </Link> | |
| 564 | − <span className="stats-region-meta"> | |
| 565 | − {formatInt(r.stores)} boutique{r.stores > 1 ? 's' : ''} | |
| 566 | − {r.price_avg !== null && | |
| 567 | − ` · prix moyen ${formatPriceCompact(r.price_avg)}`} | |
| 568 | − </span> | |
| 569 | − </div> | |
| 570 | − <div className="stats-bar-row stats-bar-row-flat"> | |
| 571 | − <span className="stats-bar-track"> | |
| 572 | − <span | |
| 573 | − className="stats-bar-fill stats-bar-fill-pine" | |
| 574 | − style={{ width: `${(r.products / regionMax) * 100}%` }} | |
| 575 | − /> | |
| 576 | − </span> | |
| 577 | − <span className="stats-bar-value">{formatInt(r.products)}</span> | |
| 578 | − </div> | |
| 579 | − </div> | |
| 580 | − ))} | |
| 581 | − </div> | |
| 582 | − </section> | |
| 583 | − )} | |
| 124 | + {error && ( | |
| 125 | + <div className="card" style={{ padding: 24, textAlign: 'center' }}> | |
| 126 | + <b style={{ fontFamily: 'var(--font-display)' }}>Impossible de charger les statistiques</b> | |
| 127 | + <p className="klabel" style={{ margin: '8px 0 12px' }}>Réessayez dans un instant.</p> | |
| 128 | + <button type="button" className="btn btn-primary" onClick={load}>Réessayer</button> | |
| 129 | + </div> | |
| 130 | + )} | |
| 584 | 131 | |
| 585 | − {/* 6 — growth */} | |
| 586 | − {stats.growth.length > 1 && ( | |
| 587 | − <section className="stats-section" aria-label="Croissance"> | |
| 588 | − <header className="section-header"> | |
| 589 | − <h2>Produits ajoutés par jour (30 jours)</h2> | |
| 590 | − </header> | |
| 591 | − <GrowthChart points={stats.growth} /> | |
| 592 | − </section> | |
| 593 | − )} | |
| 132 | + {dash && ( | |
| 133 | + <div style={{ opacity: loading ? 0.55 : 1, transition: 'opacity 0.2s' }}> | |
| 134 | + {/* ---- 1. bandeau KPI ---- */} | |
| 135 | + <section aria-label="Indicateurs clés" style={{ display: 'grid', gap: 12, gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))' }}> | |
| 136 | + {dash.kpis.map((k) => ( | |
| 137 | + <KpiCard key={k.id} k={k} /> | |
| 138 | + ))} | |
| 139 | + </section> | |
| 140 | + | |
| 141 | + {/* ---- 2. sélecteur de période global ---- */} | |
| 142 | + <section aria-label="Période" style={{ margin: '20px 0 0' }}> | |
| 143 | + <PeriodSelector | |
| 144 | + value={hasCustom ? '' : period} | |
| 145 | + onChange={(p) => { | |
| 146 | + setCustom({ from: '', to: '' }) | |
| 147 | + setPeriod(p) | |
| 148 | + }} | |
| 149 | + custom={custom} | |
| 150 | + onCustom={(from, to) => setCustom({ from, to })} | |
| 151 | + /> | |
| 152 | + <p className="klabel" style={{ margin: '8px 0 0' }}> | |
| 153 | + Période : {dash.period.label} ({dash.period.from} → {dash.period.to}) | |
| 154 | + </p> | |
| 155 | + </section> | |
| 156 | + | |
| 157 | + {/* ---- 3. graphiques ---- */} | |
| 158 | + <h2 style={SECTION_TITLE}>Évolution</h2> | |
| 159 | + <div style={{ display: 'grid', gap: 14 }}> | |
| 160 | + {dash.series.map((s) => ( | |
| 161 | + <LineChart key={s.id} serie={s} /> | |
| 162 | + ))} | |
| 163 | + {dash.heatmap ? ( | |
| 164 | + <CalendarHeatmap title={dash.heatmap.title} cells={dash.heatmap.cells} /> | |
| 165 | + ) : null} | |
| 166 | + </div> | |
| 594 | 167 | |
| 595 | − {/* 7 — origin distribution */} | |
| 596 | − {originRows.length > 0 && originTotal > 0 && ( | |
| 597 | − <section className="stats-section" aria-label="Origine"> | |
| 598 | − <header className="section-header"> | |
| 599 | − <h2>Par origine</h2> | |
| 600 | − </header> | |
| 601 | − <div | |
| 602 | − className="stats-origin-bar" | |
| 603 | − role="img" | |
| 604 | − aria-label={originRows | |
| 605 | − .map( | |
| 606 | − (r) => | |
| 607 | − `${ORIGIN_LABELS[r.key]} : ${formatInt(r.stat.products)} produits` | |
| 608 | − ) | |
| 609 | − .join(' · ')} | |
| 610 | − > | |
| 611 | − {originRows | |
| 612 | − .filter((r) => r.stat.products > 0) | |
| 613 | − .map((r) => { | |
| 614 | − const pct = (r.stat.products / originTotal) * 100 | |
| 615 | − return ( | |
| 616 | − <span | |
| 617 | − key={r.key} | |
| 618 | − className={`stats-origin-seg origin-${r.key}`} | |
| 619 | − style={{ width: `${pct}%` }} | |
| 620 | − title={`${ORIGIN_LABELS[r.key]} — ${formatInt(r.stat.products)} produits (${formatShare(r.stat.products, originTotal)})`} | |
| 621 | − > | |
| 622 | − {pct >= 6 && ( | |
| 623 | − <span className="stats-origin-seg-letter">{r.key}</span> | |
| 624 | − )} | |
| 625 | − </span> | |
| 626 | − ) | |
| 627 | − })} | |
| 628 | − </div> | |
| 629 | − <ul className="stats-origin-legend"> | |
| 630 | − {originRows.map((r) => ( | |
| 631 | − <li key={r.key}> | |
| 632 | − <OriginBadge origin={r.key} withLabel /> | |
| 633 | − <span className="stats-origin-legend-counts"> | |
| 634 | − {formatInt(r.stat.stores)} boutique | |
| 635 | − {r.stat.stores > 1 ? 's' : ''} ·{' '} | |
| 636 | − {formatInt(r.stat.products)} produits | |
| 637 | − {originTotal > 0 && | |
| 638 | − r.stat.products > 0 && | |
| 639 | − ` (${formatShare(r.stat.products, originTotal)})`} | |
| 640 | − </span> | |
| 641 | − </li> | |
| 642 | − ))} | |
| 643 | − </ul> | |
| 644 | − </section> | |
| 645 | − )} | |
| 168 | + <h2 style={SECTION_TITLE}>Répartitions</h2> | |
| 169 | + <div style={{ display: 'grid', gap: 14, gridTemplateColumns: 'repeat(auto-fit, minmax(min(340px, 100%), 1fr))' }}> | |
| 170 | + {donuts.map((b) => ( | |
| 171 | + <Donut key={b.id} title={b.title} items={b.items} /> | |
| 172 | + ))} | |
| 173 | + {bars.map((b) => ( | |
| 174 | + <BarChart key={b.id} title={b.title} items={b.items} /> | |
| 175 | + ))} | |
| 176 | + </div> | |
| 646 | 177 | |
| 647 | − {/* 8 — platforms */} | |
| 648 | − {stats.by_platform.length > 0 && ( | |
| 649 | − <section className="stats-section" aria-label="Plateformes"> | |
| 650 | − <header className="section-header"> | |
| 651 | − <h2>Plateformes</h2> | |
| 652 | − </header> | |
| 653 | − <div className="stats-platforms"> | |
| 654 | − {stats.by_platform.map((p) => ( | |
| 655 | − <span className="stats-platform-chip" key={p.key}> | |
| 656 | − <strong>{p.key}</strong> × {formatInt(p.stores)} boutique | |
| 657 | − {p.stores > 1 ? 's' : ''} ({formatInt(p.products)} produits) | |
| 658 | − </span> | |
| 659 | − ))} | |
| 660 | − </div> | |
| 661 | − </section> | |
| 178 | + {/* ---- 4. répartition géographique ---- */} | |
| 179 | + <h2 style={SECTION_TITLE}>Régions</h2> | |
| 180 | + {dash.geo && dash.geo.items.length ? ( | |
| 181 | + <BarChart title={dash.geo.title} items={dash.geo.items} unit="produits" /> | |
| 182 | + ) : ( | |
| 183 | + <EmptyBlock title="Répartition géographique" /> | |
| 662 | 184 | )} |
| 663 | 185 | |
| 664 | − {/* disponibilité */} | |
| 665 | − {availabilityRows.length > 0 && availabilityTotal > 0 && ( | |
| 666 | − <section className="stats-section" aria-label="Disponibilité"> | |
| 667 | − <header className="section-header"> | |
| 668 | − <h2>Disponibilité</h2> | |
| 669 | − </header> | |
| 670 | − <div | |
| 671 | − className="stats-avail-bar" | |
| 672 | − role="img" | |
| 673 | − aria-label={availabilityRows | |
| 674 | − .map( | |
| 675 | − (a) => | |
| 676 | − `${AVAILABILITY_META[a.key].label} : ${formatInt(a.n)} produits` | |
| 677 | − ) | |
| 678 | − .join(' · ')} | |
| 679 | − > | |
| 680 | − {availabilityRows | |
| 681 | − .filter((a) => a.n > 0) | |
| 682 | − .map((a) => ( | |
| 683 | − <span | |
| 684 | − key={a.key} | |
| 685 | − className={`stats-avail-seg stats-avail-${AVAILABILITY_META[a.key].slug}`} | |
| 686 | − style={{ width: `${(a.n / availabilityTotal) * 100}%` }} | |
| 687 | − title={`${AVAILABILITY_META[a.key].label} — ${formatInt(a.n)} (${formatShare(a.n, availabilityTotal)})`} | |
| 688 | − /> | |
| 689 | − ))} | |
| 690 | − </div> | |
| 691 | − <ul className="stats-avail-legend"> | |
| 692 | − {availabilityRows.map((a) => ( | |
| 693 | − <li key={a.key}> | |
| 694 | − <span | |
| 695 | − className={`stats-avail-dot stats-avail-${AVAILABILITY_META[a.key].slug}`} | |
| 696 | − aria-hidden="true" | |
| 697 | − /> | |
| 698 | − <span> | |
| 699 | − {AVAILABILITY_META[a.key].label}{' '} | |
| 700 | − <strong>{formatInt(a.n)}</strong>{' '} | |
| 701 | − <em>{formatShare(a.n, availabilityTotal)}</em> | |
| 702 | − </span> | |
| 703 | − </li> | |
| 704 | − ))} | |
| 705 | − </ul> | |
| 706 | − </section> | |
| 707 | − )} | |
| 186 | + {/* ---- 5. tableaux détaillés ---- */} | |
| 187 | + <h2 style={SECTION_TITLE}>Détails</h2> | |
| 188 | + <div style={{ display: 'grid', gap: 16 }}> | |
| 189 | + {dash.tables.map((t) => ( | |
| 190 | + <DataTable key={t.id} spec={t} /> | |
| 191 | + ))} | |
| 192 | + </div> | |
| 708 | 193 | |
| 709 | − {/* complétude des données */} | |
| 710 | − {coverageMeters.length > 0 && ( | |
| 711 | − <section | |
| 712 | − className="stats-section" | |
| 713 | − aria-label="Complétude des données" | |
| 714 | − > | |
| 715 | − <header className="section-header"> | |
| 716 | − <h2>Complétude des données</h2> | |
| 717 | − </header> | |
| 718 | − <div className="stats-coverage"> | |
| 719 | − {coverageMeters.map((m) => ( | |
| 720 | − <div className="stats-meter" key={m.label}> | |
| 721 | − <div className="stats-meter-head"> | |
| 722 | − <span className="stats-meter-label">{m.label}</span> | |
| 723 | − <span className="stats-meter-pct"> | |
| 724 | − {percentFormatter.format(m.pct)} | |
| 725 | − </span> | |
| 726 | − </div> | |
| 727 | − <span className="stats-meter-track"> | |
| 728 | − <span | |
| 729 | − className="stats-meter-fill" | |
| 730 | − style={{ width: `${m.pct * 100}%` }} | |
| 731 | − /> | |
| 732 | − </span> | |
| 733 | − <span className="stats-meter-sub"> | |
| 734 | − {formatInt(m.value)} / {formatInt(m.total)} | |
| 735 | − </span> | |
| 736 | − </div> | |
| 194 | + {/* ---- 6. records & faits marquants ---- */} | |
| 195 | + {dash.records.length > 0 && ( | |
| 196 | + <> | |
| 197 | + <h2 style={SECTION_TITLE}>Records & faits marquants</h2> | |
| 198 | + <div style={{ display: 'grid', gap: 10, gridTemplateColumns: 'repeat(auto-fit, minmax(min(320px, 100%), 1fr))' }}> | |
| 199 | + {dash.records.map((r) => ( | |
| 200 | + <RecordCard key={r.label} r={r} /> | |
| 737 | 201 | ))} |
| 738 | 202 | </div> |
| 739 | − </section> | |
| 203 | + </> | |
| 740 | 204 | )} |
| 741 | 205 | |
| 742 | − <div className="stats-columns"> | |
| 743 | − {/* 9 — top stores */} | |
| 744 | − {stats.top_stores.length > 0 && ( | |
| 745 | − <section className="stats-section" aria-label="Top boutiques"> | |
| 746 | − <header className="section-header"> | |
| 747 | − <h2>Top boutiques</h2> | |
| 748 | − <Link className="section-see-all" to="/boutiques"> | |
| 749 | − Toutes les boutiques | |
| 750 | − </Link> | |
| 751 | − </header> | |
| 752 | − <ol className="stats-top-stores"> | |
| 753 | − {stats.top_stores.map((s, i) => ( | |
| 754 | − <li key={s.id}> | |
| 755 | − <span className="stats-rank">{i + 1}</span> | |
| 756 | − <StoreLogo | |
| 757 | − storeId={s.id} | |
| 758 | − name={s.name} | |
| 759 | − logoUrl={s.logo_url} | |
| 760 | − size="sm" | |
| 761 | − /> | |
| 762 | − <span className="stats-top-store-id"> | |
| 763 | − <Link to={`/boutiques/${encodeURIComponent(s.id)}`}> | |
| 764 | − {s.name} | |
| 765 | − </Link> | |
| 766 | − {s.region && ( | |
| 767 | − <span className="stats-top-store-region">{s.region}</span> | |
| 768 | − )} | |
| 769 | − </span> | |
| 770 | − <span className="stats-top-store-count"> | |
| 771 | − {formatInt(s.products)} | |
| 772 | − </span> | |
| 773 | − </li> | |
| 774 | − ))} | |
| 775 | − </ol> | |
| 776 | − </section> | |
| 777 | − )} | |
| 778 | − | |
| 779 | − {/* 10 — most expensive */} | |
| 780 | − {stats.most_expensive.length > 0 && ( | |
| 781 | − <section className="stats-section" aria-label="Produits les plus chers"> | |
| 782 | − <header className="section-header"> | |
| 783 | − <h2>Les plus chers</h2> | |
| 784 | − </header> | |
| 785 | − <p className="stats-section-note"> | |
| 786 | − Le grand luxe made in Québec — véridique, promis. | |
| 787 | − </p> | |
| 788 | − <ol className="stats-expensive"> | |
| 789 | − {stats.most_expensive.map((p) => ( | |
| 790 | − <li key={p.uid}> | |
| 791 | − <Link | |
| 792 | − className="stats-expensive-link" | |
| 793 | − to={productPath(p)} | |
| 794 | − > | |
| 795 | − <span className="stats-expensive-title">{p.title}</span> | |
| 796 | − <span className="stats-expensive-store">{p.store_name}</span> | |
| 797 | − </Link> | |
| 798 | − <span className="stats-expensive-price"> | |
| 799 | − {formatPrice(p.price)} | |
| 800 | − </span> | |
| 801 | − </li> | |
| 802 | − ))} | |
| 803 | − </ol> | |
| 804 | − </section> | |
| 805 | − )} | |
| 206 | + {/* ---- 7. fraîcheur ---- */} | |
| 207 | + <div style={{ marginTop: 28, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 10 }}> | |
| 208 | + <Fraicheur updated={dash.updated} onRefresh={load} /> | |
| 209 | + <p className="klabel" style={{ margin: 0 }}> | |
| 210 | + Données réelles Fabri-Ka — aucune statistique estimée ni inventée. | |
| 211 | + </p> | |
| 806 | 212 | </div> |
| 807 | − </> | |
| 213 | + </div> | |
| 808 | 214 | )} |
| 809 | − | |
| 810 | − {/* report download — footer */} | |
| 811 | − <section className="stats-report-footer" aria-label="Rapport de marché"> | |
| 812 | − <a | |
| 813 | − className="btn btn-secondary stats-report-btn" | |
| 814 | − href={REPORT_URL} | |
| 815 | − download | |
| 816 | − > | |
| 817 | − <IconDownload size={18} /> | |
| 818 | − Télécharger le rapport PDF | |
| 819 | − </a> | |
| 820 | − <span className="stats-report-hint">{REPORT_HINT}</span> | |
| 821 | − </section> | |
| 822 | 215 | </div> |
| 823 | 216 | ) |
| 824 | 217 | } |
| 825 | 218 | |