SPB Git

Repository Public

rapportpdf.py 49.5 KB 1,251 lines python

1# -----------------------------------------------------------------------------2# Auto-Ka v2 — véhicules d'occasion à vendre au Québec3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4# rapportpdf.py : rapport PDF du marché (fpdf2), à l'identité neutre d'Auto-Ka.5# Consomme le JSON de /api/stats/dashboard. 5 modes fixes :6#   complet      — toutes les sections7#   synthese     — couverture + indicateurs + records (2-3 pages)8#   tendances    — indicateurs + séries temporelles9#   repartitions — répartitions, distributions, géographie, activité horaire10#   donnees      — tous les tableaux en version longue (400 lignes max)11# et un mode « personnalise » : le rapport suit une composition12# {"title": str, "blocks": [{"key": "series:ajouts", "render": "bar"}, …]} ;13# catalog(dash) expose les blocs disponibles.14# Graphiques vectoriels seulement (primitives fpdf).15# -----------------------------------------------------------------------------16from __future__ import annotations1718import math19from datetime import datetime20from zoneinfo import ZoneInfo2122from fpdf import FPDF2324INK = (20, 24, 20)25INK2 = (77, 85, 81)26INK3 = (139, 146, 140)27PAPER = (245, 243, 238)28SURFACE2 = (250, 249, 245)29GREEN = (28, 92, 65)30DANGER = (179, 66, 58)31WHITE = (255, 255, 255)3233REPORT_MODES = {34    "complet": "Rapport complet",35    "synthese": "Synthèse exécutive",36    "tendances": "Tendances & évolution",37    "repartitions": "Répartitions & géographie",38    "donnees": "Données détaillées",39}40# v3 — mode composé par l'utilisateur (jamais dans le menu des modes fixes)41CUSTOM_MODE = "personnalise"42CUSTOM_LABEL = "Rapport personnalisé"4344# v3 — rendus proposés par type de bloc (le 1er est le rendu par défaut ;45# « table » est toujours offert : toute donnée a un équivalent tableau)46RENDER_LABELS = {47    "line": "Courbe", "area": "Aire", "bar": "Barres verticales",48    "bars": "Barres horizontales", "donut": "Anneau",49    "lines": "Multi-courbes", "stacked": "Barres empilées",50    "histogram": "Histogramme", "heatmap": "Heatmap",51    "cards": "Cartes", "gauges": "Jauges", "table": "Tableau",52}53SECTION_LABELS = {54    "kpis": "Indicateurs", "gauges": "Taux & couvertures",55    "series": "Évolution", "multiseries": "Comparaisons",56    "stacked": "Compositions", "breakdowns": "Répartitions",57    "distributions": "Distributions", "geo": "Géographie",58    "heatmap": "Calendrier", "hourly": "Activité horaire",59    "tables": "Tableaux", "records": "Records",60}616263def catalog(dash: dict) -> list[dict]:64    """v3 — blocs composables d'un dashboard : ce que le constructeur de65    rapports personnalisés peut inclure, avec les rendus compatibles.66    key = section[:id] ; l'ordre renvoyé = ordre naturel du dashboard."""67    out: list[dict] = []6869    def add(key, title, renders, default=None, count=None):70        b = {"key": key, "section": key.split(":")[0], "title": title,71             "renders": renders, "default_render": default or renders[0]}72        if count is not None:73            b["count"] = count74        out.append(b)7576    if dash.get("kpis"):77        add("kpis", "Indicateurs clés (KPI)", ["cards", "table"],78            count=len(dash["kpis"]))79    gs = [g for g in (dash.get("gauges") or [])80          if isinstance(g.get("value"), (int, float)) and g.get("max")]81    if gs:82        add("gauges", "Taux & couvertures (jauges)", ["gauges", "table"],83            count=len(gs))84    for s in dash.get("series") or []:85        if len(s.get("points") or []) < 2:86            continue87        kind = s.get("kind") or "line"88        default = kind if kind in ("line", "area", "bar") else "line"89        add(f"series:{s.get('id')}", s.get("title", ""),90            ["line", "area", "bar", "table"], default,91            len(s.get("points") or []))92    for ms in dash.get("multiseries") or []:93        if not (ms.get("series") or []):94            continue95        add(f"multiseries:{ms.get('id')}", ms.get("title", ""),96            ["lines", "table"], count=len(ms["series"]))97    for st in dash.get("stacked") or []:98        if not (st.get("points") or []):99            continue100        add(f"stacked:{st.get('id')}", st.get("title", ""),101            ["stacked", "table"], count=len(st.get("keys") or []))102    for b in dash.get("breakdowns") or []:103        if not (b.get("items") or []):104            continue105        default = "donut" if b.get("kind") == "donut" else "bars"106        add(f"breakdowns:{b.get('id')}", b.get("title", ""),107            ["donut", "bars", "table"], default, len(b["items"]))108    for d in dash.get("distributions") or []:109        if not (d.get("bins") or []):110            continue111        add(f"distributions:{d.get('id')}", d.get("title", ""),112            ["histogram", "table"], count=len(d["bins"]))113    geo = dash.get("geo") or {}114    if geo.get("items"):115        add("geo", geo.get("title", "Répartition géographique"),116            ["bars", "table"], count=len(geo["items"]))117    hm = dash.get("heatmap") or {}118    if hm.get("cells"):119        add("heatmap", hm.get("title", "Calendrier d'activité"),120            ["heatmap", "table"])121    hr = dash.get("hourly") or {}122    if hr.get("cells"):123        add("hourly", hr.get("title", "Activité par jour et heure"),124            ["heatmap", "table"])125    for t in dash.get("tables") or []:126        if not (t.get("rows") or []):127            continue128        add(f"tables:{t.get('id')}", t.get("title", ""), ["table"],129            count=len(t["rows"]))130    if dash.get("records"):131        add("records", "Records & faits marquants", ["cards", "table"],132            count=len(dash["records"]))133    return out134135EMAILS = [136    ("contact@spboucher.ai", "Questions, corrections, retrait d'une source, données"),137]138DISCLAIMER = (139    "Auto-Ka rassemble des annonces publiées ailleurs : il ne vend rien et "140    "n'est partie à aucune transaction. Les données sont lues à la source ; "141    "chaque annonce renvoie à sa page d'origine."142)143144145def _hex(c: str) -> tuple[int, int, int]:146    c = c.lstrip("#")147    return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4))  # type: ignore148149150def _fr(n) -> str:151    if isinstance(n, float) and not n.is_integer():152        return f"{n:,.2f}".replace(",", " ").replace(".", ",")153    return f"{int(n):,}".replace(",", " ")154155156_SUBST = {157    "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",158    "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',159    "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",160    "×": "x", "·": ".", "σ": "sigma", "Δ": "delta",161}162163164def _latin1(s: str) -> str:165    for k, v in _SUBST.items():166        s = s.replace(k, v)167    return s.encode("latin-1", "replace").decode("latin-1")168169170class _PDF(FPDF):171    """FPDF avec en-tête et pied sur chaque page (sauf la couverture).172    Les polices core sont latin-1 : normalize_text sanitise en amont."""173174    def normalize_text(self, text):175        return super().normalize_text(_latin1(text))176177    def __init__(self, brand: str, accent: tuple, period_label: str):178        super().__init__(orientation="P", unit="mm", format="A4")179        self.brand = brand180        self.accent = accent181        self.period_label = period_label182        self.cover_mode = False183        self.set_margins(18, 20, 18)184        self.set_auto_page_break(True, margin=22)185186    def header(self):187        if self.cover_mode or self.page_no() == 1:188            return189        self.set_font("helvetica", "B", 8.5)190        self.set_text_color(*INK)191        self.set_xy(18, 9)192        self.cell(0, 5, f"{self.brand}")193        self.set_font("helvetica", "", 8)194        self.set_text_color(*INK3)195        self.set_xy(18, 9)196        self.cell(0, 5, "Rapport statistique", align="R")197        self.set_draw_color(*INK)198        self.set_line_width(0.5)199        self.line(18, 15.5, 192, 15.5)200        self.set_y(20)201202    def footer(self):203        # page 1 = couverture (le flag cover_mode est déjà retombé quand204        # add_page() clôt la page 1 → tester aussi le numéro de page)205        if self.cover_mode or self.page_no() == 1:206            return207        self.set_y(-15)208        self.set_draw_color(*INK3)209        self.set_line_width(0.2)210        self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5)211        self.set_font("helvetica", "", 7.5)212        self.set_text_color(*INK3)213        year = datetime.now(ZoneInfo("America/Toronto")).year214        self.cell(130, 5, f"© {self.brand} — {year} — {self.period_label}")215        self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R")216217218class Rapport:219    def __init__(self, site: dict, dashboard: dict, mode: str = "complet",220                 spec: dict | None = None):221        self.site = site222        self.d = dashboard223        self.mode = mode if (mode in REPORT_MODES or mode == CUSTOM_MODE) else "complet"224        self.spec = spec or {}225        self.accent = _hex(site.get("accent", "#d9f26b"))226        period = dashboard.get("period", {}) or {}227        self.period_label = period.get("label") or "toute la période"228        self.pdf = _PDF(site.get("wordmark", ""), self.accent, self.period_label)229        self.toc: list[tuple[str, int]] = []230231    @property232    def mode_label(self) -> str:233        if self.mode == CUSTOM_MODE:234            t = str(self.spec.get("title") or "").strip()235            return f"{CUSTOM_LABEL} — {t}" if t else CUSTOM_LABEL236        return REPORT_MODES[self.mode]237238    # ---------- primitives ----------239    def _card(self, x, y, w, h, fill=WHITE):240        p = self.pdf241        p.set_draw_color(*INK)242        p.set_line_width(0.45)243        p.set_fill_color(*fill)244        p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)245246    def _shade(self, i, n=8):247        shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]248        f = shades[i % len(shades)]249        return tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))250251    def _kicker(self, text):252        p = self.pdf253        p.set_font("helvetica", "B", 8)254        p.set_text_color(*GREEN)255        p.set_draw_color(*GREEN)256        p.set_line_width(0.6)257        y = p.get_y() + 2258        p.line(p.l_margin, y, p.l_margin + 7, y)259        p.set_xy(p.l_margin + 9, y - 2.5)260        p.cell(0, 5, text.upper())261        p.ln(8)262263    def _section_title(self, title):264        if self.pdf.get_y() > 240:265            self.pdf.add_page()266        self._kicker(self.site.get("wordmark", ""))267        self.pdf.set_font("helvetica", "B", 15)268        self.pdf.set_text_color(*INK)269        self.pdf.set_x(self.pdf.l_margin)270        self.pdf.cell(0, 8, title)271        self.toc.append((title, self.pdf.page_no()))272        self.pdf.ln(11)273274    def _chart_title(self, title):275        p = self.pdf276        p.set_font("helvetica", "B", 10)277        p.set_text_color(*INK)278        p.set_x(p.l_margin)279        p.cell(0, 6, title)280        p.ln(7)281282    # ---------- pages ----------283    def _cover(self):284        p = self.pdf285        p.cover_mode = True286        p.set_auto_page_break(False)287        p.add_page()288        p.set_fill_color(*PAPER)289        p.rect(0, 0, 210, 297, style="F")290        p.set_draw_color(*INK)291        p.set_line_width(1.0)292        p.rect(10, 10, 190, 277)293        p.set_font("helvetica", "B", 10)294        p.set_text_color(*GREEN)295        p.set_xy(24, 34)296        p.cell(0, 6, "RAPPORT STATISTIQUE")297        wm = self.site.get("wordmark", "")298        left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)299        p.set_xy(24, 70)300        p.set_font("helvetica", "B", 40)301        p.set_text_color(*INK)302        p.cell(p.get_string_width(left) + 2, 20, left)303        if boxed:304            bw = p.get_string_width(boxed) + 12305            x = p.get_x() + 2306            p.set_fill_color(*INK)307            p.rect(x, 68, bw, 22, style="F", round_corners=True, corner_radius=3)308            p.set_text_color(*self.accent)309            p.set_xy(x + 6, 70)310            p.cell(bw - 12, 18, boxed)311        p.set_xy(24, 100)312        p.set_font("helvetica", "", 13)313        p.set_text_color(*INK2)314        p.multi_cell(150, 7, f"{self.mode_label} — {wm}")315        now = datetime.now(ZoneInfo("America/Toronto"))316        per = self.d.get("period", {}) or {}317        p.set_xy(24, 125)318        p.set_font("helvetica", "", 10.5)319        rows = [320            ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),321            ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),322            ("Plateforme", "https://" + self.site.get("domain", "")),323            ("Type de rapport", self.mode_label),324        ]325        y = 128326        for k, v in rows:327            p.set_xy(24, y)328            p.set_text_color(*INK3)329            p.cell(40, 6, k)330            p.set_text_color(*INK)331            p.set_font("helvetica", "B", 10.5)332            p.cell(0, 6, str(v))333            p.set_font("helvetica", "", 10.5)334            y += 8335        p.set_fill_color(*INK)336        p.rect(10, 262, 190, 25, style="F")337        p.set_xy(24, 270)338        p.set_font("helvetica", "B", 12)339        p.set_text_color(*WHITE)340        p.cell(60, 8, self.site.get("wordmark", ""))341        p.set_font("helvetica", "B", 10)342        p.set_xy(24, 270)343        p.cell(162, 8, self.site.get("domain", ""), align="R")344        p.set_auto_page_break(True, margin=22)345        p.cover_mode = False346347    def _kpis(self):348        kpis = self.d.get("kpis") or []349        if not kpis:350            return351        self._section_title("Synthèse des indicateurs")352        p = self.pdf353        cols, gw, gh, gap = 3, 56, 26, 3354        x0, y = p.l_margin, p.get_y()355        for i, k in enumerate(kpis[:12]):356            x = x0 + (i % cols) * (gw + gap)357            if i and i % cols == 0:358                y += gh + gap359            if y > 250:360                p.add_page(); y = p.get_y()361            self._card(x, y, gw, gh)362            p.set_xy(x + 4, y + 4)363            p.set_font("helvetica", "B", 14)364            p.set_text_color(*INK)365            val = k.get("value")366            p.cell(gw - 8, 7, (_fr(val) if isinstance(val, (int, float)) else str(val)) + (" " + k["unit"] if k.get("unit") else ""))367            p.set_xy(x + 4, y + 12)368            p.set_font("helvetica", "", 7.6)369            p.set_text_color(*INK2)370            p.multi_cell(gw - 8, 3.6, str(k.get("label", ""))[:70])371            if k.get("delta_pct") is not None:372                up = (k.get("direction") or ("up" if k["delta_pct"] >= 0 else "down")) == "up"373                p.set_xy(x + 4, y + gh - 6.5)374                p.set_font("helvetica", "B", 8)375                p.set_text_color(*(GREEN if up else DANGER))376                arrow = "+" if k["delta_pct"] >= 0 else ""377                dv = round(float(k["delta_pct"]), 1)378                dv = int(dv) if float(dv).is_integer() else dv379                p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(dv).replace('.', ',')} % vs période préc.")380        p.set_y(y + gh + 8)381382    def _gauges(self):383        gs = self.d.get("gauges") or []384        gs = [g for g in gs if isinstance(g.get("value"), (int, float)) and g.get("max")]385        if not gs:386            return387        self._section_title("Taux & couvertures")388        p = self.pdf389        cols, gw, gh, gap = 3, 56, 34, 3390        x0, y = p.l_margin, p.get_y()391        for i, g in enumerate(gs[:9]):392            x = x0 + (i % cols) * (gw + gap)393            if i and i % cols == 0:394                y += gh + gap395            if y > 240:396                p.add_page(); y = p.get_y()397            self._card(x, y, gw, gh)398            frac = max(0.0, min(1.0, g["value"] / g["max"]))399            cx, cy, r = x + gw / 2, y + 20, 14400            # arc de fond + arc de valeur (demi-cercle en petits segments)401            for pass_col, pass_frac, lw in (((225, 223, 217), 1.0, 2.6), (self.accent, frac, 2.6)):402                p.set_draw_color(*pass_col)403                p.set_line_width(lw)404                steps = max(2, int(60 * pass_frac))405                last = None406                for st in range(steps + 1):407                    a = math.pi + math.pi * pass_frac * st / steps408                    pt = (cx + r * math.cos(a), cy + r * math.sin(a))409                    if last:410                        p.line(last[0], last[1], pt[0], pt[1])411                    last = pt412            p.set_font("helvetica", "B", 11)413            p.set_text_color(*INK)414            p.set_xy(x + 4, cy - 5)415            p.cell(gw - 8, 6, f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}", align="C")416            p.set_font("helvetica", "", 6.6)417            p.set_text_color(*INK3)418            p.set_xy(x + 4, cy + 1.5)419            p.cell(gw - 8, 4, f"{frac * 100:.0f} % de {_fr(g['max'])}", align="C")420            p.set_xy(x + 3, y + gh - 7)421            p.set_font("helvetica", "", 7)422            p.set_text_color(*INK2)423            p.multi_cell(gw - 6, 3.3, str(g.get("label", ""))[:60], align="C")424        p.set_y(y + gh + 8)425426    def _serie_stats_row(self, s):427        """Ligne min/max/moyenne/médiane sous un graphique de série."""428        p = self.pdf429        vs = [pt["v"] for pt in (s.get("points") or []) if isinstance(pt.get("v"), (int, float))]430        if len(vs) < 2:431            return432        sv = sorted(vs)433        mean = sum(vs) / len(vs)434        med = sv[len(sv) // 2]435        sd = math.sqrt(sum((v - mean) ** 2 for v in vs) / len(vs))436        p.set_font("helvetica", "", 6.8)437        p.set_text_color(*INK3)438        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))}")439        p.ln(5.5)440441    def _line_chart(self, s, with_stats=False):442        p = self.pdf443        pts = s.get("points") or []444        if len(pts) < 2:445            return446        if s.get("kind") == "bar":447            self._vbars(s)448            return449        if p.get_y() > 200:450            p.add_page()451        self._chart_title(s.get("title", ""))452        x0, y0, w, h = p.l_margin, p.get_y(), 174, 52453        self._card(x0, y0, w, h, fill=WHITE)454        cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16455        vals = [pt["v"] for pt in pts] + [c["v"] for c in (s.get("compare") or [])]456        vmax = max(vals) or 1457        vmin = min(0, min(vals))458        rng = (vmax - vmin) or 1459        p.set_font("helvetica", "", 6.3)460        p.set_text_color(*INK3)461        p.set_draw_color(200, 200, 195)462        p.set_line_width(0.15)463        for g in range(5):464            gy = cy + ch - ch * g / 4465            p.line(cx, gy, cx + cw, gy)466            p.set_xy(x0 + 1, gy - 1.6)467            p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")468469        def xy(i, n, v):470            return (cx + cw * (i / (n - 1)), cy + ch - ch * ((v - vmin) / rng))471472        # aire sous la courbe (kind=area) : petits trapèzes accent pâle473        if s.get("kind") == "area":474            fill = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * 0.18) for j in range(3))475            p.set_fill_color(*fill)476            p.set_draw_color(*fill)477            n = len(pts)478            for i in range(n - 1):479                x1, y1 = xy(i, n, pts[i]["v"])480                x2, y2 = xy(i + 1, n, pts[i + 1]["v"])481                p.polygon([(x1, y1), (x2, y2), (x2, cy + ch), (x1, cy + ch)], style="DF")482483        def draw(series, color, width, dash=None):484            n = len(series)485            p.set_draw_color(*color)486            p.set_line_width(width)487            if dash:488                p.set_dash_pattern(dash=1.2, gap=1.2)489            last = None490            for i, pt in enumerate(series):491                px, py = xy(i, n, pt["v"])492                if last:493                    p.line(last[0], last[1], px, py)494                last = (px, py)495            p.set_dash_pattern()496497        if s.get("compare"):498            draw(s["compare"], INK3, 0.35, dash=True)499        draw(pts, self.accent, 0.7)500        p.set_text_color(*INK3)501        for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):502            p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)503            p.cell(18, 3, str(pts[idx].get("t", ""))[:10], align="C")504        p.set_y(y0 + h + 4)505        if s.get("compare"):506            p.set_font("helvetica", "", 6.8)507            p.set_text_color(*INK3)508            p.cell(0, 4, "— période courante (accent) · ---- période comparée")509            p.ln(5.5)510        if with_stats:511            self._serie_stats_row(s)512        p.ln(1.5)513514    def _vbars(self, s):515        """Barres verticales : série kind=bar ou distribution (bins)."""516        p = self.pdf517        pts = s.get("points") or [{"t": b.get("label"), "v": b.get("value")} for b in (s.get("bins") or [])]518        pts = [pt for pt in pts if isinstance(pt.get("v"), (int, float))]519        if not pts:520            return521        if p.get_y() > 205:522            p.add_page()523        self._chart_title(s.get("title", ""))524        x0, y0, w, h = p.l_margin, p.get_y(), 174, 48525        self._card(x0, y0, w, h, fill=WHITE)526        cx, cy, cw, ch = x0 + 12, y0 + 5, w - 20, h - 14527        vmax = max(pt["v"] for pt in pts) or 1528        p.set_font("helvetica", "", 6.3)529        p.set_text_color(*INK3)530        p.set_draw_color(200, 200, 195)531        p.set_line_width(0.15)532        for g in range(5):533            gy = cy + ch - ch * g / 4534            p.line(cx, gy, cx + cw, gy)535            p.set_xy(x0 + 1, gy - 1.6)536            p.cell(10, 3, _fr(vmax * g / 4), align="R")537        n = len(pts)538        bw = max(0.8, cw / n - 0.6)539        p.set_fill_color(*self.accent)540        p.set_draw_color(*INK)541        p.set_line_width(0.15)542        for i, pt in enumerate(pts):543            bh = ch * (pt["v"] / vmax)544            p.rect(cx + cw * i / n + 0.3, cy + ch - bh, bw, max(bh, 0.4 if pt["v"] > 0 else 0), style="DF")545        p.set_text_color(*INK3)546        for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):547            p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)548            p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")549        p.set_y(y0 + h + 5)550551    def _multiline(self, ms):552        """Multi-séries (≤4) : accent plein / encre fin / accent pointillé /553        gris pointillé — l'identité passe par le motif, pas la couleur seule."""554        p = self.pdf555        series = [s for s in (ms.get("series") or []) if len(s.get("points") or []) > 1][:4]556        if not series:557            return558        if p.get_y() > 195:559            p.add_page()560        self._chart_title(ms.get("title", ""))561        x0, y0, w, h = p.l_margin, p.get_y(), 174, 52562        self._card(x0, y0, w, h, fill=WHITE)563        cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16564        vals = [pt["v"] for s in series for pt in s["points"]]565        vmax = max(vals) or 1566        vmin = min(0, min(vals))567        rng = (vmax - vmin) or 1568        p.set_font("helvetica", "", 6.3)569        p.set_text_color(*INK3)570        p.set_draw_color(200, 200, 195)571        p.set_line_width(0.15)572        for g in range(5):573            gy = cy + ch - ch * g / 4574            p.line(cx, gy, cx + cw, gy)575            p.set_xy(x0 + 1, gy - 1.6)576            p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")577        styles = [578            (self.accent, 0.7, None),579            (INK, 0.45, None),580            (self.accent, 0.55, True),581            (INK3, 0.5, True),582        ]583        for si, s in enumerate(series):584            col, lw, dash = styles[si]585            p.set_draw_color(*col)586            p.set_line_width(lw)587            if dash:588                p.set_dash_pattern(dash=1.4, gap=1.2)589            n = len(s["points"])590            last = None591            for i, pt in enumerate(s["points"]):592                px = cx + cw * (i / (n - 1))593                py = cy + ch - ch * ((pt["v"] - vmin) / rng)594                if last:595                    p.line(last[0], last[1], px, py)596                last = (px, py)597            p.set_dash_pattern()598        ref = series[0]["points"]599        p.set_text_color(*INK3)600        for frac, idx in ((0, 0), (0.5, len(ref) // 2), (1, -1)):601            p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)602            p.cell(18, 3, str(ref[idx].get("t", ""))[:10], align="C")603        p.set_y(y0 + h + 4)604        p.set_font("helvetica", "", 6.8)605        p.set_text_color(*INK3)606        marks = ["—", "—", "----", "----"]607        leg = " · ".join(f"{marks[i]} {s.get('label', '')}" for i, s in enumerate(series))608        p.cell(0, 4, leg[:120])609        p.ln(6)610611    def _stacked(self, st):612        p = self.pdf613        keys = (st.get("keys") or [])[:6]614        pts = st.get("points") or []615        if not keys or not pts:616            return617        if p.get_y() > 195:618            p.add_page()619        self._chart_title(st.get("title", ""))620        x0, y0, w, h = p.l_margin, p.get_y(), 174, 52621        self._card(x0, y0, w, h, fill=WHITE)622        cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16623        totals = [sum(v or 0 for v in pt.get("values", [])[: len(keys)]) for pt in pts]624        vmax = max(totals) or 1625        p.set_font("helvetica", "", 6.3)626        p.set_text_color(*INK3)627        p.set_draw_color(200, 200, 195)628        p.set_line_width(0.15)629        for g in range(5):630            gy = cy + ch - ch * g / 4631            p.line(cx, gy, cx + cw, gy)632            p.set_xy(x0 + 1, gy - 1.6)633            p.cell(10, 3, _fr(vmax * g / 4), align="R")634        n = len(pts)635        bw = max(0.8, cw / n - 0.6)636        p.set_draw_color(*WHITE)637        p.set_line_width(0.12)638        for i, pt in enumerate(pts):639            yacc = cy + ch640            for j, k in enumerate(keys):641                v = (pt.get("values") or [0] * len(keys))[j] if j < len(pt.get("values", [])) else 0642                if not v:643                    continue644                bh = ch * (v / vmax)645                yacc -= bh646                p.set_fill_color(*self._shade(j))647                p.rect(cx + cw * i / n + 0.3, yacc, bw, max(bh - 0.15, 0.3), style="DF")648        p.set_text_color(*INK3)649        for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):650            p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)651            p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")652        p.set_y(y0 + h + 4)653        # légende654        p.set_font("helvetica", "", 6.8)655        lx = p.l_margin656        for j, k in enumerate(keys):657            p.set_fill_color(*self._shade(j))658            p.set_draw_color(*INK)659            p.set_line_width(0.2)660            p.rect(lx, p.get_y() + 0.6, 3, 3, style="DF")661            p.set_xy(lx + 4, p.get_y())662            p.set_text_color(*INK2)663            txt = str(k)[:22]664            p.cell(p.get_string_width(txt) + 3, 4, txt)665            lx = p.get_x() + 3666            if lx > 165:667                break668        p.ln(7)669670    def _bars(self, title, items, unit=""):671        p = self.pdf672        items = [it for it in (items or []) if isinstance(it.get("value"), (int, float))][:12]673        if not items:674            return675        need = 10 + len(items) * 7676        if p.get_y() + need > 265:677            p.add_page()678        self._chart_title(title)679        p.ln(1)680        vmax = max(it["value"] for it in items) or 1681        for it in items:682            y = p.get_y()683            p.set_font("helvetica", "", 7.6)684            p.set_text_color(*INK)685            p.set_x(p.l_margin)686            p.cell(46, 5, str(it["label"])[:34])687            bw = 86 * (it["value"] / vmax)688            p.set_fill_color(*self.accent)689            p.set_draw_color(*INK)690            p.set_line_width(0.25)691            p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF")692            p.set_xy(p.l_margin + 136, y)693            p.set_font("helvetica", "B", 7.6)694            p.cell(24, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")695            if it.get("delta_pct") is not None:696                up = it["delta_pct"] >= 0697                p.set_font("helvetica", "B", 6.6)698                p.set_text_color(*(GREEN if up else DANGER))699                p.cell(14, 5, f"{'+' if up else ''}{str(round(it['delta_pct'], 1)).replace('.', ',')} %", align="R")700            p.ln(6.4)701        p.ln(3)702703    def _donut(self, b):704        p = self.pdf705        items = [it for it in (b.get("items") or []) if it.get("value")][:8]706        total = sum(it["value"] for it in items)707        if not items or not total:708            return709        if p.get_y() > 210:710            p.add_page()711        self._chart_title(b.get("title", ""))712        p.ln(1)713        cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20714        start = -90.0715        for i, it in enumerate(items):716            frac = it["value"] / total717            col = self._shade(i)718            steps = max(2, int(72 * frac))719            p.set_fill_color(*col)720            p.set_draw_color(*col)721            for st in range(steps):722                a0 = math.radians(start + 360 * frac * st / steps)723                a1 = math.radians(start + 360 * frac * (st + 1) / steps)724                p.polygon(725                    [(cx, cy),726                     (cx + r * math.cos(a0), cy + r * math.sin(a0)),727                     (cx + r * math.cos(a1), cy + r * math.sin(a1))],728                    style="DF",729                )730            start += 360 * frac731        p.set_fill_color(*WHITE)732        p.set_draw_color(*INK)733        p.set_line_width(0.4)734        p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")735        p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")736        ly = cy - 22737        for i, it in enumerate(items):738            col = self._shade(i)739            p.set_fill_color(*col)740            p.set_draw_color(*INK)741            p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")742            p.set_xy(p.l_margin + 66, ly)743            p.set_font("helvetica", "", 7.6)744            p.set_text_color(*INK)745            pct = 100 * it["value"] / total746            p.cell(0, 5.6, f"{str(it['label'])[:40]} — {_fr(it['value'])} ({pct:.1f} %)".replace(".", ","))747            ly += 5.6748        p.set_y(max(cy + r, ly) + 6)749750    def _hourly(self):751        hh = self.d.get("hourly") or {}752        cells = hh.get("cells") or []753        if not cells:754            return755        p = self.pdf756        if p.get_y() > 190:757            p.add_page()758        self._chart_title(hh.get("title", "Activité par jour et heure"))759        x0, y0 = p.l_margin, p.get_y()760        cw, chh, lx, ly = 6.4, 6.4, 12, 5761        vmax = max((c.get("value") or 0) for c in cells) or 1762        grid = {(c.get("dow"), c.get("hour")): c.get("value") or 0 for c in cells}763        dows = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"]764        p.set_font("helvetica", "", 5.8)765        p.set_text_color(*INK3)766        for h in (0, 6, 12, 18, 23):767            p.set_xy(x0 + lx + h * cw, y0)768            p.cell(cw, 3, f"{h}h", align="C")769        for d in range(7):770            p.set_xy(x0, y0 + ly + d * chh + 1.5)771            p.cell(lx - 1, 3, dows[d], align="R")772            for h in range(24):773                v = grid.get((d, h), 0)774                f = 0.1 + 0.9 * (v / vmax) if v else 0.0775                col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) if v else (235, 233, 228)776                p.set_fill_color(*col)777                p.set_draw_color(215, 213, 207)778                p.set_line_width(0.1)779                p.rect(x0 + lx + h * cw, y0 + ly + d * chh, cw - 0.5, chh - 0.5, style="DF")780        p.set_y(y0 + ly + 7 * chh + 5)781782    def _calheat(self, hm):783        """v3 — calendrier de chaleur 26 semaines (équivalent PDF du784        CalendarHeatmap du kit front) : colonnes = semaines, lignes = jours."""785        from datetime import date as _date, timedelta as _td786        cells = hm.get("cells") or []787        vals = {c.get("date"): c.get("value") or 0 for c in cells if c.get("date")}788        if not vals:789            return790        p = self.pdf791        if p.get_y() > 215:792            p.add_page()793        self._chart_title(hm.get("title", "Calendrier d'activité"))794        try:795            end = _date.fromisoformat(max(vals))796        except ValueError:797            return798        weeks = 26799        start = end - _td(days=weeks * 7 - 1)800        start -= _td(days=start.weekday())  # lundi801        vmax = max(vals.values()) or 1802        x0, y0 = p.l_margin, p.get_y()803        cw, lx, ly = 6.3, 10, 4804        dows = ["Lun", "", "Mer", "", "Ven", "", "Dim"]805        p.set_font("helvetica", "", 5.8)806        p.set_text_color(*INK3)807        for d in range(7):808            if dows[d]:809                p.set_xy(x0, y0 + ly + d * cw + 1.2)810                p.cell(lx - 1, 3, dows[d], align="R")811        for w in range(weeks):812            monday = start + _td(days=7 * w)813            if monday.day <= 7:  # étiquette de mois à la 1re semaine du mois814                p.set_xy(x0 + lx + w * cw, y0)815                p.cell(cw * 4, 3, monday.strftime("%m"))816            for d in range(7):817                day = monday + _td(days=d)818                v = vals.get(day.isoformat(), 0)819                f = 0.15 + 0.85 * (v / vmax) if v else 0.0820                col = (tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f)821                             for j in range(3)) if v else (235, 233, 228))822                p.set_fill_color(*col)823                p.set_draw_color(215, 213, 207)824                p.set_line_width(0.1)825                p.rect(x0 + lx + w * cw, y0 + ly + d * cw, cw - 0.5, cw - 0.5,826                       style="DF")827        p.set_y(y0 + ly + 7 * cw + 5)828829    # ---------- v3 : conversions bloc → tableau ----------830    @staticmethod831    def _serie_as_table(s):832        unit = s.get("unit") or "Valeur"833        cols = ["Date", unit.capitalize()]834        cmp_ = s.get("compare") or []835        if cmp_:836            cols.append("Période comparée")837        rows = []838        for i, pt in enumerate(s.get("points") or []):839            row = [str(pt.get("t", "")), pt.get("v", "")]840            if cmp_:841                row.append(cmp_[i]["v"] if i < len(cmp_) else "")842            rows.append(row)843        return {"id": s.get("id"), "title": s.get("title", ""),844                "columns": cols, "rows": rows}845846    @staticmethod847    def _multi_as_table(ms):848        labels = [s.get("label", "") for s in (ms.get("series") or [])][:4]849        by_t: dict[str, dict] = {}850        for s in (ms.get("series") or [])[:4]:851            for pt in s.get("points") or []:852                by_t.setdefault(str(pt.get("t", "")), {})[s.get("label", "")] = pt.get("v")853        rows = [[t] + [by_t[t].get(lbl, "") for lbl in labels]854                for t in sorted(by_t)]855        return {"id": ms.get("id"), "title": ms.get("title", ""),856                "columns": ["Date"] + labels, "rows": rows}857858    @staticmethod859    def _stacked_as_table(st):860        keys = (st.get("keys") or [])[:6]861        rows = []862        for pt in st.get("points") or []:863            vs = [(pt.get("values") or [])[j] if j < len(pt.get("values") or []) else 0864                  for j in range(len(keys))]865            rows.append([str(pt.get("t", ""))] + vs + [sum(v or 0 for v in vs)])866        return {"id": st.get("id"), "title": st.get("title", ""),867                "columns": ["Date"] + list(keys) + ["Total"], "rows": rows}868869    @staticmethod870    def _items_as_table(id_, title, items, label_col="Libellé"):871        items = items or []872        with_delta = any(it.get("delta_pct") is not None for it in items)873        cols = [label_col, "Valeur"] + (["delta %"] if with_delta else [])874        rows = []875        for it in items:876            row = [str(it.get("label", "")), it.get("value", "")]877            if with_delta:878                d = it.get("delta_pct")879                row.append("" if d is None else f"{'+' if d >= 0 else ''}{d} %")880            rows.append(row)881        return {"id": id_, "title": title, "columns": cols, "rows": rows}882883    def _kpis_as_table(self):884        rows = []885        for k in self.d.get("kpis") or []:886            v = k.get("value")887            val = (_fr(v) if isinstance(v, (int, float)) else str(v)) + \888                  ((" " + k["unit"]) if k.get("unit") else "")889            d = k.get("delta_pct")890            rows.append([str(k.get("label", "")), val,891                         "" if d is None else f"{'+' if d >= 0 else ''}{d} %"])892        return {"id": "kpis", "title": "Indicateurs clés",893                "columns": ["Indicateur", "Valeur", "delta %"], "rows": rows}894895    def _gauges_as_table(self):896        rows = [[str(g.get("label", "")),897                 f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}",898                 _fr(g["max"]), f"{100.0 * g['value'] / g['max']:.0f} %"]899                for g in self.d.get("gauges") or []900                if isinstance(g.get("value"), (int, float)) and g.get("max")]901        return {"id": "gauges", "title": "Taux & couvertures",902                "columns": ["Mesure", "Valeur", "Max", "Part"], "rows": rows}903904    def _records_as_table(self):905        rows = [[str(r.get("label", "")), str(r.get("value", "")),906                 str(r.get("date", "") or "")]907                for r in self.d.get("records") or []]908        return {"id": "records", "title": "Records & faits marquants",909                "columns": ["Fait marquant", "Valeur", "Date"], "rows": rows}910911    @staticmethod912    def _heatmap_as_table(hm, title):913        cells = sorted((hm.get("cells") or []),914                       key=lambda c: -(c.get("value") or 0))[:40]915        return {"id": "heatmap", "title": title + " — jours les plus chargés",916                "columns": ["Date", "Valeur"],917                "rows": [[c.get("date", ""), c.get("value") or 0] for c in cells]}918919    @staticmethod920    def _hourly_as_table(hr, title):921        days = ["Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi",922                "Dimanche"]923        cells = sorted((hr.get("cells") or []),924                       key=lambda c: -(c.get("value") or 0))[:40]925        return {"id": "hourly", "title": title + " — créneaux les plus actifs",926                "columns": ["Jour", "Heure", "Valeur"],927                "rows": [[days[c["dow"]] if 0 <= c.get("dow", -1) <= 6 else "?",928                          f"{c.get('hour', '?')} h", c.get("value") or 0]929                         for c in cells]}930931    # ---------- v3 : rendu d'un bloc du rapport personnalisé ----------932    def _find(self, coll: str, id_: str):933        for it in self.d.get(coll) or []:934            if str(it.get("id")) == id_:935                return it936        return None937938    def _toc_mark(self, title: str):939        """Blocs graphiques du mode personnalisé : entrée de sommaire sans940        _section_title (le graphique porte déjà son titre)."""941        if self.pdf.get_y() > 235:942            self.pdf.add_page()943        self.toc.append((title, self.pdf.page_no()))944945    def _render_block(self, key: str, render: str):946        section, _, id_ = key.partition(":")947        if section == "kpis":948            self._table(self._kpis_as_table()) if render == "table" else self._kpis()949        elif section == "gauges":950            self._table(self._gauges_as_table()) if render == "table" else self._gauges()951        elif section == "records":952            self._table(self._records_as_table()) if render == "table" else self._records()953        elif section == "series":954            s = self._find("series", id_)955            if not s:956                return957            if render == "table":958                self._table(self._serie_as_table(s), max_rows=400)959            else:960                s2 = dict(s)961                if render in ("line", "area", "bar"):962                    s2["kind"] = render963                self._toc_mark(s2.get("title", ""))964                if s2.get("kind") == "bar":965                    self._vbars(s2)966                else:967                    self._line_chart(s2, with_stats=True)968        elif section == "multiseries":969            ms = self._find("multiseries", id_)970            if not ms:971                return972            if render == "table":973                self._table(self._multi_as_table(ms), max_rows=400)974            else:975                self._toc_mark(ms.get("title", ""))976                self._multiline(ms)977        elif section == "stacked":978            st = self._find("stacked", id_)979            if not st:980                return981            if render == "table":982                self._table(self._stacked_as_table(st), max_rows=400)983            else:984                self._toc_mark(st.get("title", ""))985                self._stacked(st)986        elif section == "breakdowns":987            b = self._find("breakdowns", id_)988            if not b:989                return990            if render == "table":991                self._table(self._items_as_table(id_, b.get("title", ""),992                                                 b.get("items")), max_rows=400)993            else:994                self._toc_mark(b.get("title", ""))995                if render == "donut":996                    self._donut(b)997                else:998                    self._bars(b.get("title", ""), b.get("items"))999        elif section == "distributions":1000            d = self._find("distributions", id_)1001            if not d:1002                return1003            if render == "table":1004                bins = [{"label": bn.get("label"), "value": bn.get("value")}1005                        for bn in d.get("bins") or []]1006                self._table(self._items_as_table(id_, d.get("title", ""), bins,1007                                                 label_col="Tranche"))1008            else:1009                self._toc_mark(d.get("title", ""))1010                self._vbars(d)1011        elif section == "geo":1012            geo = self.d.get("geo") or {}1013            if not geo.get("items"):1014                return1015            title = geo.get("title", "Répartition géographique")1016            if render == "table":1017                self._table(self._items_as_table("geo", title, geo["items"],1018                                                 label_col="Zone"), max_rows=400)1019            else:1020                self._toc_mark(title)1021                self._bars(title, geo["items"])1022        elif section == "heatmap":1023            hm = self.d.get("heatmap") or {}1024            if not hm.get("cells"):1025                return1026            title = hm.get("title", "Calendrier d'activité")1027            if render == "table":1028                self._table(self._heatmap_as_table(hm, title))1029            else:1030                self._toc_mark(title)1031                self._calheat(hm)1032        elif section == "hourly":1033            hr = self.d.get("hourly") or {}1034            if not hr.get("cells"):1035                return1036            title = hr.get("title", "Activité par jour et heure")1037            if render == "table":1038                self._table(self._hourly_as_table(hr, title))1039            else:1040                self._toc_mark(title)1041                self._hourly()1042        elif section == "tables":1043            t = self._find("tables", id_)1044            if t:1045                self._table(t, max_rows=400)10461047    def _table(self, t, max_rows=200):1048        p = self.pdf1049        cols = t.get("columns") or []1050        rows = t.get("rows") or []1051        if not cols or not rows:1052            return1053        self._section_title(t.get("title", "Tableau"))1054        w = 174 / len(cols)1055        def head():1056            p.set_font("helvetica", "B", 7.6)1057            p.set_fill_color(*INK)1058            p.set_text_color(*WHITE)1059            for c in cols:1060                p.cell(w, 6, " " + str(c)[:30], fill=True)1061            p.ln(6)1062        head()1063        p.set_text_color(*INK)1064        for i, row in enumerate(rows[:max_rows]):1065            if p.get_y() > 262:1066                p.add_page()1067                head()1068                p.set_text_color(*INK)1069            p.set_font("helvetica", "", 7.4)1070            p.set_fill_color(*(SURFACE2 if i % 2 else WHITE))1071            for cell in row:1072                txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)1073                p.cell(w, 5.4, " " + txt[:34], fill=True)1074            p.ln(5.4)1075        if len(rows) > max_rows:1076            p.set_font("helvetica", "", 7)1077            p.set_text_color(*INK3)1078            p.cell(0, 5, f"… {len(rows) - max_rows} lignes supplémentaires non imprimées")1079        p.ln(6)10801081    def _records(self):1082        recs = self.d.get("records") or []1083        if not recs:1084            return1085        self._section_title("Records & faits marquants")1086        p = self.pdf1087        for r in recs[:14]:1088            if p.get_y() > 258:1089                p.add_page()1090            y = p.get_y()1091            self._card(p.l_margin, y, 174, 11, fill=SURFACE2)1092            p.set_xy(p.l_margin + 4, y + 2)1093            p.set_font("helvetica", "", 8.6)1094            p.set_text_color(*INK2)1095            p.cell(96, 7, str(r.get("label", ""))[:70])1096            p.set_font("helvetica", "B", 9)1097            p.set_text_color(*INK)1098            p.cell(52, 7, str(r.get("value", ""))[:36], align="R")1099            p.set_font("helvetica", "", 7.6)1100            p.set_text_color(*INK3)1101            p.cell(20, 7, str(r.get("date", "") or ""), align="R")1102            p.set_y(y + 13.5)1103        p.ln(4)11041105    def _final_page(self):1106        p = self.pdf1107        p.add_page()1108        self._kicker("Contact")1109        p.set_font("helvetica", "B", 15)1110        p.set_text_color(*INK)1111        p.cell(0, 8, "Nous joindre")1112        p.ln(12)1113        for email, role in EMAILS:1114            p.set_font("helvetica", "B", 10.5)1115            p.set_text_color(*INK)1116            p.cell(0, 6, email)1117            p.ln(5.5)1118            p.set_font("helvetica", "", 8.6)1119            p.set_text_color(*INK3)1120            p.cell(0, 5, role)1121            p.ln(8)1122        p.ln(2)1123        p.set_font("helvetica", "B", 10)1124        p.set_text_color(*GREEN)1125        p.cell(0, 6, self.site.get("domain", ""))1126        p.ln(10)1127        p.set_draw_color(*self.accent)1128        p.set_line_width(0.8)1129        p.line(p.l_margin, p.get_y(), p.l_margin + 30, p.get_y())1130        p.ln(4)1131        p.set_font("helvetica", "", 8.6)1132        p.set_text_color(*INK2)1133        p.multi_cell(160, 4.6, DISCLAIMER)1134        p.ln(4)1135        p.set_font("helvetica", "", 7.6)1136        p.set_text_color(*INK3)1137        p.multi_cell(1138            160, 4.2,1139            "Mentions : rapport généré automatiquement à partir des données réelles de la "1140            "plateforme au moment indiqué en couverture. Seules les annonces publiques "1141            "(actives, plausibles, sans doublon) entrent dans les calculs.",1142        )11431144    # ---------- groupes de sections ----------1145    def _all_series(self, with_stats=True):1146        for s in self.d.get("series") or []:1147            self._line_chart(s, with_stats=with_stats)1148        for ms in self.d.get("multiseries") or []:1149            self._multiline(ms)1150        for st in self.d.get("stacked") or []:1151            self._stacked(st)11521153    def _all_breakdowns(self):1154        for b in self.d.get("breakdowns") or []:1155            if b.get("kind") == "donut":1156                self._donut(b)1157            else:1158                self._bars(b.get("title", ""), b.get("items"))1159        for dist in self.d.get("distributions") or []:1160            self._vbars(dist)1161        geo = self.d.get("geo")1162        if geo:1163            self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))1164        self._hourly()11651166    def build(self) -> bytes:1167        p = self.pdf1168        p.alias_nb_pages()1169        self._cover()1170        with_toc = self.mode in ("complet", "donnees", CUSTOM_MODE)1171        toc_page_no = None1172        if self.mode == "synthese":1173            p.add_page()1174            self._kpis()1175            self._gauges()1176            self._records()1177            self._final_page()1178        elif self.mode == "tendances":1179            p.add_page()1180            self._kpis()1181            self._section_title("Évolution & tendances")1182            self._all_series(with_stats=True)1183            self._records()1184            self._final_page()1185        elif self.mode == "repartitions":1186            p.add_page()1187            self._section_title("Répartitions, distributions & géographie")1188            self._all_breakdowns()1189            self._final_page()1190        elif self.mode == "donnees":1191            p.add_page()1192            toc_page_no = p.page_no()1193            for t in self.d.get("tables") or []:1194                self._table(t, max_rows=400)1195            self._final_page()1196        elif self.mode == CUSTOM_MODE:1197            p.add_page()1198            toc_page_no = p.page_no()1199            p.add_page()1200            known = {b["key"]: b for b in catalog(self.d)}1201            for blk in self.spec.get("blocks") or []:1202                key = str(blk.get("key", ""))1203                b = known.get(key)1204                if not b:1205                    continue1206                render = str(blk.get("render") or "")1207                if render not in b["renders"]:1208                    render = b["default_render"]1209                self._render_block(key, render)1210            self._final_page()1211        else:  # complet1212            p.add_page()1213            toc_page_no = p.page_no()1214            p.add_page()1215            self._kpis()1216            self._gauges()1217            if (self.d.get("series") or self.d.get("multiseries") or self.d.get("stacked")):1218                self._section_title("Évolution & tendances")1219                self._all_series(with_stats=True)1220            if (self.d.get("breakdowns") or self.d.get("distributions") or self.d.get("geo") or self.d.get("hourly")):1221                self._section_title("Répartitions, distributions & géographie")1222                self._all_breakdowns()1223            for t in self.d.get("tables") or []:1224                self._table(t)1225            self._records()1226            self._final_page()1227        # sommaire écrit sur la page réservée1228        if toc_page_no is not None:1229            last_page = p.page1230            p.page = toc_page_no1231            p.set_y(22)1232            p.set_font("helvetica", "B", 15)1233            p.set_text_color(*INK)1234            p.cell(0, 8, "Sommaire")1235            p.ln(12)1236            p.set_font("helvetica", "", 9.5)1237            for title, page_no in self.toc:1238                p.set_text_color(*INK)1239                p.cell(140, 6.5, title[:80])1240                p.set_text_color(*INK3)1241                p.cell(0, 6.5, str(page_no), align="R")1242                p.ln(6.5)1243            p.page = last_page1244        return bytes(p.output())124512461247def filename(platform_id: str, period: str, mode: str = "complet") -> str:1248    today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")1249    suffix = "" if mode in ("", "complet") else f"_{mode}"1250    return f"{platform_id}_marche_{period}{suffix}_{today}.pdf"1251
Files main
Menu

Theme