# Auteur : Simon-Pierre Boucher — contact@spboucher.ai # ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2). # Consomme le JSON du contrat /api/stats/dashboard (voir SPEC.md) et produit # le rapport estampillé Groupe-KA : couverture, sommaire, KPI, graphiques # VECTORIELS (courbes/barres/anneaux), tableaux paginés, records, page de fin. # Usage : # from kapdf import GroupeKAReport # pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00", # "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json, # mode="complet").build() # Dépendance : pip install fpdf2 (aucune autre) from __future__ import annotations import math from datetime import datetime from zoneinfo import ZoneInfo from fpdf import FPDF INK = (20, 24, 20) INK2 = (77, 85, 81) INK3 = (139, 146, 140) PAPER = (245, 243, 238) SURFACE2 = (250, 249, 245) GREEN = (28, 92, 65) DANGER = (179, 66, 58) WHITE = (255, 255, 255) EMAILS = [ ("contact@groupe-ka.com", "Projets, partenariats & données"), ("info@groupe-ka.com", "Médias & questions générales"), ("admin@groupe-ka.com", "Légal, vie privée & Loi 25"), ] DISCLAIMER = ( "Groupe KA est un agrégateur de contenu : nous ne vendons rien, ne louons " "rien et ne sommes partie à aucune transaction. Données lues à la source, " "rien d'inventé, tout est traçable." ) def _hex(c: str) -> tuple[int, int, int]: c = c.lstrip("#") return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore def _fr(n) -> str: if isinstance(n, float) and not n.is_integer(): return f"{n:,.2f}".replace(",", " ").replace(".", ",") return f"{int(n):,}".replace(",", " ") _SUBST = { "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-", "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"', "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ", } def _latin1(s: str) -> str: for k, v in _SUBST.items(): s = s.replace(k, v) return s.encode("latin-1", "replace").decode("latin-1") class _PDF(FPDF): """FPDF avec en-tête/pied Groupe-KA sur chaque page (sauf couverture). Les polices core sont latin-1 : normalize_text sanitise en amont.""" def normalize_text(self, text): return super().normalize_text(_latin1(text)) def __init__(self, brand: str, accent: tuple, period_label: str): super().__init__(orientation="P", unit="mm", format="A4") self.brand = brand self.accent = accent self.period_label = period_label self.cover_mode = False self.set_margins(18, 20, 18) self.set_auto_page_break(True, margin=22) def header(self): if self.cover_mode or self.page_no() == 1: return self.set_font("helvetica", "B", 8.5) self.set_text_color(*INK) self.set_xy(18, 9) self.cell(0, 5, f"Groupe KA · {self.brand}") self.set_font("helvetica", "", 8) self.set_text_color(*INK3) self.set_xy(18, 9) self.cell(0, 5, "Rapport statistique", align="R") self.set_draw_color(*INK) self.set_line_width(0.5) self.line(18, 15.5, 192, 15.5) self.set_y(20) def footer(self): # page 1 = couverture (le flag cover_mode est déjà retombé quand # add_page() clôt la page 1 → tester aussi le numéro de page) if self.cover_mode or self.page_no() == 1: return self.set_y(-15) self.set_draw_color(*INK3) self.set_line_width(0.2) self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5) self.set_font("helvetica", "", 7.5) self.set_text_color(*INK3) year = datetime.now(ZoneInfo("America/Toronto")).year self.cell(130, 5, f"© Groupe-KA — {year} — groupe-ka.com · {self.period_label}") self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R") class GroupeKAReport: def __init__(self, site: dict, dashboard: dict, mode: str = "complet"): self.site = site self.d = dashboard self.mode = mode self.accent = _hex(site.get("accent", "#d9f26b")) period = dashboard.get("period", {}) or {} self.period_label = period.get("label") or "toute la période" self.pdf = _PDF(site.get("wordmark", ""), self.accent, self.period_label) self.toc: list[tuple[str, int]] = [] # ---------- primitives ---------- def _card(self, x, y, w, h, fill=WHITE): p = self.pdf p.set_draw_color(*INK) p.set_line_width(0.45) p.set_fill_color(*fill) p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2) def _kicker(self, text): p = self.pdf p.set_font("helvetica", "B", 8) p.set_text_color(*GREEN) p.set_draw_color(*GREEN) p.set_line_width(0.6) y = p.get_y() + 2 p.line(p.l_margin, y, p.l_margin + 7, y) p.set_xy(p.l_margin + 9, y - 2.5) p.cell(0, 5, text.upper()) p.ln(8) def _section_title(self, title): if self.pdf.get_y() > 240: self.pdf.add_page() self._kicker("Groupe KA · " + self.site.get("wordmark", "")) self.pdf.set_font("helvetica", "B", 15) self.pdf.set_text_color(*INK) self.pdf.set_x(self.pdf.l_margin) self.pdf.cell(0, 8, title) self.toc.append((title, self.pdf.page_no())) self.pdf.ln(11) # ---------- pages ---------- def _cover(self): p = self.pdf p.cover_mode = True p.set_auto_page_break(False) p.add_page() p.set_fill_color(*PAPER) p.rect(0, 0, 210, 297, style="F") p.set_draw_color(*INK) p.set_line_width(1.0) p.rect(10, 10, 190, 277) # kicker p.set_font("helvetica", "B", 10) p.set_text_color(*GREEN) p.set_xy(24, 34) p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE") # wordmark : partie gauche + boîte encre/accent wm = self.site.get("wordmark", "") left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None) p.set_xy(24, 70) p.set_font("helvetica", "B", 40) p.set_text_color(*INK) p.cell(p.get_string_width(left) + 2, 20, left) if boxed: bw = p.get_string_width(boxed) + 12 x = p.get_x() + 2 p.set_fill_color(*INK) p.rect(x, 68, bw, 22, style="F", round_corners=True, corner_radius=3) p.set_text_color(*self.accent) p.set_xy(x + 6, 70) p.cell(bw - 12, 18, boxed) p.set_xy(24, 100) p.set_font("helvetica", "", 13) p.set_text_color(*INK2) p.multi_cell(150, 7, f"Rapport statistique — {wm}") now = datetime.now(ZoneInfo("America/Toronto")) per = self.d.get("period", {}) or {} p.set_xy(24, 125) p.set_font("helvetica", "", 10.5) rows = [ ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")), ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"), ("Plateforme", "https://" + self.site.get("domain", "")), ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"), ] y = 128 for k, v in rows: p.set_xy(24, y) p.set_text_color(*INK3) p.cell(40, 6, k) p.set_text_color(*INK) p.set_font("helvetica", "B", 10.5) p.cell(0, 6, str(v)) p.set_font("helvetica", "", 10.5) y += 8 # bande encre au pied p.set_fill_color(*INK) p.rect(10, 262, 190, 25, style="F") p.set_xy(24, 270) p.set_font("helvetica", "B", 12) p.set_text_color(*WHITE) p.cell(60, 8, "par Groupe ") p.set_text_color(*self.accent) p.set_xy(24 + p.get_string_width("par Groupe ") + 1, 270) p.cell(20, 8, "KA") p.set_font("helvetica", "B", 10) p.set_xy(24, 270) p.set_text_color(*self.accent) p.cell(162, 8, "groupe-ka.com", align="R") p.set_auto_page_break(True, margin=22) p.cover_mode = False def _kpis(self): kpis = self.d.get("kpis") or [] if not kpis: return self._section_title("Synthèse des indicateurs") p = self.pdf cols, gw, gh, gap = 3, 56, 26, 3 x0, y = p.l_margin, p.get_y() for i, k in enumerate(kpis[:9]): x = x0 + (i % cols) * (gw + gap) if i and i % cols == 0: y += gh + gap if y > 250: p.add_page(); y = p.get_y() self._card(x, y, gw, gh) p.set_xy(x + 4, y + 4) p.set_font("helvetica", "B", 14) p.set_text_color(*INK) val = k.get("value") p.cell(gw - 8, 7, (_fr(val) if isinstance(val, (int, float)) else str(val)) + (" " + k["unit"] if k.get("unit") else "")) p.set_xy(x + 4, y + 12) p.set_font("helvetica", "", 7.6) p.set_text_color(*INK2) p.multi_cell(gw - 8, 3.6, str(k.get("label", ""))[:70]) if k.get("delta_pct") is not None: up = (k.get("direction") or ("up" if k["delta_pct"] >= 0 else "down")) == "up" p.set_xy(x + 4, y + gh - 6.5) p.set_font("helvetica", "B", 8) p.set_text_color(*(GREEN if up else DANGER)) arrow = "+" if k["delta_pct"] >= 0 else "" p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(k['delta_pct']).replace('.', ',')} % vs période préc.") p.set_y(y + gh + 8) def _line_chart(self, s): p = self.pdf pts = s.get("points") or [] if len(pts) < 2: return if p.get_y() > 200: p.add_page() p.set_font("helvetica", "B", 10) p.set_text_color(*INK) p.cell(0, 6, s.get("title", "")) p.ln(7) x0, y0, w, h = p.l_margin, p.get_y(), 174, 52 self._card(x0, y0, w, h, fill=WHITE) cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16 vals = [pt["v"] for pt in pts] + [c["v"] for c in (s.get("compare") or [])] vmax = max(vals) or 1 vmin = min(0, min(vals)) rng = (vmax - vmin) or 1 # grille + graduations p.set_font("helvetica", "", 6.3) p.set_text_color(*INK3) p.set_draw_color(200, 200, 195) p.set_line_width(0.15) for g in range(5): gy = cy + ch - ch * g / 4 p.line(cx, gy, cx + cw, gy) p.set_xy(x0 + 1, gy - 1.6) p.cell(10, 3, _fr(vmin + rng * g / 4), align="R") def draw(series, color, width, dash=None): n = len(series) p.set_draw_color(*color) p.set_line_width(width) if dash: p.set_dash_pattern(dash=1.2, gap=1.2) last = None for i, pt in enumerate(series): px = cx + cw * (i / (n - 1)) py = cy + ch - ch * ((pt["v"] - vmin) / rng) if last: p.line(last[0], last[1], px, py) last = (px, py) p.set_dash_pattern() if s.get("compare"): draw(s["compare"], INK3, 0.35, dash=True) draw(pts, self.accent, 0.7) # libellés d'axe X (premier / milieu / dernier) p.set_text_color(*INK3) for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)): p.set_xy(cx + cw * frac - 9, cy + ch + 1.5) p.cell(18, 3, str(pts[idx].get("t", ""))[:10], align="C") p.set_y(y0 + h + 4) if s.get("compare"): p.set_font("helvetica", "", 6.8) p.set_text_color(*INK3) p.cell(0, 4, "— période courante (accent) · ---- période comparée") p.ln(6) else: p.ln(2) def _bars(self, title, items, unit=""): p = self.pdf items = [it for it in (items or []) if isinstance(it.get("value"), (int, float))][:12] if not items: return need = 10 + len(items) * 7 if p.get_y() + need > 265: p.add_page() p.set_font("helvetica", "B", 10) p.set_text_color(*INK) p.cell(0, 6, title) p.ln(8) vmax = max(it["value"] for it in items) or 1 for it in items: y = p.get_y() p.set_font("helvetica", "", 7.6) p.set_text_color(*INK) p.set_x(p.l_margin) p.cell(46, 5, str(it["label"])[:34]) bw = 96 * (it["value"] / vmax) p.set_fill_color(*self.accent) p.set_draw_color(*INK) p.set_line_width(0.25) p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF") p.set_xy(p.l_margin + 148, y) p.set_font("helvetica", "B", 7.6) p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R") p.ln(6.4) p.ln(3) def _donut(self, b): # anneau vectoriel simple (arcs) + légende p = self.pdf items = [it for it in (b.get("items") or []) if it.get("value")][:8] total = sum(it["value"] for it in items) if not items or not total: return if p.get_y() > 210: p.add_page() p.set_font("helvetica", "B", 10) p.set_text_color(*INK) p.cell(0, 6, b.get("title", "")) p.ln(8) cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20 shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10] start = -90.0 for i, it in enumerate(items): frac = it["value"] / total f = shades[i % len(shades)] col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) steps = max(2, int(72 * frac)) p.set_fill_color(*col) p.set_draw_color(*col) for st in range(steps): a0 = math.radians(start + 360 * frac * st / steps) a1 = math.radians(start + 360 * frac * (st + 1) / steps) p.polygon( [(cx, cy), (cx + r * math.cos(a0), cy + r * math.sin(a0)), (cx + r * math.cos(a1), cy + r * math.sin(a1))], style="DF", ) start += 360 * frac p.set_fill_color(*WHITE) p.set_draw_color(*INK) p.set_line_width(0.4) p.ellipse(cx - 11, cy - 11, 22, 22, style="DF") p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D") # légende ly = cy - 22 for i, it in enumerate(items): f = shades[i % len(shades)] col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) p.set_fill_color(*col) p.set_draw_color(*INK) p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF") p.set_xy(p.l_margin + 66, ly) p.set_font("helvetica", "", 7.6) p.set_text_color(*INK) pct = 100 * it["value"] / total p.cell(0, 5.6, f"{str(it['label'])[:40]} — {_fr(it['value'])} ({pct:.1f} %)".replace(".", ",")) ly += 5.6 p.set_y(max(cy + r, ly) + 6) def _table(self, t): p = self.pdf cols = t.get("columns") or [] rows = t.get("rows") or [] if not cols or not rows: return self._section_title(t.get("title", "Tableau")) w = 174 / len(cols) def head(): p.set_font("helvetica", "B", 7.6) p.set_fill_color(*INK) p.set_text_color(*WHITE) for c in cols: p.cell(w, 6, " " + str(c)[:30], fill=True) p.ln(6) head() p.set_text_color(*INK) for i, row in enumerate(rows[:200]): if p.get_y() > 262: p.add_page() head() p.set_text_color(*INK) p.set_font("helvetica", "", 7.4) p.set_fill_color(*(SURFACE2 if i % 2 else WHITE)) for cell in row: txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell) p.cell(w, 5.4, " " + txt[:34], fill=True) p.ln(5.4) if len(rows) > 200: p.set_font("helvetica", "", 7) p.set_text_color(*INK3) p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées") p.ln(6) def _records(self): recs = self.d.get("records") or [] if not recs: return self._section_title("Records & faits marquants") p = self.pdf for r in recs[:10]: if p.get_y() > 258: p.add_page() y = p.get_y() self._card(p.l_margin, y, 174, 11, fill=SURFACE2) p.set_xy(p.l_margin + 4, y + 2) p.set_font("helvetica", "", 8.6) p.set_text_color(*INK2) p.cell(96, 7, str(r.get("label", ""))[:70]) p.set_font("helvetica", "B", 9) p.set_text_color(*INK) p.cell(52, 7, str(r.get("value", ""))[:36], align="R") p.set_font("helvetica", "", 7.6) p.set_text_color(*INK3) p.cell(20, 7, str(r.get("date", "") or ""), align="R") p.set_y(y + 13.5) p.ln(4) def _final_page(self): p = self.pdf p.add_page() self._kicker("Groupe KA · contact") p.set_font("helvetica", "B", 15) p.set_text_color(*INK) p.cell(0, 8, "Coordonnées du Groupe KA") p.ln(12) for email, role in EMAILS: p.set_font("helvetica", "B", 10.5) p.set_text_color(*INK) p.cell(0, 6, email) p.ln(5.5) p.set_font("helvetica", "", 8.6) p.set_text_color(*INK3) p.cell(0, 5, role) p.ln(8) p.ln(2) p.set_font("helvetica", "B", 10) p.set_text_color(*GREEN) p.cell(0, 6, "groupe-ka.com — le portail de l'écosystème ·Ka") p.ln(10) p.set_draw_color(*self.accent) p.set_line_width(0.8) p.line(p.l_margin, p.get_y(), p.l_margin + 30, p.get_y()) p.ln(4) p.set_font("helvetica", "", 8.6) p.set_text_color(*INK2) p.multi_cell(160, 4.6, DISCLAIMER) p.ln(4) p.set_font("helvetica", "", 7.6) p.set_text_color(*INK3) p.multi_cell( 160, 4.2, "Mentions : rapport généré automatiquement à partir des données réelles de la " "plateforme au moment indiqué en couverture. Conditions d'utilisation, politique " "de confidentialité et protection des renseignements personnels (Loi 25) : " "groupe-ka.com/conditions · /confidentialite · /loi-25.", ) def _toc_page(self): # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en # page 2 en réservant la page lors du build (voir build()). pass def build(self) -> bytes: p = self.pdf p.alias_nb_pages() self._cover() if self.mode == "synthese": p.add_page() self._kpis() self._records() self._final_page() else: p.add_page() toc_page_no = p.page_no() p.add_page() self._kpis() for s in self.d.get("series") or []: if s.get("kind") == "bar": self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", "")) else: self._line_chart(s) for b in self.d.get("breakdowns") or []: if b.get("kind") == "donut": self._donut(b) else: self._bars(b.get("title", ""), b.get("items")) geo = self.d.get("geo") if geo: self._bars(geo.get("title", "Répartition géographique"), geo.get("items")) for t in self.d.get("tables") or []: self._table(t) self._records() self._final_page() # sommaire écrit sur la page réservée (page 2) last_page = p.page p.page = toc_page_no p.set_y(22) p.set_font("helvetica", "B", 15) p.set_text_color(*INK) p.cell(0, 8, "Sommaire") p.ln(12) p.set_font("helvetica", "", 9.5) for title, page_no in self.toc: p.set_text_color(*INK) p.cell(140, 6.5, title[:80]) p.set_text_color(*INK3) p.cell(0, 6.5, str(page_no), align="R") p.ln(6.5) p.page = last_page return bytes(p.output()) def filename(platform_id: str, period: str) -> str: today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d") return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf"