SPB Git

Repository Public

reportpdf.py 53.7 KB 1,351 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/kapdf.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1713# Last Modified    : 2026-08-2314#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# Auteur : Simon-Pierre Boucher — contact@spboucher.ai88# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2). v389# Consomme le JSON du contrat /api/stats/dashboard (voir SPEC.md) et produit90# les rapports estampillés Groupe-KA. 5 modes fixes :91#   complet      — toutes les sections (KPI, jauges, séries + stats, multi-92#                  séries, empilées, distributions, répartitions, géo,93#                  heatmap horaire, tableaux, records)94#   synthese     — couverture + KPI + records (2-3 pages)95#   tendances    — KPI + toutes les séries temporelles + stats de séries96#   repartitions — breakdowns, distributions, géo, activité horaire97#   donnees      — tous les tableaux en version longue (400 lignes max)98# v3 : mode « personnalise » — l'utilisateur compose son rapport bloc par99# bloc (choix des données ET du rendu par bloc : courbe/aire/barres/anneau/100# heatmap/tableau…). catalog(dash) expose les blocs disponibles ; le rapport101# suit une spec {"title": str, "blocks": [{"key": "series:ajouts",102# "render": "bar"}, …]} et respecte l'ordre demandé.103# Graphiques VECTORIELS uniquement (primitives fpdf), accent de la marque.104# Usage :105#   from kapdf import MarketReport, REPORT_MODES, catalog, filename106#   pdf_bytes = MarketReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00",107#       "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json,108#       mode="complet").build()109#   pdf_bytes = MarketReport(site=SITE, dashboard=dash, mode="personnalise",110#       spec={"title": "Mon rapport", "blocks": [...]}).build()111# Dépendance : pip install fpdf2  (aucune autre)112from __future__ import annotations113114import math115from datetime import datetime116from zoneinfo import ZoneInfo117118from fpdf import FPDF119120INK = (20, 24, 20)121INK2 = (77, 85, 81)122INK3 = (139, 146, 140)123PAPER = (245, 243, 238)124SURFACE2 = (250, 249, 245)125GREEN = (28, 92, 65)126DANGER = (179, 66, 58)127WHITE = (255, 255, 255)128129REPORT_MODES = {130    "complet": "Rapport complet",131    "synthese": "Synthèse exécutive",132    "tendances": "Tendances & évolution",133    "repartitions": "Répartitions & géographie",134    "donnees": "Données détaillées",135}136# v3 — mode composé par l'utilisateur (jamais dans le menu des modes fixes)137CUSTOM_MODE = "personnalise"138CUSTOM_LABEL = "Rapport personnalisé"139140# v3 — rendus proposés par type de bloc (le 1er est le rendu par défaut ;141# « table » est toujours offert : toute donnée a un équivalent tableau)142RENDER_LABELS = {143    "line": "Courbe", "area": "Aire", "bar": "Barres verticales",144    "bars": "Barres horizontales", "donut": "Anneau",145    "lines": "Multi-courbes", "stacked": "Barres empilées",146    "histogram": "Histogramme", "heatmap": "Heatmap",147    "cards": "Cartes", "gauges": "Jauges", "table": "Tableau",148}149SECTION_LABELS = {150    "kpis": "Indicateurs", "gauges": "Taux & couvertures",151    "series": "Évolution", "multiseries": "Comparaisons",152    "stacked": "Compositions", "breakdowns": "Répartitions",153    "distributions": "Distributions", "geo": "Géographie",154    "heatmap": "Calendrier", "hourly": "Activité horaire",155    "tables": "Tableaux", "records": "Records",156}157158159def catalog(dash: dict) -> list[dict]:160    """v3 — blocs composables d'un dashboard : ce que le constructeur de161    rapports personnalisés peut inclure, avec les rendus compatibles.162    key = section[:id] ; l'ordre renvoyé = ordre naturel du dashboard."""163    out: list[dict] = []164165    def add(key, title, renders, default=None, count=None):166        b = {"key": key, "section": key.split(":")[0], "title": title,167             "renders": renders, "default_render": default or renders[0]}168        if count is not None:169            b["count"] = count170        out.append(b)171172    if dash.get("kpis"):173        add("kpis", "Indicateurs clés (KPI)", ["cards", "table"],174            count=len(dash["kpis"]))175    gs = [g for g in (dash.get("gauges") or [])176          if isinstance(g.get("value"), (int, float)) and g.get("max")]177    if gs:178        add("gauges", "Taux & couvertures (jauges)", ["gauges", "table"],179            count=len(gs))180    for s in dash.get("series") or []:181        if len(s.get("points") or []) < 2:182            continue183        kind = s.get("kind") or "line"184        default = kind if kind in ("line", "area", "bar") else "line"185        add(f"series:{s.get('id')}", s.get("title", ""),186            ["line", "area", "bar", "table"], default,187            len(s.get("points") or []))188    for ms in dash.get("multiseries") or []:189        if not (ms.get("series") or []):190            continue191        add(f"multiseries:{ms.get('id')}", ms.get("title", ""),192            ["lines", "table"], count=len(ms["series"]))193    for st in dash.get("stacked") or []:194        if not (st.get("points") or []):195            continue196        add(f"stacked:{st.get('id')}", st.get("title", ""),197            ["stacked", "table"], count=len(st.get("keys") or []))198    for b in dash.get("breakdowns") or []:199        if not (b.get("items") or []):200            continue201        default = "donut" if b.get("kind") == "donut" else "bars"202        add(f"breakdowns:{b.get('id')}", b.get("title", ""),203            ["donut", "bars", "table"], default, len(b["items"]))204    for d in dash.get("distributions") or []:205        if not (d.get("bins") or []):206            continue207        add(f"distributions:{d.get('id')}", d.get("title", ""),208            ["histogram", "table"], count=len(d["bins"]))209    geo = dash.get("geo") or {}210    if geo.get("items"):211        add("geo", geo.get("title", "Répartition géographique"),212            ["bars", "table"], count=len(geo["items"]))213    hm = dash.get("heatmap") or {}214    if hm.get("cells"):215        add("heatmap", hm.get("title", "Calendrier d'activité"),216            ["heatmap", "table"])217    hr = dash.get("hourly") or {}218    if hr.get("cells"):219        add("hourly", hr.get("title", "Activité par jour et heure"),220            ["heatmap", "table"])221    for t in dash.get("tables") or []:222        if not (t.get("rows") or []):223            continue224        add(f"tables:{t.get('id')}", t.get("title", ""), ["table"],225            count=len(t["rows"]))226    if dash.get("records"):227        add("records", "Records & faits marquants", ["cards", "table"],228            count=len(dash["records"]))229    return out230231EMAILS = [232    ("contact@spboucher.ai", "Projets, partenariats & données"),233    ("contact@spboucher.ai", "Médias & questions générales"),234    ("contact@spboucher.ai", "Légal, vie privée & Loi 25"),235]236DISCLAIMER = (237    "Lou-Ka est un agrégateur de contenu : nous ne vendons rien, ne louons "238    "rien et ne sommes partie à aucune transaction. Données lues à la source, "239    "rien d'inventé, tout est traçable."240)241242243def _hex(c: str) -> tuple[int, int, int]:244    c = c.lstrip("#")245    return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4))  # type: ignore246247248def _fr(n) -> str:249    if isinstance(n, float) and not n.is_integer():250        return f"{n:,.2f}".replace(",", " ").replace(".", ",")251    return f"{int(n):,}".replace(",", " ")252253254_SUBST = {255    "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",256    "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',257    "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",258    "×": "x", "·": ".", "σ": "sigma", "Δ": "delta",259}260261262def _latin1(s: str) -> str:263    for k, v in _SUBST.items():264        s = s.replace(k, v)265    return s.encode("latin-1", "replace").decode("latin-1")266267268class _PDF(FPDF):269    """FPDF avec en-tête/pied Lou-Ka sur chaque page (sauf couverture).270    Les polices core sont latin-1 : normalize_text sanitise en amont."""271272    def normalize_text(self, text):273        return super().normalize_text(_latin1(text))274275    def __init__(self, brand: str, accent: tuple, period_label: str):276        super().__init__(orientation="P", unit="mm", format="A4")277        self.brand = brand278        self.accent = accent279        self.period_label = period_label280        self.cover_mode = False281        self.set_margins(18, 20, 18)282        self.set_auto_page_break(True, margin=22)283284    def header(self):285        if self.cover_mode or self.page_no() == 1:286            return287        self.set_font("helvetica", "B", 8.5)288        self.set_text_color(*INK)289        self.set_xy(18, 9)290        self.cell(0, 5, f"{self.brand}")291        self.set_font("helvetica", "", 8)292        self.set_text_color(*INK3)293        self.set_xy(18, 9)294        self.cell(0, 5, "Rapport statistique", align="R")295        self.set_draw_color(*INK)296        self.set_line_width(0.5)297        self.line(18, 15.5, 192, 15.5)298        self.set_y(20)299300    def footer(self):301        # page 1 = couverture (le flag cover_mode est déjà retombé quand302        # add_page() clôt la page 1 → tester aussi le numéro de page)303        if self.cover_mode or self.page_no() == 1:304            return305        self.set_y(-15)306        self.set_draw_color(*INK3)307        self.set_line_width(0.2)308        self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5)309        self.set_font("helvetica", "", 7.5)310        self.set_text_color(*INK3)311        year = datetime.now(ZoneInfo("America/Toronto")).year312        self.cell(130, 5, f"© Lou-Ka — {year} — lou-ka.com · {self.period_label}")313        self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R")314315316class MarketReport:317    def __init__(self, site: dict, dashboard: dict, mode: str = "complet",318                 spec: dict | None = None):319        self.site = site320        self.d = dashboard321        self.mode = mode if (mode in REPORT_MODES or mode == CUSTOM_MODE) else "complet"322        self.spec = spec or {}323        self.accent = _hex(site.get("accent", "#d9f26b"))324        period = dashboard.get("period", {}) or {}325        self.period_label = period.get("label") or "toute la période"326        self.pdf = _PDF(site.get("wordmark", ""), self.accent, self.period_label)327        self.toc: list[tuple[str, int]] = []328329    @property330    def mode_label(self) -> str:331        if self.mode == CUSTOM_MODE:332            t = str(self.spec.get("title") or "").strip()333            return f"{CUSTOM_LABEL} — {t}" if t else CUSTOM_LABEL334        return REPORT_MODES[self.mode]335336    # ---------- primitives ----------337    def _card(self, x, y, w, h, fill=WHITE):338        p = self.pdf339        p.set_draw_color(*INK)340        p.set_line_width(0.45)341        p.set_fill_color(*fill)342        p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)343344    def _shade(self, i, n=8):345        shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]346        f = shades[i % len(shades)]347        return tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))348349    def _kicker(self, text):350        p = self.pdf351        p.set_font("helvetica", "B", 8)352        p.set_text_color(*GREEN)353        p.set_draw_color(*GREEN)354        p.set_line_width(0.6)355        y = p.get_y() + 2356        p.line(p.l_margin, y, p.l_margin + 7, y)357        p.set_xy(p.l_margin + 9, y - 2.5)358        p.cell(0, 5, text.upper())359        p.ln(8)360361    def _section_title(self, title):362        if self.pdf.get_y() > 240:363            self.pdf.add_page()364        self._kicker(self.site.get("wordmark", ""))365        self.pdf.set_font("helvetica", "B", 15)366        self.pdf.set_text_color(*INK)367        self.pdf.set_x(self.pdf.l_margin)368        self.pdf.cell(0, 8, title)369        self.toc.append((title, self.pdf.page_no()))370        self.pdf.ln(11)371372    def _chart_title(self, title):373        p = self.pdf374        p.set_font("helvetica", "B", 10)375        p.set_text_color(*INK)376        p.set_x(p.l_margin)377        p.cell(0, 6, title)378        p.ln(7)379380    # ---------- pages ----------381    def _cover(self):382        p = self.pdf383        p.cover_mode = True384        p.set_auto_page_break(False)385        p.add_page()386        p.set_fill_color(*PAPER)387        p.rect(0, 0, 210, 297, style="F")388        p.set_draw_color(*INK)389        p.set_line_width(1.0)390        p.rect(10, 10, 190, 277)391        p.set_font("helvetica", "B", 10)392        p.set_text_color(*GREEN)393        p.set_xy(24, 34)394        p.cell(0, 6, "LOU-KA · RAPPORT STATISTIQUE")395        wm = self.site.get("wordmark", "")396        left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)397        p.set_xy(24, 70)398        p.set_font("helvetica", "B", 40)399        p.set_text_color(*INK)400        p.cell(p.get_string_width(left) + 2, 20, left)401        if boxed:402            bw = p.get_string_width(boxed) + 12403            x = p.get_x() + 2404            p.set_fill_color(*INK)405            p.rect(x, 68, bw, 22, style="F", round_corners=True, corner_radius=3)406            p.set_text_color(*self.accent)407            p.set_xy(x + 6, 70)408            p.cell(bw - 12, 18, boxed)409        p.set_xy(24, 100)410        p.set_font("helvetica", "", 13)411        p.set_text_color(*INK2)412        p.multi_cell(150, 7, f"{self.mode_label} — {wm}")413        now = datetime.now(ZoneInfo("America/Toronto"))414        per = self.d.get("period", {}) or {}415        p.set_xy(24, 125)416        p.set_font("helvetica", "", 10.5)417        rows = [418            ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),419            ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),420            ("Plateforme", "https://" + self.site.get("domain", "")),421            ("Type de rapport", self.mode_label),422        ]423        y = 128424        for k, v in rows:425            p.set_xy(24, y)426            p.set_text_color(*INK3)427            p.cell(40, 6, k)428            p.set_text_color(*INK)429            p.set_font("helvetica", "B", 10.5)430            p.cell(0, 6, str(v))431            p.set_font("helvetica", "", 10.5)432            y += 8433        p.set_fill_color(*INK)434        p.rect(10, 262, 190, 25, style="F")435        p.set_xy(24, 270)436        p.set_font("helvetica", "B", 12)437        p.set_text_color(*WHITE)438        p.cell(60, 8, "Lou-Ka")439        p.set_font("helvetica", "B", 10)440        p.set_xy(24, 270)441        p.set_text_color(*self.accent)442        p.cell(162, 8, "lou-ka.com", align="R")443        p.set_auto_page_break(True, margin=22)444        p.cover_mode = False445446    def _kpis(self):447        kpis = self.d.get("kpis") or []448        if not kpis:449            return450        self._section_title("Synthèse des indicateurs")451        p = self.pdf452        cols, gw, gh, gap = 3, 56, 26, 3453        x0, y = p.l_margin, p.get_y()454        for i, k in enumerate(kpis[:12]):455            x = x0 + (i % cols) * (gw + gap)456            if i and i % cols == 0:457                y += gh + gap458            if y > 250:459                p.add_page(); y = p.get_y()460            self._card(x, y, gw, gh)461            p.set_xy(x + 4, y + 4)462            p.set_font("helvetica", "B", 14)463            p.set_text_color(*INK)464            val = k.get("value")465            p.cell(gw - 8, 7, (_fr(val) if isinstance(val, (int, float)) else str(val)) + (" " + k["unit"] if k.get("unit") else ""))466            p.set_xy(x + 4, y + 12)467            p.set_font("helvetica", "", 7.6)468            p.set_text_color(*INK2)469            p.multi_cell(gw - 8, 3.6, str(k.get("label", ""))[:70])470            if k.get("delta_pct") is not None:471                up = (k.get("direction") or ("up" if k["delta_pct"] >= 0 else "down")) == "up"472                p.set_xy(x + 4, y + gh - 6.5)473                p.set_font("helvetica", "B", 8)474                p.set_text_color(*(GREEN if up else DANGER))475                arrow = "+" if k["delta_pct"] >= 0 else ""476                dv = round(float(k["delta_pct"]), 1)477                dv = int(dv) if float(dv).is_integer() else dv478                p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(dv).replace('.', ',')} % vs période préc.")479        p.set_y(y + gh + 8)480481    def _gauges(self):482        gs = self.d.get("gauges") or []483        gs = [g for g in gs if isinstance(g.get("value"), (int, float)) and g.get("max")]484        if not gs:485            return486        self._section_title("Taux & couvertures")487        p = self.pdf488        cols, gw, gh, gap = 3, 56, 34, 3489        x0, y = p.l_margin, p.get_y()490        for i, g in enumerate(gs[:9]):491            x = x0 + (i % cols) * (gw + gap)492            if i and i % cols == 0:493                y += gh + gap494            if y > 240:495                p.add_page(); y = p.get_y()496            self._card(x, y, gw, gh)497            frac = max(0.0, min(1.0, g["value"] / g["max"]))498            cx, cy, r = x + gw / 2, y + 20, 14499            # arc de fond + arc de valeur (demi-cercle en petits segments)500            for pass_col, pass_frac, lw in (((225, 223, 217), 1.0, 2.6), (self.accent, frac, 2.6)):501                p.set_draw_color(*pass_col)502                p.set_line_width(lw)503                steps = max(2, int(60 * pass_frac))504                last = None505                for st in range(steps + 1):506                    a = math.pi + math.pi * pass_frac * st / steps507                    pt = (cx + r * math.cos(a), cy + r * math.sin(a))508                    if last:509                        p.line(last[0], last[1], pt[0], pt[1])510                    last = pt511            p.set_font("helvetica", "B", 11)512            p.set_text_color(*INK)513            p.set_xy(x + 4, cy - 5)514            p.cell(gw - 8, 6, f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}", align="C")515            p.set_font("helvetica", "", 6.6)516            p.set_text_color(*INK3)517            p.set_xy(x + 4, cy + 1.5)518            p.cell(gw - 8, 4, f"{frac * 100:.0f} % de {_fr(g['max'])}", align="C")519            p.set_xy(x + 3, y + gh - 7)520            p.set_font("helvetica", "", 7)521            p.set_text_color(*INK2)522            p.multi_cell(gw - 6, 3.3, str(g.get("label", ""))[:60], align="C")523        p.set_y(y + gh + 8)524525    def _serie_stats_row(self, s):526        """Ligne min/max/moyenne/médiane sous un graphique de série."""527        p = self.pdf528        vs = [pt["v"] for pt in (s.get("points") or []) if isinstance(pt.get("v"), (int, float))]529        if len(vs) < 2:530            return531        sv = sorted(vs)532        mean = sum(vs) / len(vs)533        med = sv[len(sv) // 2]534        sd = math.sqrt(sum((v - mean) ** 2 for v in vs) / len(vs))535        p.set_font("helvetica", "", 6.8)536        p.set_text_color(*INK3)537        p.cell(0, 4, f"min {_fr(sv[0])} · max {_fr(sv[-1])} · moyenne {_fr(round(mean, 2))} · médiane {_fr(med)} · écart-type {_fr(round(sd, 2))}")538        p.ln(5.5)539540    def _line_chart(self, s, with_stats=False):541        p = self.pdf542        pts = s.get("points") or []543        if len(pts) < 2:544            return545        if s.get("kind") == "bar":546            self._vbars(s)547            return548        if p.get_y() > 200:549            p.add_page()550        self._chart_title(s.get("title", ""))551        x0, y0, w, h = p.l_margin, p.get_y(), 174, 52552        self._card(x0, y0, w, h, fill=WHITE)553        cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16554        vals = [pt["v"] for pt in pts] + [c["v"] for c in (s.get("compare") or [])]555        vmax = max(vals) or 1556        vmin = min(0, min(vals))557        rng = (vmax - vmin) or 1558        p.set_font("helvetica", "", 6.3)559        p.set_text_color(*INK3)560        p.set_draw_color(200, 200, 195)561        p.set_line_width(0.15)562        for g in range(5):563            gy = cy + ch - ch * g / 4564            p.line(cx, gy, cx + cw, gy)565            p.set_xy(x0 + 1, gy - 1.6)566            p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")567568        def xy(i, n, v):569            return (cx + cw * (i / (n - 1)), cy + ch - ch * ((v - vmin) / rng))570571        # aire sous la courbe (kind=area) : petits trapèzes accent pâle572        if s.get("kind") == "area":573            fill = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * 0.18) for j in range(3))574            p.set_fill_color(*fill)575            p.set_draw_color(*fill)576            n = len(pts)577            for i in range(n - 1):578                x1, y1 = xy(i, n, pts[i]["v"])579                x2, y2 = xy(i + 1, n, pts[i + 1]["v"])580                p.polygon([(x1, y1), (x2, y2), (x2, cy + ch), (x1, cy + ch)], style="DF")581582        def draw(series, color, width, dash=None):583            n = len(series)584            p.set_draw_color(*color)585            p.set_line_width(width)586            if dash:587                p.set_dash_pattern(dash=1.2, gap=1.2)588            last = None589            for i, pt in enumerate(series):590                px, py = xy(i, n, pt["v"])591                if last:592                    p.line(last[0], last[1], px, py)593                last = (px, py)594            p.set_dash_pattern()595596        if s.get("compare"):597            draw(s["compare"], INK3, 0.35, dash=True)598        draw(pts, self.accent, 0.7)599        p.set_text_color(*INK3)600        for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):601            p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)602            p.cell(18, 3, str(pts[idx].get("t", ""))[:10], align="C")603        p.set_y(y0 + h + 4)604        if s.get("compare"):605            p.set_font("helvetica", "", 6.8)606            p.set_text_color(*INK3)607            p.cell(0, 4, "— période courante (accent) · ---- période comparée")608            p.ln(5.5)609        if with_stats:610            self._serie_stats_row(s)611        p.ln(1.5)612613    def _vbars(self, s):614        """Barres verticales : série kind=bar ou distribution (bins)."""615        p = self.pdf616        pts = s.get("points") or [{"t": b.get("label"), "v": b.get("value")} for b in (s.get("bins") or [])]617        pts = [pt for pt in pts if isinstance(pt.get("v"), (int, float))]618        if not pts:619            return620        if p.get_y() > 205:621            p.add_page()622        self._chart_title(s.get("title", ""))623        x0, y0, w, h = p.l_margin, p.get_y(), 174, 48624        self._card(x0, y0, w, h, fill=WHITE)625        cx, cy, cw, ch = x0 + 12, y0 + 5, w - 20, h - 14626        vmax = max(pt["v"] for pt in pts) or 1627        p.set_font("helvetica", "", 6.3)628        p.set_text_color(*INK3)629        p.set_draw_color(200, 200, 195)630        p.set_line_width(0.15)631        for g in range(5):632            gy = cy + ch - ch * g / 4633            p.line(cx, gy, cx + cw, gy)634            p.set_xy(x0 + 1, gy - 1.6)635            p.cell(10, 3, _fr(vmax * g / 4), align="R")636        n = len(pts)637        bw = max(0.8, cw / n - 0.6)638        p.set_fill_color(*self.accent)639        p.set_draw_color(*INK)640        p.set_line_width(0.15)641        for i, pt in enumerate(pts):642            bh = ch * (pt["v"] / vmax)643            p.rect(cx + cw * i / n + 0.3, cy + ch - bh, bw, max(bh, 0.4 if pt["v"] > 0 else 0), style="DF")644        p.set_text_color(*INK3)645        for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):646            p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)647            p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")648        p.set_y(y0 + h + 5)649650    def _multiline(self, ms):651        """Multi-séries (≤4) : accent plein / encre fin / accent pointillé /652        gris pointillé — l'identité passe par le motif, pas la couleur seule."""653        p = self.pdf654        series = [s for s in (ms.get("series") or []) if len(s.get("points") or []) > 1][:4]655        if not series:656            return657        if p.get_y() > 195:658            p.add_page()659        self._chart_title(ms.get("title", ""))660        x0, y0, w, h = p.l_margin, p.get_y(), 174, 52661        self._card(x0, y0, w, h, fill=WHITE)662        cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16663        vals = [pt["v"] for s in series for pt in s["points"]]664        vmax = max(vals) or 1665        vmin = min(0, min(vals))666        rng = (vmax - vmin) or 1667        p.set_font("helvetica", "", 6.3)668        p.set_text_color(*INK3)669        p.set_draw_color(200, 200, 195)670        p.set_line_width(0.15)671        for g in range(5):672            gy = cy + ch - ch * g / 4673            p.line(cx, gy, cx + cw, gy)674            p.set_xy(x0 + 1, gy - 1.6)675            p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")676        styles = [677            (self.accent, 0.7, None),678            (INK, 0.45, None),679            (self.accent, 0.55, True),680            (INK3, 0.5, True),681        ]682        for si, s in enumerate(series):683            col, lw, dash = styles[si]684            p.set_draw_color(*col)685            p.set_line_width(lw)686            if dash:687                p.set_dash_pattern(dash=1.4, gap=1.2)688            n = len(s["points"])689            last = None690            for i, pt in enumerate(s["points"]):691                px = cx + cw * (i / (n - 1))692                py = cy + ch - ch * ((pt["v"] - vmin) / rng)693                if last:694                    p.line(last[0], last[1], px, py)695                last = (px, py)696            p.set_dash_pattern()697        ref = series[0]["points"]698        p.set_text_color(*INK3)699        for frac, idx in ((0, 0), (0.5, len(ref) // 2), (1, -1)):700            p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)701            p.cell(18, 3, str(ref[idx].get("t", ""))[:10], align="C")702        p.set_y(y0 + h + 4)703        p.set_font("helvetica", "", 6.8)704        p.set_text_color(*INK3)705        marks = ["—", "—", "----", "----"]706        leg = " · ".join(f"{marks[i]} {s.get('label', '')}" for i, s in enumerate(series))707        p.cell(0, 4, leg[:120])708        p.ln(6)709710    def _stacked(self, st):711        p = self.pdf712        keys = (st.get("keys") or [])[:6]713        pts = st.get("points") or []714        if not keys or not pts:715            return716        if p.get_y() > 195:717            p.add_page()718        self._chart_title(st.get("title", ""))719        x0, y0, w, h = p.l_margin, p.get_y(), 174, 52720        self._card(x0, y0, w, h, fill=WHITE)721        cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16722        totals = [sum(v or 0 for v in pt.get("values", [])[: len(keys)]) for pt in pts]723        vmax = max(totals) or 1724        p.set_font("helvetica", "", 6.3)725        p.set_text_color(*INK3)726        p.set_draw_color(200, 200, 195)727        p.set_line_width(0.15)728        for g in range(5):729            gy = cy + ch - ch * g / 4730            p.line(cx, gy, cx + cw, gy)731            p.set_xy(x0 + 1, gy - 1.6)732            p.cell(10, 3, _fr(vmax * g / 4), align="R")733        n = len(pts)734        bw = max(0.8, cw / n - 0.6)735        p.set_draw_color(*WHITE)736        p.set_line_width(0.12)737        for i, pt in enumerate(pts):738            yacc = cy + ch739            for j, k in enumerate(keys):740                v = (pt.get("values") or [0] * len(keys))[j] if j < len(pt.get("values", [])) else 0741                if not v:742                    continue743                bh = ch * (v / vmax)744                yacc -= bh745                p.set_fill_color(*self._shade(j))746                p.rect(cx + cw * i / n + 0.3, yacc, bw, max(bh - 0.15, 0.3), style="DF")747        p.set_text_color(*INK3)748        for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):749            p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)750            p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")751        p.set_y(y0 + h + 4)752        # légende753        p.set_font("helvetica", "", 6.8)754        lx = p.l_margin755        for j, k in enumerate(keys):756            p.set_fill_color(*self._shade(j))757            p.set_draw_color(*INK)758            p.set_line_width(0.2)759            p.rect(lx, p.get_y() + 0.6, 3, 3, style="DF")760            p.set_xy(lx + 4, p.get_y())761            p.set_text_color(*INK2)762            txt = str(k)[:22]763            p.cell(p.get_string_width(txt) + 3, 4, txt)764            lx = p.get_x() + 3765            if lx > 165:766                break767        p.ln(7)768769    def _bars(self, title, items, unit=""):770        p = self.pdf771        items = [it for it in (items or []) if isinstance(it.get("value"), (int, float))][:12]772        if not items:773            return774        need = 10 + len(items) * 7775        if p.get_y() + need > 265:776            p.add_page()777        self._chart_title(title)778        p.ln(1)779        vmax = max(it["value"] for it in items) or 1780        for it in items:781            y = p.get_y()782            p.set_font("helvetica", "", 7.6)783            p.set_text_color(*INK)784            p.set_x(p.l_margin)785            p.cell(46, 5, str(it["label"])[:34])786            bw = 86 * (it["value"] / vmax)787            p.set_fill_color(*self.accent)788            p.set_draw_color(*INK)789            p.set_line_width(0.25)790            p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF")791            p.set_xy(p.l_margin + 136, y)792            p.set_font("helvetica", "B", 7.6)793            p.cell(24, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")794            if it.get("delta_pct") is not None:795                up = it["delta_pct"] >= 0796                p.set_font("helvetica", "B", 6.6)797                p.set_text_color(*(GREEN if up else DANGER))798                p.cell(14, 5, f"{'+' if up else ''}{str(round(it['delta_pct'], 1)).replace('.', ',')} %", align="R")799            p.ln(6.4)800        p.ln(3)801802    def _donut(self, b):803        p = self.pdf804        items = [it for it in (b.get("items") or []) if it.get("value")][:8]805        total = sum(it["value"] for it in items)806        if not items or not total:807            return808        if p.get_y() > 210:809            p.add_page()810        self._chart_title(b.get("title", ""))811        p.ln(1)812        cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20813        start = -90.0814        for i, it in enumerate(items):815            frac = it["value"] / total816            col = self._shade(i)817            steps = max(2, int(72 * frac))818            p.set_fill_color(*col)819            p.set_draw_color(*col)820            for st in range(steps):821                a0 = math.radians(start + 360 * frac * st / steps)822                a1 = math.radians(start + 360 * frac * (st + 1) / steps)823                p.polygon(824                    [(cx, cy),825                     (cx + r * math.cos(a0), cy + r * math.sin(a0)),826                     (cx + r * math.cos(a1), cy + r * math.sin(a1))],827                    style="DF",828                )829            start += 360 * frac830        p.set_fill_color(*WHITE)831        p.set_draw_color(*INK)832        p.set_line_width(0.4)833        p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")834        p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")835        ly = cy - 22836        for i, it in enumerate(items):837            col = self._shade(i)838            p.set_fill_color(*col)839            p.set_draw_color(*INK)840            p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")841            p.set_xy(p.l_margin + 66, ly)842            p.set_font("helvetica", "", 7.6)843            p.set_text_color(*INK)844            pct = 100 * it["value"] / total845            p.cell(0, 5.6, f"{str(it['label'])[:40]} — {_fr(it['value'])} ({pct:.1f} %)".replace(".", ","))846            ly += 5.6847        p.set_y(max(cy + r, ly) + 6)848849    def _hourly(self):850        hh = self.d.get("hourly") or {}851        cells = hh.get("cells") or []852        if not cells:853            return854        p = self.pdf855        if p.get_y() > 190:856            p.add_page()857        self._chart_title(hh.get("title", "Activité par jour et heure"))858        x0, y0 = p.l_margin, p.get_y()859        cw, chh, lx, ly = 6.4, 6.4, 12, 5860        vmax = max((c.get("value") or 0) for c in cells) or 1861        grid = {(c.get("dow"), c.get("hour")): c.get("value") or 0 for c in cells}862        dows = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"]863        p.set_font("helvetica", "", 5.8)864        p.set_text_color(*INK3)865        for h in (0, 6, 12, 18, 23):866            p.set_xy(x0 + lx + h * cw, y0)867            p.cell(cw, 3, f"{h}h", align="C")868        for d in range(7):869            p.set_xy(x0, y0 + ly + d * chh + 1.5)870            p.cell(lx - 1, 3, dows[d], align="R")871            for h in range(24):872                v = grid.get((d, h), 0)873                f = 0.1 + 0.9 * (v / vmax) if v else 0.0874                col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) if v else (235, 233, 228)875                p.set_fill_color(*col)876                p.set_draw_color(215, 213, 207)877                p.set_line_width(0.1)878                p.rect(x0 + lx + h * cw, y0 + ly + d * chh, cw - 0.5, chh - 0.5, style="DF")879        p.set_y(y0 + ly + 7 * chh + 5)880881    def _calheat(self, hm):882        """v3 — calendrier de chaleur 26 semaines (équivalent PDF du883        CalendarHeatmap du kit front) : colonnes = semaines, lignes = jours."""884        from datetime import date as _date, timedelta as _td885        cells = hm.get("cells") or []886        vals = {c.get("date"): c.get("value") or 0 for c in cells if c.get("date")}887        if not vals:888            return889        p = self.pdf890        if p.get_y() > 215:891            p.add_page()892        self._chart_title(hm.get("title", "Calendrier d'activité"))893        try:894            end = _date.fromisoformat(max(vals))895        except ValueError:896            return897        weeks = 26898        start = end - _td(days=weeks * 7 - 1)899        start -= _td(days=start.weekday())  # lundi900        vmax = max(vals.values()) or 1901        x0, y0 = p.l_margin, p.get_y()902        cw, lx, ly = 6.3, 10, 4903        dows = ["Lun", "", "Mer", "", "Ven", "", "Dim"]904        p.set_font("helvetica", "", 5.8)905        p.set_text_color(*INK3)906        for d in range(7):907            if dows[d]:908                p.set_xy(x0, y0 + ly + d * cw + 1.2)909                p.cell(lx - 1, 3, dows[d], align="R")910        for w in range(weeks):911            monday = start + _td(days=7 * w)912            if monday.day <= 7:  # étiquette de mois à la 1re semaine du mois913                p.set_xy(x0 + lx + w * cw, y0)914                p.cell(cw * 4, 3, monday.strftime("%m"))915            for d in range(7):916                day = monday + _td(days=d)917                v = vals.get(day.isoformat(), 0)918                f = 0.15 + 0.85 * (v / vmax) if v else 0.0919                col = (tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f)920                             for j in range(3)) if v else (235, 233, 228))921                p.set_fill_color(*col)922                p.set_draw_color(215, 213, 207)923                p.set_line_width(0.1)924                p.rect(x0 + lx + w * cw, y0 + ly + d * cw, cw - 0.5, cw - 0.5,925                       style="DF")926        p.set_y(y0 + ly + 7 * cw + 5)927928    # ---------- v3 : conversions bloc → tableau ----------929    @staticmethod930    def _serie_as_table(s):931        unit = s.get("unit") or "Valeur"932        cols = ["Date", unit.capitalize()]933        cmp_ = s.get("compare") or []934        if cmp_:935            cols.append("Période comparée")936        rows = []937        for i, pt in enumerate(s.get("points") or []):938            row = [str(pt.get("t", "")), pt.get("v", "")]939            if cmp_:940                row.append(cmp_[i]["v"] if i < len(cmp_) else "")941            rows.append(row)942        return {"id": s.get("id"), "title": s.get("title", ""),943                "columns": cols, "rows": rows}944945    @staticmethod946    def _multi_as_table(ms):947        labels = [s.get("label", "") for s in (ms.get("series") or [])][:4]948        by_t: dict[str, dict] = {}949        for s in (ms.get("series") or [])[:4]:950            for pt in s.get("points") or []:951                by_t.setdefault(str(pt.get("t", "")), {})[s.get("label", "")] = pt.get("v")952        rows = [[t] + [by_t[t].get(lbl, "") for lbl in labels]953                for t in sorted(by_t)]954        return {"id": ms.get("id"), "title": ms.get("title", ""),955                "columns": ["Date"] + labels, "rows": rows}956957    @staticmethod958    def _stacked_as_table(st):959        keys = (st.get("keys") or [])[:6]960        rows = []961        for pt in st.get("points") or []:962            vs = [(pt.get("values") or [])[j] if j < len(pt.get("values") or []) else 0963                  for j in range(len(keys))]964            rows.append([str(pt.get("t", ""))] + vs + [sum(v or 0 for v in vs)])965        return {"id": st.get("id"), "title": st.get("title", ""),966                "columns": ["Date"] + list(keys) + ["Total"], "rows": rows}967968    @staticmethod969    def _items_as_table(id_, title, items, label_col="Libellé"):970        items = items or []971        with_delta = any(it.get("delta_pct") is not None for it in items)972        cols = [label_col, "Valeur"] + (["delta %"] if with_delta else [])973        rows = []974        for it in items:975            row = [str(it.get("label", "")), it.get("value", "")]976            if with_delta:977                d = it.get("delta_pct")978                row.append("" if d is None else f"{'+' if d >= 0 else ''}{d} %")979            rows.append(row)980        return {"id": id_, "title": title, "columns": cols, "rows": rows}981982    def _kpis_as_table(self):983        rows = []984        for k in self.d.get("kpis") or []:985            v = k.get("value")986            val = (_fr(v) if isinstance(v, (int, float)) else str(v)) + \987                  ((" " + k["unit"]) if k.get("unit") else "")988            d = k.get("delta_pct")989            rows.append([str(k.get("label", "")), val,990                         "" if d is None else f"{'+' if d >= 0 else ''}{d} %"])991        return {"id": "kpis", "title": "Indicateurs clés",992                "columns": ["Indicateur", "Valeur", "delta %"], "rows": rows}993994    def _gauges_as_table(self):995        rows = [[str(g.get("label", "")),996                 f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}",997                 _fr(g["max"]), f"{100.0 * g['value'] / g['max']:.0f} %"]998                for g in self.d.get("gauges") or []999                if isinstance(g.get("value"), (int, float)) and g.get("max")]1000        return {"id": "gauges", "title": "Taux & couvertures",1001                "columns": ["Mesure", "Valeur", "Max", "Part"], "rows": rows}10021003    def _records_as_table(self):1004        rows = [[str(r.get("label", "")), str(r.get("value", "")),1005                 str(r.get("date", "") or "")]1006                for r in self.d.get("records") or []]1007        return {"id": "records", "title": "Records & faits marquants",1008                "columns": ["Fait marquant", "Valeur", "Date"], "rows": rows}10091010    @staticmethod1011    def _heatmap_as_table(hm, title):1012        cells = sorted((hm.get("cells") or []),1013                       key=lambda c: -(c.get("value") or 0))[:40]1014        return {"id": "heatmap", "title": title + " — jours les plus chargés",1015                "columns": ["Date", "Valeur"],1016                "rows": [[c.get("date", ""), c.get("value") or 0] for c in cells]}10171018    @staticmethod1019    def _hourly_as_table(hr, title):1020        days = ["Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi",1021                "Dimanche"]1022        cells = sorted((hr.get("cells") or []),1023                       key=lambda c: -(c.get("value") or 0))[:40]1024        return {"id": "hourly", "title": title + " — créneaux les plus actifs",1025                "columns": ["Jour", "Heure", "Valeur"],1026                "rows": [[days[c["dow"]] if 0 <= c.get("dow", -1) <= 6 else "?",1027                          f"{c.get('hour', '?')} h", c.get("value") or 0]1028                         for c in cells]}10291030    # ---------- v3 : rendu d'un bloc du rapport personnalisé ----------1031    def _find(self, coll: str, id_: str):1032        for it in self.d.get(coll) or []:1033            if str(it.get("id")) == id_:1034                return it1035        return None10361037    def _toc_mark(self, title: str):1038        """Blocs graphiques du mode personnalisé : entrée de sommaire sans1039        _section_title (le graphique porte déjà son titre)."""1040        if self.pdf.get_y() > 235:1041            self.pdf.add_page()1042        self.toc.append((title, self.pdf.page_no()))10431044    def _render_block(self, key: str, render: str):1045        section, _, id_ = key.partition(":")1046        if section == "kpis":1047            self._table(self._kpis_as_table()) if render == "table" else self._kpis()1048        elif section == "gauges":1049            self._table(self._gauges_as_table()) if render == "table" else self._gauges()1050        elif section == "records":1051            self._table(self._records_as_table()) if render == "table" else self._records()1052        elif section == "series":1053            s = self._find("series", id_)1054            if not s:1055                return1056            if render == "table":1057                self._table(self._serie_as_table(s), max_rows=400)1058            else:1059                s2 = dict(s)1060                if render in ("line", "area", "bar"):1061                    s2["kind"] = render1062                self._toc_mark(s2.get("title", ""))1063                if s2.get("kind") == "bar":1064                    self._vbars(s2)1065                else:1066                    self._line_chart(s2, with_stats=True)1067        elif section == "multiseries":1068            ms = self._find("multiseries", id_)1069            if not ms:1070                return1071            if render == "table":1072                self._table(self._multi_as_table(ms), max_rows=400)1073            else:1074                self._toc_mark(ms.get("title", ""))1075                self._multiline(ms)1076        elif section == "stacked":1077            st = self._find("stacked", id_)1078            if not st:1079                return1080            if render == "table":1081                self._table(self._stacked_as_table(st), max_rows=400)1082            else:1083                self._toc_mark(st.get("title", ""))1084                self._stacked(st)1085        elif section == "breakdowns":1086            b = self._find("breakdowns", id_)1087            if not b:1088                return1089            if render == "table":1090                self._table(self._items_as_table(id_, b.get("title", ""),1091                                                 b.get("items")), max_rows=400)1092            else:1093                self._toc_mark(b.get("title", ""))1094                if render == "donut":1095                    self._donut(b)1096                else:1097                    self._bars(b.get("title", ""), b.get("items"))1098        elif section == "distributions":1099            d = self._find("distributions", id_)1100            if not d:1101                return1102            if render == "table":1103                bins = [{"label": bn.get("label"), "value": bn.get("value")}1104                        for bn in d.get("bins") or []]1105                self._table(self._items_as_table(id_, d.get("title", ""), bins,1106                                                 label_col="Tranche"))1107            else:1108                self._toc_mark(d.get("title", ""))1109                self._vbars(d)1110        elif section == "geo":1111            geo = self.d.get("geo") or {}1112            if not geo.get("items"):1113                return1114            title = geo.get("title", "Répartition géographique")1115            if render == "table":1116                self._table(self._items_as_table("geo", title, geo["items"],1117                                                 label_col="Zone"), max_rows=400)1118            else:1119                self._toc_mark(title)1120                self._bars(title, geo["items"])1121        elif section == "heatmap":1122            hm = self.d.get("heatmap") or {}1123            if not hm.get("cells"):1124                return1125            title = hm.get("title", "Calendrier d'activité")1126            if render == "table":1127                self._table(self._heatmap_as_table(hm, title))1128            else:1129                self._toc_mark(title)1130                self._calheat(hm)1131        elif section == "hourly":1132            hr = self.d.get("hourly") or {}1133            if not hr.get("cells"):1134                return1135            title = hr.get("title", "Activité par jour et heure")1136            if render == "table":1137                self._table(self._hourly_as_table(hr, title))1138            else:1139                self._toc_mark(title)1140                self._hourly()1141        elif section == "tables":1142            t = self._find("tables", id_)1143            if t:1144                self._table(t, max_rows=400)11451146    def _table(self, t, max_rows=200):1147        p = self.pdf1148        cols = t.get("columns") or []1149        rows = t.get("rows") or []1150        if not cols or not rows:1151            return1152        self._section_title(t.get("title", "Tableau"))1153        w = 174 / len(cols)1154        def head():1155            p.set_font("helvetica", "B", 7.6)1156            p.set_fill_color(*INK)1157            p.set_text_color(*WHITE)1158            for c in cols:1159                p.cell(w, 6, " " + str(c)[:30], fill=True)1160            p.ln(6)1161        head()1162        p.set_text_color(*INK)1163        for i, row in enumerate(rows[:max_rows]):1164            if p.get_y() > 262:1165                p.add_page()1166                head()1167                p.set_text_color(*INK)1168            p.set_font("helvetica", "", 7.4)1169            p.set_fill_color(*(SURFACE2 if i % 2 else WHITE))1170            for cell in row:1171                txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)1172                p.cell(w, 5.4, " " + txt[:34], fill=True)1173            p.ln(5.4)1174        if len(rows) > max_rows:1175            p.set_font("helvetica", "", 7)1176            p.set_text_color(*INK3)1177            p.cell(0, 5, f"… {len(rows) - max_rows} lignes supplémentaires non imprimées")1178        p.ln(6)11791180    def _records(self):1181        recs = self.d.get("records") or []1182        if not recs:1183            return1184        self._section_title("Records & faits marquants")1185        p = self.pdf1186        for r in recs[:14]:1187            if p.get_y() > 258:1188                p.add_page()1189            y = p.get_y()1190            self._card(p.l_margin, y, 174, 11, fill=SURFACE2)1191            p.set_xy(p.l_margin + 4, y + 2)1192            p.set_font("helvetica", "", 8.6)1193            p.set_text_color(*INK2)1194            p.cell(96, 7, str(r.get("label", ""))[:70])1195            p.set_font("helvetica", "B", 9)1196            p.set_text_color(*INK)1197            p.cell(52, 7, str(r.get("value", ""))[:36], align="R")1198            p.set_font("helvetica", "", 7.6)1199            p.set_text_color(*INK3)1200            p.cell(20, 7, str(r.get("date", "") or ""), align="R")1201            p.set_y(y + 13.5)1202        p.ln(4)12031204    def _final_page(self):1205        p = self.pdf1206        p.add_page()1207        self._kicker("Lou-Ka · contact")1208        p.set_font("helvetica", "B", 15)1209        p.set_text_color(*INK)1210        p.cell(0, 8, "Coordonnées de Lou-Ka")1211        p.ln(12)1212        for email, role in EMAILS:1213            p.set_font("helvetica", "B", 10.5)1214            p.set_text_color(*INK)1215            p.cell(0, 6, email)1216            p.ln(5.5)1217            p.set_font("helvetica", "", 8.6)1218            p.set_text_color(*INK3)1219            p.cell(0, 5, role)1220            p.ln(8)1221        p.ln(2)1222        p.set_font("helvetica", "B", 10)1223        p.set_text_color(*GREEN)1224        p.cell(0, 6, "lou-ka.com")1225        p.ln(10)1226        p.set_draw_color(*self.accent)1227        p.set_line_width(0.8)1228        p.line(p.l_margin, p.get_y(), p.l_margin + 30, p.get_y())1229        p.ln(4)1230        p.set_font("helvetica", "", 8.6)1231        p.set_text_color(*INK2)1232        p.multi_cell(160, 4.6, DISCLAIMER)1233        p.ln(4)1234        p.set_font("helvetica", "", 7.6)1235        p.set_text_color(*INK3)1236        p.multi_cell(1237            160, 4.2,1238            "Mentions : rapport généré automatiquement à partir des données réelles de la "1239            "plateforme au moment indiqué en couverture. Conditions d'utilisation, politique "1240            "de confidentialité et protection des renseignements personnels (Loi 25) : "1241            "lou-ka.com/conditions · /confidentialite.",1242        )12431244    # ---------- groupes de sections ----------1245    def _all_series(self, with_stats=True):1246        for s in self.d.get("series") or []:1247            self._line_chart(s, with_stats=with_stats)1248        for ms in self.d.get("multiseries") or []:1249            self._multiline(ms)1250        for st in self.d.get("stacked") or []:1251            self._stacked(st)12521253    def _all_breakdowns(self):1254        for b in self.d.get("breakdowns") or []:1255            if b.get("kind") == "donut":1256                self._donut(b)1257            else:1258                self._bars(b.get("title", ""), b.get("items"))1259        for dist in self.d.get("distributions") or []:1260            self._vbars(dist)1261        geo = self.d.get("geo")1262        if geo:1263            self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))1264        self._hourly()12651266    def build(self) -> bytes:1267        p = self.pdf1268        p.alias_nb_pages()1269        self._cover()1270        with_toc = self.mode in ("complet", "donnees", CUSTOM_MODE)1271        toc_page_no = None1272        if self.mode == "synthese":1273            p.add_page()1274            self._kpis()1275            self._gauges()1276            self._records()1277            self._final_page()1278        elif self.mode == "tendances":1279            p.add_page()1280            self._kpis()1281            self._section_title("Évolution & tendances")1282            self._all_series(with_stats=True)1283            self._records()1284            self._final_page()1285        elif self.mode == "repartitions":1286            p.add_page()1287            self._section_title("Répartitions, distributions & géographie")1288            self._all_breakdowns()1289            self._final_page()1290        elif self.mode == "donnees":1291            p.add_page()1292            toc_page_no = p.page_no()1293            for t in self.d.get("tables") or []:1294                self._table(t, max_rows=400)1295            self._final_page()1296        elif self.mode == CUSTOM_MODE:1297            p.add_page()1298            toc_page_no = p.page_no()1299            p.add_page()1300            known = {b["key"]: b for b in catalog(self.d)}1301            for blk in self.spec.get("blocks") or []:1302                key = str(blk.get("key", ""))1303                b = known.get(key)1304                if not b:1305                    continue1306                render = str(blk.get("render") or "")1307                if render not in b["renders"]:1308                    render = b["default_render"]1309                self._render_block(key, render)1310            self._final_page()1311        else:  # complet1312            p.add_page()1313            toc_page_no = p.page_no()1314            p.add_page()1315            self._kpis()1316            self._gauges()1317            if (self.d.get("series") or self.d.get("multiseries") or self.d.get("stacked")):1318                self._section_title("Évolution & tendances")1319                self._all_series(with_stats=True)1320            if (self.d.get("breakdowns") or self.d.get("distributions") or self.d.get("geo") or self.d.get("hourly")):1321                self._section_title("Répartitions, distributions & géographie")1322                self._all_breakdowns()1323            for t in self.d.get("tables") or []:1324                self._table(t)1325            self._records()1326            self._final_page()1327        # sommaire écrit sur la page réservée1328        if toc_page_no is not None:1329            last_page = p.page1330            p.page = toc_page_no1331            p.set_y(22)1332            p.set_font("helvetica", "B", 15)1333            p.set_text_color(*INK)1334            p.cell(0, 8, "Sommaire")1335            p.ln(12)1336            p.set_font("helvetica", "", 9.5)1337            for title, page_no in self.toc:1338                p.set_text_color(*INK)1339                p.cell(140, 6.5, title[:80])1340                p.set_text_color(*INK3)1341                p.cell(0, 6.5, str(page_no), align="R")1342                p.ln(6.5)1343            p.page = last_page1344        return bytes(p.output())134513461347def filename(platform_id: str, period: str, mode: str = "complet") -> str:1348    today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")1349    suffix = "" if mode in ("", "complet") else f"_{mode}"1350    return f"{platform_id}_stats_{period}{suffix}_{today}.pdf"1351
Files main
Menu

Theme