SPB Git forge

spb/food-ka

Public

Food-Ka — agrégateur de produits d'épicerie du Québec — www.food-ka.com

55commits 1branches 0releases
10.2 MBsize
maindefault branch
9 days agolast push
Python 53.9% TypeScript 24% CSS 14.9% JavaScript 5.8% HTML 1.4%

Stats : tableau de bord analytique commun Groupe KA + export PDF

- Vendor du module ka-ui/stats (SPEC.md, kit kacharts.tsx, moteur kapdf.py)
- foodka/statsdash.py : GET /api/stats/dashboard?period=… (contrat SPEC) —
  KPI avec deltas, séries/jour (produits suivis, relevés de prix, prix moyen,
  baisses détectées, nouveautés), donut bannières top 8, top catégories,
  heatmap des relevés, tableaux (top soldes, top baisses, prix par catégorie),
  records & faits marquants ; tout calculé sur products/price_log/sync_log,
  cache serveur 5 min par période
- GET /api/stats/report?period=&mode=complet|synthese : rapport PDF
  Groupe-KA (fpdf2, graphiques vectoriels, wordmark Food·Ka, accent #1f9d55),
  filename kapdf.filename ; correctif kapdf : jamais d en-tête/pied sur la
  couverture (p. 1)
- pages/Stats.tsx : refonte sur le kit kacharts — bandeau KPI, sélecteur de
  période (+ plage personnalisée), courbes interactives, anneau, heatmap,
  tableaux triables/paginés, records, fraîcheur + rafraîchir, boutons PDF ;
  le panier comparatif Food-Ka est conservé (section métier)
- requirements.txt : + fpdf2

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

9 changed files +2,277 −348

added foodka/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 or self.page_no() == 1: # la couverture est la p. 1
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 or self.page_no() == 1: # jamais de pied sur la couverture
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 foodka/statsdash.py +401 −0
@@ -0,0 +1,401 @@
1 +# -----------------------------------------------------------------------------
2 +# Food-Ka — Agrégateur de produits d'épicerie (province de Québec)
3 +# Auteur : Simon-Pierre Boucher — contact@spboucher.ai
4 +# statsdash.py : tableau de bord analytique — source unique de
5 +# GET /api/stats/dashboard (contrat commun ka-ui/stats/SPEC.md) et du
6 +# rapport PDF Groupe-KA (GET /api/stats/report, moteur foodka/kapdf.py).
7 +# Tout est calculé sur les données réelles : products (catalogue vivant),
8 +# price_log (historique des relevés de prix), sync_log (journal des syncs).
9 +# Cache serveur : 5 minutes par période demandée.
10 +# -----------------------------------------------------------------------------
11 +from __future__ import annotations
12 +
13 +import json
14 +import statistics
15 +import threading
16 +import time
17 +from datetime import date, datetime, timedelta
18 +from pathlib import Path
19 +from zoneinfo import ZoneInfo
20 +
21 +from . import db
22 +
23 +TZ = ZoneInfo("America/Toronto")
24 +CACHE_TTL = 300 # secondes (SPEC : >= 5 min par période)
25 +
26 +_cache: dict[tuple, tuple[float, dict]] = {}
27 +_cache_lock = threading.Lock()
28 +
29 +# période -> (libellé, nombre de jours) ; « annee » et « tout » sont calculés
30 +_PERIOD_DAYS = {
31 + "auj": ("Aujourd'hui", 1),
32 + "7j": ("7 jours", 7),
33 + "30j": ("30 jours", 30),
34 + "3m": ("3 mois", 91),
35 + "6m": ("6 mois", 182),
36 + "12m": ("12 mois", 365),
37 +}
38 +
39 +_PRICE_SANE = "price IS NOT NULL AND price > 0 AND price <= 2000"
40 +
41 +# Noms d'affichage des bannières (registre data/sources.json)
42 +_SOURCES_PATH = Path(__file__).resolve().parent.parent / "data" / "sources.json"
43 +
44 +
45 +def _source_names() -> dict[str, str]:
46 + try:
47 + reg = json.loads(_SOURCES_PATH.read_text(encoding="utf-8"))["sources"]
48 + return {s["id"]: s.get("name") or s["id"] for s in reg}
49 + except Exception:
50 + return {}
51 +
52 +
53 +def _fmt_money(v: float | None) -> str:
54 + if v is None:
55 + return "—"
56 + return f"{v:,.2f}".replace(",", " ").replace(".", ",") + " $"
57 +
58 +
59 +def _parse_date(s: str | None) -> date | None:
60 + if not s:
61 + return None
62 + try:
63 + return date.fromisoformat(s[:10])
64 + except ValueError:
65 + return None
66 +
67 +
68 +def _day_start_ts(d: date) -> float:
69 + return datetime(d.year, d.month, d.day, tzinfo=TZ).timestamp()
70 +
71 +
72 +def _resolve_period(con, period: str, from_s: str | None, to_s: str | None):
73 + """Retourne (from_date, to_date, label, period_id) — bornes inclusives."""
74 + today = datetime.now(TZ).date()
75 + f, t = _parse_date(from_s), _parse_date(to_s)
76 + if f and t:
77 + if t < f:
78 + f, t = t, f
79 + return f, min(t, today), f"du {f.isoformat()} au {t.isoformat()}", "perso"
80 + if period == "annee":
81 + return date(today.year, 1, 1), today, "Année en cours", period
82 + if period == "tout":
83 + row = con.execute("SELECT MIN(first_seen) m FROM products").fetchone()
84 + start = (datetime.fromtimestamp(row["m"], TZ).date()
85 + if row and row["m"] else today)
86 + return start, today, "Toute la période", period
87 + label, days = _PERIOD_DAYS.get(period, _PERIOD_DAYS["30j"])
88 + if period not in _PERIOD_DAYS:
89 + label, period = _PERIOD_DAYS["30j"][0], "30j"
90 + return today - timedelta(days=days - 1), today, label, period
91 +
92 +
93 +def _delta_pct(cur: float | None, prev: float | None) -> float | None:
94 + if cur is None or prev is None or prev == 0:
95 + return None
96 + return round(100 * (cur - prev) / prev, 1)
97 +
98 +
99 +def _days_range(f: date, t: date) -> list[date]:
100 + n = (t - f).days + 1
101 + step = max(1, -(-n // 200)) # au plus ~200 points de série
102 + days = [f + timedelta(days=i) for i in range(0, n, step)]
103 + if days[-1] != t:
104 + days.append(t)
105 + return days
106 +
107 +
108 +# ---------------------------------------------------------------------------
109 +# Calcul principal
110 +# ---------------------------------------------------------------------------
111 +
112 +def _tracked_at(con, ts: float) -> int:
113 + """Produits suivis à l'instant ts (reconstruit via first_seen/last_seen)."""
114 + return con.execute(
115 + "SELECT COUNT(*) c FROM products"
116 + " WHERE first_seen IS NOT NULL AND first_seen <= ?"
117 + " AND (active = 1 OR last_seen >= ?)", (ts, ts)).fetchone()["c"]
118 +
119 +
120 +def _compute(period: str, from_s: str | None, to_s: str | None) -> dict:
121 + con = db.connect()
122 + names = _source_names()
123 + label_of = lambda src: names.get(src, src) # noqa: E731
124 +
125 + f_date, t_date, label, period_id = _resolve_period(con, period, from_s, to_s)
126 + start = _day_start_ts(f_date)
127 + end = _day_start_ts(t_date + timedelta(days=1))
128 + now_ts = time.time()
129 + end_eff = min(end, now_ts) # fin effective (la période inclut souvent « maintenant »)
130 + span = end - start
131 + prev_start, prev_end = start - span, start
132 +
133 + # ---- historique des relevés de prix (price_log) --------------------------
134 + first_log = con.execute("SELECT MIN(ts) m FROM price_log").fetchone()["m"]
135 + has_history = first_log is not None
136 +
137 + releves_cur = con.execute(
138 + "SELECT COUNT(*) c FROM price_log WHERE ts >= ? AND ts < ?",
139 + (start, end)).fetchone()["c"]
140 + releves_prev = con.execute(
141 + "SELECT COUNT(*) c FROM price_log WHERE ts >= ? AND ts < ?",
142 + (prev_start, prev_end)).fetchone()["c"]
143 +
144 + # variations de prix détectées dans la période (LAG sur price_log)
145 + moves = con.execute(
146 + """WITH x AS (
147 + SELECT uid, ts, price,
148 + LAG(price) OVER (PARTITION BY uid ORDER BY ts) prev
149 + FROM price_log)
150 + SELECT x.uid, x.ts, x.price, x.prev, p.name, p.source
151 + FROM x JOIN products p ON p.uid = x.uid
152 + WHERE x.ts >= ? AND x.ts < ?
153 + AND x.price IS NOT NULL AND x.prev IS NOT NULL
154 + AND x.prev > 0 AND x.price > 0 AND x.price <> x.prev
155 + AND x.price <= 2000 AND x.prev <= 2000""",
156 + (start, end)).fetchall()
157 + drops = [m for m in moves if m["price"] < m["prev"]]
158 + hikes = [m for m in moves if m["price"] > m["prev"]]
159 + amp = ([abs(m["price"] - m["prev"]) / m["prev"] for m in moves])
160 + amp_avg_pct = round(100 * statistics.mean(amp), 1) if amp else None
161 + drops_by_day: dict[str, int] = {}
162 + for m in drops:
163 + d = datetime.fromtimestamp(m["ts"], TZ).date().isoformat()
164 + drops_by_day[d] = drops_by_day.get(d, 0) + 1
165 + top_drops = sorted(
166 + ({"name": m["name"] or "", "source": m["source"],
167 + "old": m["prev"], "new": m["price"], "ts": m["ts"],
168 + "pct": round(100 * (m["prev"] - m["price"]) / m["prev"], 1)}
169 + for m in drops), key=lambda d: -d["pct"])
170 +
171 + # ---- KPI ------------------------------------------------------------------
172 + g = con.execute(
173 + f"""SELECT COUNT(*) total, SUM(on_sale) on_sale,
174 + COUNT(DISTINCT source) sources,
175 + COUNT(DISTINCT category) categories,
176 + AVG(CASE WHEN {_PRICE_SANE} THEN price END) avg_price
177 + FROM products WHERE active=1""").fetchone()
178 +
179 + tracked_now = _tracked_at(con, end_eff)
180 + tracked_prev = _tracked_at(con, start) if start > (first_log or 0) - 1 else None
181 +
182 + src_cur = con.execute(
183 + "SELECT COUNT(DISTINCT source) c FROM sync_log WHERE ok=1 AND ts >= ? AND ts < ?",
184 + (start, end)).fetchone()["c"]
185 + src_prev = con.execute(
186 + "SELECT COUNT(DISTINCT source) c FROM sync_log WHERE ok=1 AND ts >= ? AND ts < ?",
187 + (prev_start, prev_end)).fetchone()["c"]
188 +
189 + avg_obs_cur = con.execute(
190 + "SELECT AVG(price) a FROM price_log WHERE ts >= ? AND ts < ?"
191 + " AND price > 0 AND price <= 2000", (start, end)).fetchone()["a"]
192 + avg_obs_prev = con.execute(
193 + "SELECT AVG(price) a FROM price_log WHERE ts >= ? AND ts < ?"
194 + " AND price > 0 AND price <= 2000", (prev_start, prev_end)).fetchone()["a"]
195 +
196 + def _kpi(id_, lbl, value, unit="", delta=None):
197 + d = {"id": id_, "label": lbl, "value": value, "unit": unit}
198 + if delta is not None:
199 + d["delta_pct"] = delta
200 + d["direction"] = "up" if delta >= 0 else "down"
201 + else:
202 + d["delta_pct"] = None
203 + return d
204 +
205 + kpis = [
206 + _kpi("suivis", "Produits suivis (actifs)", g["total"], "",
207 + _delta_pct(tracked_now, tracked_prev)),
208 + _kpi("releves", "Relevés de prix (période)", releves_cur, "",
209 + _delta_pct(releves_cur, releves_prev)),
210 + _kpi("bannieres", "Bannières connectées", g["sources"], "",
211 + _delta_pct(src_cur, src_prev)),
212 + _kpi("soldes", "Soldes actifs", g["on_sale"] or 0, ""),
213 + _kpi("prix_moyen", "Prix moyen (produits actifs)",
214 + round(g["avg_price"], 2) if g["avg_price"] else 0, "$",
215 + _delta_pct(avg_obs_cur, avg_obs_prev)),
216 + _kpi("categories", "Catégories", g["categories"], ""),
217 + ]
218 +
219 + # ---- séries par jour --------------------------------------------------------
220 + data_start = (datetime.fromtimestamp(first_log, TZ).date()
221 + if has_history else t_date)
222 + serie_from = max(f_date, data_start)
223 + days = _days_range(serie_from, t_date)
224 + iso = [d.isoformat() for d in days]
225 +
226 + pts_tracked = [{"t": d.isoformat(),
227 + "v": _tracked_at(con, min(_day_start_ts(d + timedelta(days=1)), now_ts))}
228 + for d in days]
229 +
230 + per_day = {r["d"]: r["c"] for r in con.execute(
231 + "SELECT date(ts,'unixepoch','localtime') d, COUNT(*) c FROM price_log"
232 + " WHERE ts >= ? AND ts < ? GROUP BY d", (start, end))}
233 + pts_releves = [{"t": d, "v": per_day.get(d, 0)} for d in iso]
234 +
235 + avg_day = {r["d"]: round(r["a"], 2) for r in con.execute(
236 + "SELECT date(ts,'unixepoch','localtime') d, AVG(price) a FROM price_log"
237 + " WHERE ts >= ? AND ts < ? AND price > 0 AND price <= 2000"
238 + " GROUP BY d", (start, end)) if r["a"] is not None}
239 + pts_avg = [{"t": d, "v": avg_day[d]} for d in iso if d in avg_day]
240 +
241 + new_day = {r["d"]: r["c"] for r in con.execute(
242 + "SELECT date(first_seen,'unixepoch','localtime') d, COUNT(*) c FROM products"
243 + " WHERE first_seen >= ? AND first_seen < ? GROUP BY d", (start, end))}
244 + pts_new = [{"t": d, "v": new_day.get(d, 0)} for d in iso]
245 +
246 + pts_drops = [{"t": d, "v": drops_by_day.get(d, 0)} for d in iso]
247 +
248 + series = []
249 + if len(pts_tracked) >= 2:
250 + series.append({"id": "suivis", "title": "Produits suivis par jour",
251 + "unit": "produits", "kind": "line", "points": pts_tracked})
252 + if has_history and len(pts_releves) >= 2:
253 + series.append({"id": "releves", "title": "Relevés de prix par jour",
254 + "unit": "relevés", "kind": "line", "points": pts_releves})
255 + if has_history and len(pts_avg) >= 2:
256 + series.append({"id": "prix_moyen", "title": "Prix moyen relevé par jour",
257 + "unit": "$", "kind": "line", "points": pts_avg})
258 + if has_history and len(pts_drops) >= 2 and drops:
259 + series.append({"id": "baisses", "title": "Baisses de prix détectées par jour",
260 + "unit": "baisses", "kind": "line", "points": pts_drops})
261 + if len(pts_new) >= 2 and any(p["v"] for p in pts_new):
262 + series.append({"id": "nouveautes", "title": "Nouveaux produits par jour",
263 + "unit": "produits", "kind": "line", "points": pts_new})
264 +
265 + # ---- répartitions -------------------------------------------------------------
266 + by_src = con.execute(
267 + "SELECT source, COUNT(*) n FROM products WHERE active=1"
268 + " GROUP BY source ORDER BY n DESC").fetchall()
269 + donut_items = [{"label": label_of(r["source"]), "value": r["n"]}
270 + for r in by_src[:8]] # top 8 (limite du donut ka-ui/kapdf)
271 + by_cat = con.execute(
272 + "SELECT category, COUNT(*) n FROM products WHERE active=1 AND category<>''"
273 + " GROUP BY category ORDER BY n DESC").fetchall()
274 + breakdowns = [
275 + {"id": "bannieres", "title": "Produits actifs par bannière", "kind": "donut",
276 + "items": donut_items},
277 + {"id": "categories", "title": "Top catégories (produits actifs)", "kind": "bars",
278 + "items": [{"label": r["category"], "value": r["n"]} for r in by_cat[:14]]},
279 + ]
280 +
281 + # ---- heatmap : relevés de prix par jour ---------------------------------------
282 + heatmap = None
283 + if has_history:
284 + hm_start = max(start, now_ts - 183 * 86400)
285 + cells = [{"date": r["d"], "value": r["c"]} for r in con.execute(
286 + "SELECT date(ts,'unixepoch','localtime') d, COUNT(*) c FROM price_log"
287 + " WHERE ts >= ? AND ts < ? GROUP BY d ORDER BY d", (hm_start, end))]
288 + if cells:
289 + heatmap = {"title": "Relevés de prix par jour", "cells": cells}
290 +
291 + # ---- tableaux -------------------------------------------------------------------
292 + def _cut(s: str, n: int = 26) -> str:
293 + s = (s or "").strip()
294 + return s if len(s) <= n else s[: n - 1] + "…"
295 +
296 + sale_rows = [
297 + [_cut(r["name"]), label_of(r["source"]), _fmt_money(r["price"]),
298 + _fmt_money(r["regular_price"]),
299 + f"−{round(100 * (r['regular_price'] - r['price']) / r['regular_price'])} %"]
300 + for r in con.execute(
301 + f"""SELECT name, source, price, regular_price FROM products
302 + WHERE active=1 AND on_sale=1 AND regular_price IS NOT NULL
303 + AND {_PRICE_SANE} AND regular_price > price
304 + ORDER BY (regular_price - price) / regular_price DESC LIMIT 100""")]
305 +
306 + cat_prices: dict[str, list[float]] = {}
307 + cat_sales: dict[str, int] = {}
308 + for r in con.execute(
309 + f"""SELECT category, price, on_sale FROM products
310 + WHERE active=1 AND category<>'' AND {_PRICE_SANE}"""):
311 + cat_prices.setdefault(r["category"], []).append(r["price"])
312 + cat_sales[r["category"]] = cat_sales.get(r["category"], 0) + (r["on_sale"] or 0)
313 + cat_rows = sorted(
314 + ([cat, len(v), _fmt_money(round(statistics.mean(v), 2)),
315 + _fmt_money(round(statistics.median(v), 2)), cat_sales.get(cat, 0)]
316 + for cat, v in cat_prices.items()), key=lambda r: -r[1])
317 +
318 + tables = [
319 + {"id": "top_soldes", "title": "Top produits en solde (rabais les plus forts)",
320 + "columns": ["Produit", "Bannière", "Prix", "Prix rég.", "Rabais"],
321 + "rows": sale_rows},
322 + {"id": "prix_categories", "title": "Prix moyens par catégorie",
323 + "columns": ["Catégorie", "Produits", "Prix moyen", "Prix médian", "En solde"],
324 + "rows": cat_rows},
325 + ]
326 + if top_drops:
327 + tables.insert(1, {
328 + "id": "baisses", "title": "Top baisses de prix détectées (période)",
329 + "columns": ["Produit", "Bannière", "Avant", "Après", "Baisse"],
330 + "rows": [[_cut(d["name"]), label_of(d["source"]), _fmt_money(d["old"]),
331 + _fmt_money(d["new"]), f"−{d['pct']} %".replace(".", ",")]
332 + for d in top_drops[:100]]})
333 +
334 + # ---- records & faits marquants -----------------------------------------------
335 + records = []
336 + best_sale = con.execute(
337 + f"""SELECT name, source, price, regular_price,
338 + (regular_price - price) / regular_price pct
339 + FROM products WHERE active=1 AND on_sale=1 AND {_PRICE_SANE}
340 + AND regular_price IS NOT NULL AND regular_price > price
341 + ORDER BY pct DESC LIMIT 1""").fetchone()
342 + if best_sale:
343 + records.append({
344 + "label": "Record de promo — plus gros rabais affiché",
345 + "value": f"−{round(100 * best_sale['pct'])} % · {_cut(best_sale['name'], 34)} "
346 + f"({label_of(best_sale['source'])})"})
347 + if top_drops:
348 + d0 = top_drops[0]
349 + records.append({
350 + "label": "Plus forte baisse détectée (période)",
351 + "value": f"−{str(d0['pct']).replace('.', ',')} % · {_cut(d0['name'], 34)} "
352 + f"({_fmt_money(d0['old'])} → {_fmt_money(d0['new'])})",
353 + "date": datetime.fromtimestamp(d0["ts"], TZ).date().isoformat()})
354 + if has_history and per_day:
355 + rec_day = max(per_day.items(), key=lambda kv: kv[1])
356 + records.append({"label": "Jour record de relevés de prix",
357 + "value": f"{rec_day[1]:,}".replace(",", " ") + " relevés",
358 + "date": rec_day[0]})
359 + if new_day:
360 + rec_new = max(new_day.items(), key=lambda kv: kv[1])
361 + records.append({"label": "Jour record de nouveaux produits",
362 + "value": f"{rec_new[1]:,}".replace(",", " ") + " produits",
363 + "date": rec_new[0]})
364 + if moves:
365 + records.append({
366 + "label": "Variations de prix détectées (période)",
367 + "value": f"{len(drops):,} baisses · {len(hikes):,} hausses".replace(",", " ")})
368 + if amp_avg_pct is not None:
369 + records.append({"label": "Amplitude moyenne des variations de prix",
370 + "value": f"±{amp_avg_pct} %".replace(".", ",")})
371 +
372 + con.close()
373 + return {
374 + "updated": datetime.now(TZ).isoformat(timespec="seconds"),
375 + "period": {"from": f_date.isoformat(), "to": t_date.isoformat(),
376 + "label": label, "id": period_id},
377 + "kpis": kpis,
378 + "series": series,
379 + "breakdowns": breakdowns,
380 + **({"heatmap": heatmap} if heatmap else {}),
381 + "tables": tables,
382 + "records": records,
383 + }
384 +
385 +
386 +def dashboard(period: str = "30j", from_s: str | None = None,
387 + to_s: str | None = None) -> dict:
388 + """Tableau de bord (contrat SPEC.md) — mis en cache 5 minutes par période."""
389 + key = (period, from_s or "", to_s or "")
390 + now = time.time()
391 + with _cache_lock:
392 + hit = _cache.get(key)
393 + if hit and now - hit[0] < CACHE_TTL:
394 + return hit[1]
395 + data = _compute(period, from_s, to_s)
396 + with _cache_lock:
397 + _cache[key] = (now, data)
398 + if len(_cache) > 64: # borne de sécurité (plages personnalisées)
399 + oldest = min(_cache, key=lambda k: _cache[k][0])
400 + _cache.pop(oldest, None)
401 + return data
modified foodka/web.py +40 −0
@@ -198,6 +198,46 @@ def stats_detailed():
198 198 return marketstats.compute()
199 199
200 200
201 +@app.get("/api/stats/dashboard")
202 +def stats_dashboard(
203 + period: str = "30j",
204 + from_date: str | None = Query(None, alias="from"),
205 + to_date: str | None = Query(None, alias="to"),
206 +):
207 + """Tableau de bord analytique — contrat commun ka-ui/stats/SPEC.md.
208 +
209 + Périodes : auj|7j|30j|3m|6m|12m|annee|tout, ou plage personnalisée
210 + from/to (YYYY-MM-DD). Cache serveur : 5 minutes par période."""
211 + from . import statsdash
212 + return statsdash.dashboard(period, from_date, to_date)
213 +
214 +
215 +@app.get("/api/stats/report")
216 +def stats_report(
217 + period: str = "30j",
218 + from_date: str | None = Query(None, alias="from"),
219 + to_date: str | None = Query(None, alias="to"),
220 + mode: str = "complet",
221 +):
222 + """Rapport PDF estampillé Groupe-KA — mêmes chiffres que /api/stats/dashboard."""
223 + from . import kapdf, statsdash
224 + dash = statsdash.dashboard(period, from_date, to_date)
225 + site = {
226 + "wordmark": "Food·Ka",
227 + "accent": "#1f9d55",
228 + "domain": "www.food-ka.com",
229 + "tagline": "Épicerie — tout le Québec, toujours à jour",
230 + }
231 + pdf = kapdf.GroupeKAReport(
232 + site=site, dashboard=dash,
233 + mode="synthese" if mode == "synthese" else "complet").build()
234 + return Response(
235 + content=pdf,
236 + media_type="application/pdf",
237 + headers={"Content-Disposition":
238 + f'attachment; filename="{kapdf.filename("food-ka", period)}"'})
239 +
240 +
201 241 @app.get("/api/stats/rapport.pdf")
202 242 def rapport_pdf():
203 243 """Rapport PDF du marché — mêmes chiffres que la page Statistiques."""
modified frontend/src/api.ts +27 −0
@@ -134,6 +134,33 @@ export interface DetailedStats {
134 134 price_distribution: { range: string; n: number }[];
135 135 }
136 136
137 +// --- Tableau de bord analytique (GET /api/stats/dashboard — contrat ka-ui) ----
138 +import type { Kpi, RecordFact, Serie, TableSpec } from "./ka/stats/kacharts";
139 +
140 +export interface DashBreakdown {
141 + id: string;
142 + title: string;
143 + kind: "donut" | "bars";
144 + items: { label: string; value: number }[];
145 +}
146 +
147 +export interface Dashboard {
148 + updated: string; // ISO — moment du calcul
149 + period: { from: string; to: string; label: string; id: string };
150 + kpis: Kpi[];
151 + series: Serie[];
152 + breakdowns: DashBreakdown[];
153 + heatmap?: { title: string; cells: { date: string; value: number }[] };
154 + tables: TableSpec[];
155 + records: RecordFact[];
156 +}
157 +
158 +export function fetchDashboard(period: string, from?: string, to?: string) {
159 + const p = new URLSearchParams({ period });
160 + if (from && to) { p.set("from", from); p.set("to", to); }
161 + return get<Dashboard>(`/api/stats/dashboard?${p}`);
162 +}
163 +
137 164 // --- Compte (connexion KA ID — SSO Groupe KA) ---------------------------------
138 165 export interface Socials {
139 166 instagram?: string;
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 or self.page_no() == 1: # la couverture est la p. 1
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 or self.page_no() == 1: # jamais de pied sur la couverture
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 +180 −348
@@ -1,23 +1,24 @@
1 1 // -----------------------------------------------------------------------------
2 2 // Food-Ka — Agrégateur de produits d'épicerie (province de Québec)
3 3 // Auteur : Simon-Pierre Boucher — contact@spboucher.ai
4 −// pages/Stats.tsx : observatoire du marché — consomme /api/stats/detailed
5 −// · Tuiles héro (produits, soldes, bannières, marques, prix médian, activité 7 j)
6 −// · 🧺 Panier comparatif : articles courants × bannières (prix médians)
7 −// · Bannières en chiffres (tableau triable, mini-barres de prix médian)
8 −// · Matrice catégorie × bannière (teinte chaleur, moins cher en vert)
9 −// · Distribution des prix, baisses de prix (7 j)
10 −// · Meilleures aubaines + journal des synchronisations (/api/stats)
4 +// pages/Stats.tsx : tableau de bord analytique (module Stats commun Groupe KA)
5 +// · Consomme /api/stats/dashboard (contrat ka-ui/stats/SPEC.md) — KPI avec
6 +// deltas, sélecteur de période, courbes/barres/anneau/heatmap, tableaux
7 +// triables, records & faits marquants, export PDF Groupe-KA.
8 +// · Bonus plateforme : 🧺 panier comparatif (depuis /api/stats/detailed).
11 9 // -----------------------------------------------------------------------------
12 −import { useEffect, useState } from "react";
10 +import { useCallback, useEffect, useState } from "react";
13 11 import { Link } from "react-router-dom";
14 12 import {
15 − BasketTotal, DetailedStats, SourceMarketStats, Stats,
16 − fetchSources, fetchStats, fmtTs, registerSourceNames,
13 + BasketTotal, Dashboard, DetailedStats,
14 + fetchDashboard, fetchSources, registerSourceNames,
17 15 sourceName, sourceShort, statsDetailed,
18 16 } from "../api";
19 −import ProductCard from "../components/ProductCard";
20 17 import SourceLogo from "../components/SourceLogo";
18 +import {
19 + BarChart, CalendarHeatmap, DataTable, Donut, EmptyBlock, Fraicheur,
20 + KpiCard, LineChart, PdfButton, PeriodSelector, RecordCard,
21 +} from "../ka/stats/kacharts";
21 22
22 23 const fmt = (n: number | null | undefined) =>
23 24 n == null ? "—" : n.toLocaleString("fr-CA");
@@ -25,34 +26,117 @@ const fmt$ = (n: number | null | undefined) =>
25 26 n == null
26 27 ? "—"
27 28 : `${n.toLocaleString("fr-CA", { minimumFractionDigits: 2, maximumFractionDigits: 2 })} $`;
28 −const fmtPct = (n: number | null | undefined, digits = 0) =>
29 − n == null
30 − ? "—"
31 − : `${n.toLocaleString("fr-CA", { maximumFractionDigits: digits })} %`;
32 29
33 −function Tile({ v, k, hero }: { v: string; k: string; hero?: boolean }) {
30 +/* ---------- 🧺 Panier comparatif (section métier Food-Ka) ---------- */
31 +function BasketSection({ m }: { m: DetailedStats }) {
32 + const basketCols = m.basket_totals.map((t) => t.source);
33 + const bestBasket: BasketTotal | null = m.basket_totals[0] ?? null;
34 + const totalBySrc: Record<string, BasketTotal> = {};
35 + for (const t of m.basket_totals) totalBySrc[t.source] = t;
36 + if (basketCols.length === 0) return <EmptyBlock title="🧺 Panier comparatif" />;
34 37 return (
35 − <div className={`tile ${hero ? "hero-tile" : ""}`}>
36 − <div className="tile-v">{v}</div>
37 − <div className="tile-k">{k}</div>
38 − </div>
38 + <section className="viz-card">
39 + <h2>🧺 Panier comparatif</h2>
40 + <p className="viz-sub">
41 + articles courants × bannières — prix médian des produits correspondants
42 + </p>
43 + <div className="basket-wrap">
44 + <table className="basket-table">
45 + <thead>
46 + <tr>
47 + <th>Article</th>
48 + {basketCols.map((src) => (
49 + <th key={src} className={src === bestBasket?.source ? "best-col" : ""}>
50 + <span className="basket-th">
51 + <SourceLogo source={src} size={28} fallback="hide" />
52 + {sourceShort(src)}
53 + </span>
54 + </th>
55 + ))}
56 + </tr>
57 + </thead>
58 + <tbody>
59 + {m.basket.map((row) => {
60 + const prices = basketCols
61 + .map((src) => row.by_source[src]?.median_price)
62 + .filter((v): v is number => v != null);
63 + const min = prices.length ? Math.min(...prices) : null;
64 + return (
65 + <tr key={row.item}>
66 + <th>{row.item}</th>
67 + {basketCols.map((src) => {
68 + const cell = row.by_source[src];
69 + const v = cell?.median_price ?? null;
70 + const cls = [
71 + v != null && v === min ? "cell-best" : "",
72 + src === bestBasket?.source ? "best-col" : "",
73 + ].join(" ").trim();
74 + return (
75 + <td key={src} className={cls}
76 + title={cell ? `${fmt(cell.n)} produits correspondants` : undefined}>
77 + {fmt$(v)}
78 + </td>
79 + );
80 + })}
81 + </tr>
82 + );
83 + })}
84 + </tbody>
85 + <tfoot>
86 + <tr>
87 + <th>Total du panier</th>
88 + {basketCols.map((src) => {
89 + const t = totalBySrc[src];
90 + return (
91 + <td key={src}
92 + className={src === bestBasket?.source ? "best-col cell-best" : ""}>
93 + {fmt$(t?.total)}
94 + <small>{t ? `${t.items}/${m.basket.length} articles` : ""}</small>
95 + </td>
96 + );
97 + })}
98 + </tr>
99 + </tfoot>
100 + </table>
101 + </div>
102 + {bestBasket && (
103 + <div className="basket-callout">
104 + 🏆 Panier le moins cher : <b>{sourceName(bestBasket.source)}</b> —{" "}
105 + {fmt$(bestBasket.total)} pour {bestBasket.items} articles
106 + </div>
107 + )}
108 + <p className="stats-foot">
109 + Prix médian des produits correspondant à chaque article chez la bannière ;
110 + seules les bannières couvrant la majorité du panier sont comparées.
111 + </p>
112 + </section>
39 113 );
40 114 }
41 115
42 −// clés numériques triables du tableau « bannières en chiffres »
43 −type BannerSortKey = "n" | "median_price" | "sale_share" | "avg_discount_pct" | "max_discount_pct";
44 −
116 +/* ---------- Page ---------- */
45 117 export default function StatsPage() {
46 − const [d, setD] = useState<Stats | null>(null); // /api/stats (aubaines + journal)
47 − const [m, setM] = useState<DetailedStats | null>(null); // /api/stats/detailed
118 + const [period, setPeriod] = useState("30j");
119 + const [custom, setCustom] = useState<{ from: string; to: string }>({ from: "", to: "" });
120 + const [dash, setDash] = useState<Dashboard | null>(null);
121 + const [basket, setBasket] = useState<DetailedStats | null>(null);
48 122 const [error, setError] = useState<string | null>(null);
49 − const [sortKey, setSortKey] = useState<BannerSortKey>("n");
50 − const [sortDir, setSortDir] = useState<-1 | 1>(-1);
123 + const [loading, setLoading] = useState(true);
124 +
125 + const useCustom = Boolean(custom.from && custom.to);
51 126
127 + const load = useCallback(() => {
128 + setLoading(true);
129 + setError(null);
130 + fetchDashboard(period, useCustom ? custom.from : undefined, useCustom ? custom.to : undefined)
131 + .then(setDash)
132 + .catch((e) => setError(String(e)))
133 + .finally(() => setLoading(false));
134 + }, [period, custom.from, custom.to, useCustom]);
135 +
136 + useEffect(() => { load(); }, [load]);
52 137 useEffect(() => {
53 138 fetchSources().then((r) => registerSourceNames(r.sources)).catch(() => {});
54 − fetchStats().then(setD).catch((e) => setError(String(e)));
55 − statsDetailed().then(setM).catch((e) => setError(String(e)));
139 + statsDetailed().then(setBasket).catch(() => {});
56 140 }, []);
57 141
58 142 if (error)
@@ -61,16 +145,17 @@ export default function StatsPage() {
61 145 <div className="big">⚠️</div>
62 146 <h2>Statistiques indisponibles</h2>
63 147 <p>{error}</p>
148 + <button type="button" className="btn btn-primary" onClick={load}>Réessayer</button>
64 149 </div>
65 150 );
66 151
67 − if (!m || !d)
152 + if (!dash)
68 153 return (
69 154 <div className="container stats-page" aria-busy="true">
70 155 <div className="skel" style={{ height: 110, marginTop: 40 }} />
71 156 <div className="tiles" style={{ marginTop: 20 }}>
72 157 {Array.from({ length: 6 }).map((_, i) => (
73 − <div className="skel" key={i} style={{ height: 92 }} />
158 + <div className="skel" key={i} style={{ height: 110 }} />
74 159 ))}
75 160 </div>
76 161 <div className="skel" style={{ height: 320, marginTop: 8 }} />
@@ -78,345 +163,92 @@ export default function StatsPage() {
78 163 </div>
79 164 );
80 165
81 − const g = m.global;
82 −
83 − // ---- panier comparatif -----------------------------------------------------
84 − // colonnes = bannières couvrant assez d'articles, déjà triées du moins cher
85 − const basketCols = m.basket_totals.map((t) => t.source);
86 − const bestBasket: BasketTotal | null = m.basket_totals[0] ?? null;
87 − const totalBySrc: Record<string, BasketTotal> = {};
88 − for (const t of m.basket_totals) totalBySrc[t.source] = t;
89 −
90 − // ---- tableau bannières (triable) --------------------------------------------
91 − const numOf = (r: SourceMarketStats, k: BannerSortKey): number =>
92 − (r[k] ?? -Infinity) as number;
93 − const bannerRows = [...m.by_source].sort(
94 − (a, b) => (numOf(a, sortKey) - numOf(b, sortKey)) * sortDir || b.n - a.n
95 − );
96 − const maxMedian = Math.max(...m.by_source.map((r) => r.median_price ?? 0), 0.01);
97 − const sortBy = (k: BannerSortKey) => {
98 − if (sortKey === k) setSortDir((dir) => (dir === -1 ? 1 : -1));
99 − else { setSortKey(k); setSortDir(-1); }
100 − };
101 − const Th = ({ k, label }: { k: BannerSortKey; label: string }) => (
102 − <th
103 − className={`sortable ${sortKey === k ? "sorted" : ""}`}
104 − onClick={() => sortBy(k)}
105 − title="Trier"
106 − >
107 − {label}{sortKey === k ? (sortDir === -1 ? " ▾" : " ▴") : ""}
108 − </th>
109 − );
110 −
111 − // ---- matrice catégorie × bannière --------------------------------------------
112 − const matrixSources = m.by_source.slice(0, 9).map((s) => s.source);
113 − const matrixRows = Object.entries(m.category_matrix)
114 − .map(([cat, per]) => ({
115 − cat, per,
116 − total: Object.values(per).reduce((s, c) => s + c.n, 0),
117 − }))
118 − .sort((a, b) => b.total - a.total);
119 −
120 − // ---- distribution des prix ---------------------------------------------------
121 − const distMax = Math.max(...m.price_distribution.map((b) => b.n), 1);
166 + const lines = dash.series.filter((s) => (s.kind ?? "line") === "line");
167 + const barSeries = dash.series.filter((s) => s.kind === "bar");
168 + const donuts = dash.breakdowns.filter((b) => b.kind === "donut");
169 + const barBreaks = dash.breakdowns.filter((b) => b.kind !== "donut");
122 170
123 171 return (
124 − <div className="container stats-page">
172 + <div className="container stats-page" style={{ opacity: loading ? 0.6 : 1, transition: "opacity 0.2s" }}>
125 173 <span className="kicker">Observatoire — prix d'épicerie au Québec</span>
174 +
175 + {/* 1 · en-tête : titre + export PDF */}
126 176 <div className="stats-head">
127 177 <h1 className="stats-title">L'épicerie, en chiffres</h1>
128 − <a className="btn btn-primary btn-pdf" href="/api/stats/rapport.pdf" download>
129 − ↓ Télécharger le rapport PDF
130 − </a>
178 + <PdfButton period={dash.period.id} from={useCustom ? custom.from : undefined}
179 + to={useCustom ? custom.to : undefined} />
131 180 </div>
132 181 <p className="sub">
133 − Calculé en direct sur les {fmt(g.total)} produits actifs de {fmt(g.sources)} bannières,
134 − répartis dans {fmt(g.categories)} catégories et {fmt(g.brands)} marques.
182 + Tableau de bord calculé sur les données réelles de la plateforme —
183 + catalogue vivant, historique des relevés de prix et journal des
184 + synchronisations. Période : <b>{dash.period.label}</b> ({dash.period.from} → {dash.period.to}).
135 185 </p>
136 186
137 − {/* ---- 1 · tuiles héro ---- */}
138 − <div className="tiles">
139 − <Tile hero v={fmt(g.total)} k="produits suivis" />
140 − <Tile v={fmtPct(g.sale_share * 100)} k={`en solde (${fmt(g.on_sale)} produits)`} />
141 − <Tile v={fmt(g.sources)} k="bannières connectées" />
142 − <Tile v={fmt(g.brands)} k="marques" />
143 − <Tile v={fmt$(g.median_price)} k="prix médian global" />
144 − <Tile v={fmt(g.price_changes_7d)} k="changements de prix (7 j)" />
187 + {/* 2 · sélecteur de période */}
188 + <div style={{ margin: "0 0 22px" }}>
189 + <PeriodSelector
190 + value={useCustom ? "" : period}
191 + onChange={(p) => { setCustom({ from: "", to: "" }); setPeriod(p); }}
192 + custom={custom}
193 + onCustom={(from, to) => setCustom({ from, to })}
194 + />
145 195 </div>
146 196
147 − {/* ---- 2 · panier comparatif ---- */}
148 − <section className="viz-card">
149 − <h2>🧺 Panier comparatif</h2>
150 − <p className="viz-sub">
151 − articles courants × bannières — prix médian des produits correspondants
152 − </p>
153 − {basketCols.length > 0 ? (
154 − <>
155 − <div className="basket-wrap">
156 − <table className="basket-table">
157 − <thead>
158 − <tr>
159 − <th>Article</th>
160 − {basketCols.map((src) => (
161 − <th key={src}
162 − className={src === bestBasket?.source ? "best-col" : ""}>
163 − <span className="basket-th">
164 − <SourceLogo source={src} size={28} fallback="hide" />
165 − {sourceShort(src)}
166 − </span>
167 − </th>
168 − ))}
169 − </tr>
170 − </thead>
171 − <tbody>
172 − {m.basket.map((row) => {
173 − const prices = basketCols
174 − .map((src) => row.by_source[src]?.median_price)
175 − .filter((v): v is number => v != null);
176 − const min = prices.length ? Math.min(...prices) : null;
177 − return (
178 − <tr key={row.item}>
179 − <th>{row.item}</th>
180 − {basketCols.map((src) => {
181 − const cell = row.by_source[src];
182 − const v = cell?.median_price ?? null;
183 − const cls = [
184 − v != null && v === min ? "cell-best" : "",
185 − src === bestBasket?.source ? "best-col" : "",
186 − ].join(" ").trim();
187 − return (
188 − <td key={src} className={cls}
189 − title={cell ? `${fmt(cell.n)} produits correspondants` : undefined}>
190 − {fmt$(v)}
191 − </td>
192 − );
193 − })}
194 − </tr>
195 − );
196 − })}
197 − </tbody>
198 − <tfoot>
199 − <tr>
200 − <th>Total du panier</th>
201 − {basketCols.map((src) => {
202 − const t = totalBySrc[src];
203 − return (
204 − <td key={src}
205 − className={src === bestBasket?.source ? "best-col cell-best" : ""}>
206 − {fmt$(t?.total)}
207 − <small>{t ? `${t.items}/${m.basket.length} articles` : ""}</small>
208 − </td>
209 − );
210 − })}
211 − </tr>
212 − </tfoot>
213 − </table>
214 − </div>
215 − {bestBasket && (
216 − <div className="basket-callout">
217 − 🏆 Panier le moins cher : <b>{sourceName(bestBasket.source)}</b> —{" "}
218 − {fmt$(bestBasket.total)} pour {bestBasket.items} articles
219 − </div>
220 − )}
221 − <p className="stats-foot">
222 − Prix médian des produits correspondant à chaque article chez la bannière ;
223 − seules les bannières couvrant la majorité du panier sont comparées.
224 − </p>
225 − </>
226 − ) : (
227 − <p className="fine">
228 − Pas encore assez de données pour composer le panier — il se remplit à
229 − mesure que les bannières sont synchronisées.
230 − </p>
231 − )}
232 − </section>
197 + {/* 3 · bandeau KPI */}
198 + <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(165px, 1fr))", gap: 14, marginBottom: 26 }}>
199 + {dash.kpis.map((k) => <KpiCard key={k.id} k={k} />)}
200 + </div>
233 201
234 − {/* ---- 3 · bannières en chiffres ---- */}
235 − <section className="viz-card">
236 − <h2>Bannières en chiffres</h2>
237 − <p className="viz-sub">cliquez un en-tête pour trier · cliquez une bannière pour filtrer</p>
238 − <div className="stat-table-wrap">
239 − <table className="stat-table">
240 − <thead>
241 − <tr>
242 − <th>Bannière</th>
243 − <Th k="n" label="Produits" />
244 − <Th k="median_price" label="Prix médian" />
245 − <Th k="sale_share" label="En solde" />
246 − <Th k="avg_discount_pct" label="Rabais moyen" />
247 − <Th k="max_discount_pct" label="Rabais max" />
248 − </tr>
249 − </thead>
250 − <tbody>
251 − {bannerRows.map((r) => (
252 − <tr key={r.source}>
253 − <td>
254 − <Link to={`/?source=${encodeURIComponent(r.source)}`}>
255 − <SourceLogo source={r.source} size={22} name="short" />
256 − </Link>
257 − </td>
258 − <td>{fmt(r.n)}</td>
259 − <td>
260 − {fmt$(r.median_price)}
261 − <span className="mini-track" aria-hidden="true">
262 − <span className="mini-fill"
263 − style={{ width: `${((r.median_price ?? 0) / maxMedian) * 100}%` }} />
264 − </span>
265 − </td>
266 − <td className={r.sale_share > 0 ? "pct-sale" : ""}>
267 − {fmtPct(r.sale_share * 100)}
268 − </td>
269 − <td>{fmtPct(r.avg_discount_pct, 1)}</td>
270 − <td>{fmtPct(r.max_discount_pct, 1)}</td>
271 − </tr>
272 − ))}
273 − </tbody>
274 − </table>
275 − </div>
276 − </section>
202 + {/* 4 · courbes d'évolution */}
203 + <div style={{ display: "grid", gap: 18, marginBottom: 18 }}>
204 + {lines.map((s) => <LineChart key={s.id} serie={s} />)}
205 + {lines.length === 0 && <EmptyBlock title="Évolution sur la période" />}
206 + </div>
277 207
278 − {/* ---- 4 · matrice catégorie × bannière ---- */}
279 − <section className="viz-card">
280 − <h2>Prix médian par catégorie et bannière</h2>
281 − <p className="viz-sub">
282 − {matrixSources.length} plus grandes bannières — le moins cher de chaque rangée en vert
283 − </p>
284 − <div className="stat-table-wrap">
285 − <table className="stat-table matrix-table">
286 − <thead>
287 − <tr>
288 − <th>Catégorie</th>
289 − {matrixSources.map((src) => (
290 − <th key={src} title={sourceName(src)}>
291 − <span className="basket-th">
292 − <SourceLogo source={src} size={24} fallback="hide" />
293 − {sourceShort(src)}
294 − </span>
295 − </th>
296 − ))}
297 − </tr>
298 − </thead>
299 − <tbody>
300 − {matrixRows.map(({ cat, per }) => {
301 − const vals = matrixSources
302 − .map((src) => per[src]?.median_price)
303 − .filter((v): v is number => v != null);
304 − const min = vals.length ? Math.min(...vals) : null;
305 − const max = vals.length ? Math.max(...vals) : null;
306 − return (
307 − <tr key={cat}>
308 − <td>
309 − <Link to={`/?category=${encodeURIComponent(cat)}`}>{cat}</Link>
310 − </td>
311 − {matrixSources.map((src) => {
312 − const cell = per[src];
313 − const v = cell?.median_price ?? null;
314 − let style: React.CSSProperties | undefined;
315 − if (v != null && min != null && max != null) {
316 − if (v === min) style = { background: "rgba(46, 158, 99, 0.16)" };
317 − else if (max > min) {
318 − const t = (v - min) / (max - min);
319 − style = { background: `rgba(232, 84, 47, ${(0.05 + 0.2 * t).toFixed(3)})` };
320 − }
321 − }
322 − return (
323 − <td key={src} style={style}
324 − className={v != null && v === min ? "cell-best" : ""}
325 − title={cell ? `${fmt(cell.n)} produits` : undefined}>
326 − {fmt$(v)}
327 − </td>
328 − );
329 − })}
330 − </tr>
331 − );
332 − })}
333 − </tbody>
334 − </table>
335 − </div>
336 − <div className="matrix-legend">
337 − <span><span className="sw" style={{ background: "rgba(46, 158, 99, 0.3)" }} />moins cher</span>
338 − <span><span className="sw" style={{ background: "rgba(232, 84, 47, 0.25)" }} />plus cher</span>
339 − </div>
340 − </section>
208 + {/* 5 · barres (séries) + répartitions */}
209 + <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 320px), 1fr))", gap: 18, marginBottom: 18 }}>
210 + {barSeries.map((s) => (
211 + <BarChart key={s.id} title={s.title} unit={s.unit}
212 + items={s.points.slice(-14).map((p) => ({ label: p.t, value: p.v }))} />
213 + ))}
214 + {donuts.map((b) => <Donut key={b.id} title={b.title} items={b.items} />)}
215 + {barBreaks.map((b) => <BarChart key={b.id} title={b.title} items={b.items} />)}
216 + </div>
341 217
342 − {/* ---- 5 · distribution des prix ---- */}
343 − <section className="viz-card">
344 − <h2>Distribution des prix</h2>
345 − <p className="viz-sub">produits actifs par palier de prix</p>
346 − <div className="hbars">
347 − {m.price_distribution.map((b) => (
348 − <div className="hbar-row" key={b.range}>
349 − <span className="hbar-label">{b.range}</span>
350 − <span className="hbar-track">
351 − <span className="hbar-fill" style={{ width: `${(b.n / distMax) * 100}%` }} />
352 − </span>
353 − <span className="hbar-value">{fmt(b.n)}</span>
354 − </div>
355 − ))}
218 + {/* 6 · calendrier de chaleur */}
219 + {dash.heatmap && (
220 + <div style={{ marginBottom: 18 }}>
221 + <CalendarHeatmap title={dash.heatmap.title} cells={dash.heatmap.cells} />
356 222 </div>
357 − </section>
223 + )}
358 224
359 − {/* ---- 6 · baisses de prix (7 j) ---- */}
360 − <section className="viz-card">
361 − <h2>📉 Baisses de prix (7 jours)</h2>
362 − <p className="viz-sub">produits dont le prix relevé a diminué depuis la dernière synchronisation</p>
363 − {m.price_drops.length > 0 ? (
364 − <ul className="drops-list">
365 − {m.price_drops.slice(0, 20).map((dr, i) => (
366 − <li key={`${dr.uid}-${i}`}>
367 − <Link to={`/produit/${encodeURIComponent(dr.uid)}`}>
368 − <SourceLogo source={dr.source} size={22} fallback="hide" />
369 − <span className="drop-name">{dr.name}</span>
370 − <span className="drop-prices">
371 − <s>{fmt$(dr.old_price)}</s> → <b>{fmt$(dr.new_price)}</b>
372 − </span>
373 − <span className="drop-pct">−{dr.drop_pct.toLocaleString("fr-CA")} %</span>
374 − </Link>
375 − </li>
376 − ))}
377 − </ul>
378 − ) : (
379 − <p className="fine">
380 − Aucune baisse détectée encore — l'historique se construit à chaque synchronisation.
381 − </p>
382 − )}
383 − </section>
225 + {/* 7 · tableaux détaillés */}
226 + <div style={{ display: "grid", gap: 18, marginBottom: 18 }}>
227 + {dash.tables.map((t) => <DataTable key={t.id} spec={t} />)}
228 + </div>
384 229
385 − {/* ---- aubaines & journal (depuis /api/stats) ---- */}
386 − {d.deals.length > 0 && (
387 − <section className="viz-card">
388 − <h2>Meilleures aubaines du moment 🔥</h2>
389 − <p className="viz-sub">rabais relatif le plus fort, toutes bannières confondues</p>
390 − <div className="grid deals-grid">
391 − {d.deals.slice(0, 12).map((p) => (
392 − <ProductCard key={p.uid} p={p} />
393 − ))}
394 − </div>
395 − <p className="stats-foot">
396 − <Link to="/aubaines">Voir toutes les aubaines →</Link>
397 − </p>
398 − </section>
399 − )}
230 + {/* 8 · panier comparatif (section métier Food-Ka) */}
231 + {basket && <BasketSection m={basket} />}
400 232
401 − {d.recent_syncs.length > 0 && (
402 − <section className="viz-card">
403 − <h2>Dernières synchronisations</h2>
404 − <ul className="alertes">
405 − {d.recent_syncs.map((s) => (
406 − <li key={s.id}>
407 − {s.ok ? "✅" : "⚠️"} <b>{sourceName(s.source)}</b> — {fmtTs(s.ts)} ·{" "}
408 − {fmt(s.found)} produits trouvés, {fmt(s.added)} ajoutés,{" "}
409 − {fmt(s.updated)} mis à jour, {fmt(s.removed)} retirés
410 − {s.message ? ` — ${s.message}` : ""}
411 − </li>
412 − ))}
413 − </ul>
233 + {/* 9 · records & faits marquants */}
234 + {dash.records.length > 0 && (
235 + <section style={{ margin: "18px 0" }}>
236 + <h2 style={{ fontSize: 19, textTransform: "uppercase" }}>Records &amp; faits marquants</h2>
237 + <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 300px), 1fr))", gap: 12 }}>
238 + {dash.records.map((r) => <RecordCard key={r.label} r={r} />)}
239 + </div>
414 240 </section>
415 241 )}
416 242
243 + {/* 10 · fraîcheur + pied */}
244 + <div style={{ display: "flex", flexWrap: "wrap", gap: 12, alignItems: "center", justifyContent: "space-between", marginTop: 24 }}>
245 + <Fraicheur updated={dash.updated} onRefresh={load} />
246 + <PdfButton period={dash.period.id} from={useCustom ? custom.from : undefined}
247 + to={useCustom ? custom.to : undefined} />
248 + </div>
417 249 <p className="stats-foot">
418 − Données recalculées à chaque synchronisation. Les catégories et bannières
419 − renvoient vers les produits filtrés correspondants.{" "}
250 + Données réelles recalculées à chaque synchronisation (cache 5 min) —
251 + rien d'inventé : une mesure indisponible est affichée « Pas encore mesuré ».{" "}
420 252 <Link to="/sources">Voir le registre complet des sources →</Link>
421 253 </p>
422 254 </div>
modified requirements.txt +1 −0
@@ -5,4 +5,5 @@ uvicorn>=0.29
5 5 requests>=2.31
6 6 beautifulsoup4>=4.12
7 7 reportlab>=4.0
8 +fpdf2>=2.7
8 9 pillow>=10.0
9 10