Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Immo·Ka9# File : immoka/reportpdf.py10# Module : immoka11# Repository : https://git.spboucher.ai/immo-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# reportpdf.py — moteur des rapports statistiques PDF d'Immo-Ka (fpdf2). v389# Consomme le JSON du contrat /api/stats/dashboard (voir SPEC.md) et produit90# les rapports Immo-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 reportpdf import MarketReport, REPORT_MODES, catalog, filename106# pdf_bytes = MarketReport(site={"wordmark":"Immo-Ka","accent":"#D12C37",107# "domain":"www.immo-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 FPDF119120# palette Immo-Ka v2 : charbon, chaux, ardoise ; l'accent (rouge porte #D12C37)121# vient du paramètre `site`122INK = (27, 29, 34)123INK2 = (74, 78, 87)124INK3 = (138, 142, 150)125PAPER = (246, 243, 236)126SURFACE2 = (251, 249, 245)127SLATE = (43, 74, 99)128LOGO_PATH = __import__("pathlib").Path(__file__).resolve().parent / "assets" / "logo-immo-ka.png"129GREEN = (28, 92, 65)130DANGER = (179, 66, 58)131WHITE = (255, 255, 255)132133REPORT_MODES = {134 "complet": "Rapport complet",135 "synthese": "Synthèse exécutive",136 "tendances": "Tendances & évolution",137 "repartitions": "Répartitions & géographie",138 "donnees": "Données détaillées",139}140# v3 — mode composé par l'utilisateur (jamais dans le menu des modes fixes)141CUSTOM_MODE = "personnalise"142CUSTOM_LABEL = "Rapport personnalisé"143144# v3 — rendus proposés par type de bloc (le 1er est le rendu par défaut ;145# « table » est toujours offert : toute donnée a un équivalent tableau)146RENDER_LABELS = {147 "line": "Courbe", "area": "Aire", "bar": "Barres verticales",148 "bars": "Barres horizontales", "donut": "Anneau",149 "lines": "Multi-courbes", "stacked": "Barres empilées",150 "histogram": "Histogramme", "heatmap": "Heatmap",151 "cards": "Cartes", "gauges": "Jauges", "table": "Tableau",152}153SECTION_LABELS = {154 "kpis": "Indicateurs", "gauges": "Taux & couvertures",155 "series": "Évolution", "multiseries": "Comparaisons",156 "stacked": "Compositions", "breakdowns": "Répartitions",157 "distributions": "Distributions", "geo": "Géographie",158 "heatmap": "Calendrier", "hourly": "Activité horaire",159 "tables": "Tableaux", "records": "Records",160}161162163def catalog(dash: dict) -> list[dict]:164 """v3 — blocs composables d'un dashboard : ce que le constructeur de165 rapports personnalisés peut inclure, avec les rendus compatibles.166 key = section[:id] ; l'ordre renvoyé = ordre naturel du dashboard."""167 out: list[dict] = []168169 def add(key, title, renders, default=None, count=None):170 b = {"key": key, "section": key.split(":")[0], "title": title,171 "renders": renders, "default_render": default or renders[0]}172 if count is not None:173 b["count"] = count174 out.append(b)175176 if dash.get("kpis"):177 add("kpis", "Indicateurs clés (KPI)", ["cards", "table"],178 count=len(dash["kpis"]))179 gs = [g for g in (dash.get("gauges") or [])180 if isinstance(g.get("value"), (int, float)) and g.get("max")]181 if gs:182 add("gauges", "Taux & couvertures (jauges)", ["gauges", "table"],183 count=len(gs))184 for s in dash.get("series") or []:185 if len(s.get("points") or []) < 2:186 continue187 kind = s.get("kind") or "line"188 default = kind if kind in ("line", "area", "bar") else "line"189 add(f"series:{s.get('id')}", s.get("title", ""),190 ["line", "area", "bar", "table"], default,191 len(s.get("points") or []))192 for ms in dash.get("multiseries") or []:193 if not (ms.get("series") or []):194 continue195 add(f"multiseries:{ms.get('id')}", ms.get("title", ""),196 ["lines", "table"], count=len(ms["series"]))197 for st in dash.get("stacked") or []:198 if not (st.get("points") or []):199 continue200 add(f"stacked:{st.get('id')}", st.get("title", ""),201 ["stacked", "table"], count=len(st.get("keys") or []))202 for b in dash.get("breakdowns") or []:203 if not (b.get("items") or []):204 continue205 default = "donut" if b.get("kind") == "donut" else "bars"206 add(f"breakdowns:{b.get('id')}", b.get("title", ""),207 ["donut", "bars", "table"], default, len(b["items"]))208 for d in dash.get("distributions") or []:209 if not (d.get("bins") or []):210 continue211 add(f"distributions:{d.get('id')}", d.get("title", ""),212 ["histogram", "table"], count=len(d["bins"]))213 geo = dash.get("geo") or {}214 if geo.get("items"):215 add("geo", geo.get("title", "Répartition géographique"),216 ["bars", "table"], count=len(geo["items"]))217 hm = dash.get("heatmap") or {}218 if hm.get("cells"):219 add("heatmap", hm.get("title", "Calendrier d'activité"),220 ["heatmap", "table"])221 hr = dash.get("hourly") or {}222 if hr.get("cells"):223 add("hourly", hr.get("title", "Activité par jour et heure"),224 ["heatmap", "table"])225 for t in dash.get("tables") or []:226 if not (t.get("rows") or []):227 continue228 add(f"tables:{t.get('id')}", t.get("title", ""), ["table"],229 count=len(t["rows"]))230 if dash.get("records"):231 add("records", "Records & faits marquants", ["cards", "table"],232 count=len(dash["records"]))233 return out234235EMAILS = [236 ("contact@spboucher.ai", "Questions, partenariats & données"),237]238DISCLAIMER = (239 "Immo-Ka est un agrégateur de contenu : nous ne vendons rien, ne louons "240 "rien et ne sommes partie à aucune transaction. Données lues à la source, "241 "rien d'inventé, tout est traçable."242)243244245def _hex(c: str) -> tuple[int, int, int]:246 c = c.lstrip("#")247 return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore248249250def _fr(n) -> str:251 if isinstance(n, float) and not n.is_integer():252 return f"{n:,.2f}".replace(",", " ").replace(".", ",")253 return f"{int(n):,}".replace(",", " ")254255256_SUBST = {257 "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",258 "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',259 "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",260 "×": "x", "·": ".", "σ": "sigma", "Δ": "delta",261}262263264def _latin1(s: str) -> str:265 for k, v in _SUBST.items():266 s = s.replace(k, v)267 return s.encode("latin-1", "replace").decode("latin-1")268269270class _PDF(FPDF):271 """FPDF avec en-tête/pied Immo-Ka sur chaque page (sauf couverture).272 Les polices core sont latin-1 : normalize_text sanitise en amont."""273274 def normalize_text(self, text):275 return super().normalize_text(_latin1(text))276277 def __init__(self, brand: str, accent: tuple, period_label: str):278 super().__init__(orientation="P", unit="mm", format="A4")279 self.brand = brand280 self.accent = accent281 self.period_label = period_label282 self.cover_mode = False283 self.set_margins(18, 20, 18)284 self.set_auto_page_break(True, margin=22)285286 def header(self):287 if self.cover_mode or self.page_no() == 1:288 return289 self.set_font("helvetica", "B", 8.5)290 self.set_text_color(*INK)291 self.set_xy(18, 9)292 self.cell(0, 5, f"{self.brand}")293 self.set_font("helvetica", "", 8)294 self.set_text_color(*INK3)295 self.set_xy(18, 9)296 self.cell(0, 5, "Rapport statistique", align="R")297 self.set_draw_color(*INK)298 self.set_line_width(0.5)299 self.line(18, 15.5, 192, 15.5)300 self.set_y(20)301302 def footer(self):303 # page 1 = couverture (le flag cover_mode est déjà retombé quand304 # add_page() clôt la page 1 → tester aussi le numéro de page)305 if self.cover_mode or self.page_no() == 1:306 return307 self.set_y(-15)308 self.set_draw_color(*INK3)309 self.set_line_width(0.2)310 self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5)311 self.set_font("helvetica", "", 7.5)312 self.set_text_color(*INK3)313 year = datetime.now(ZoneInfo("America/Toronto")).year314 self.cell(130, 5, f"© Immo-Ka — {year} — immo-ka.com · {self.period_label}")315 self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R")316317318class MarketReport:319 def __init__(self, site: dict, dashboard: dict, mode: str = "complet",320 spec: dict | None = None):321 self.site = site322 self.d = dashboard323 self.mode = mode if (mode in REPORT_MODES or mode == CUSTOM_MODE) else "complet"324 self.spec = spec or {}325 self.accent = _hex(site.get("accent", "#d9f26b"))326 period = dashboard.get("period", {}) or {}327 self.period_label = period.get("label") or "toute la période"328 self.pdf = _PDF(site.get("wordmark", ""), self.accent, self.period_label)329 self.toc: list[tuple[str, int]] = []330331 @property332 def mode_label(self) -> str:333 if self.mode == CUSTOM_MODE:334 t = str(self.spec.get("title") or "").strip()335 return f"{CUSTOM_LABEL} — {t}" if t else CUSTOM_LABEL336 return REPORT_MODES[self.mode]337338 # ---------- primitives ----------339 def _card(self, x, y, w, h, fill=WHITE):340 p = self.pdf341 p.set_draw_color(*INK)342 p.set_line_width(0.45)343 p.set_fill_color(*fill)344 p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)345346 def _shade(self, i, n=8):347 shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]348 f = shades[i % len(shades)]349 return tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))350351 def _kicker(self, text):352 p = self.pdf353 p.set_font("helvetica", "B", 8)354 p.set_text_color(*GREEN)355 p.set_draw_color(*GREEN)356 p.set_line_width(0.6)357 y = p.get_y() + 2358 p.line(p.l_margin, y, p.l_margin + 7, y)359 p.set_xy(p.l_margin + 9, y - 2.5)360 p.cell(0, 5, text.upper())361 p.ln(8)362363 def _section_title(self, title):364 if self.pdf.get_y() > 240:365 self.pdf.add_page()366 self._kicker(self.site.get("wordmark", ""))367 self.pdf.set_font("helvetica", "B", 15)368 self.pdf.set_text_color(*INK)369 self.pdf.set_x(self.pdf.l_margin)370 self.pdf.cell(0, 8, title)371 self.toc.append((title, self.pdf.page_no()))372 self.pdf.ln(11)373374 def _chart_title(self, title):375 p = self.pdf376 p.set_font("helvetica", "B", 10)377 p.set_text_color(*INK)378 p.set_x(p.l_margin)379 p.cell(0, 6, title)380 p.ln(7)381382 # ---------- pages ----------383 def _cover(self):384 p = self.pdf385 p.cover_mode = True386 p.set_auto_page_break(False)387 p.add_page()388 p.set_fill_color(*PAPER)389 p.rect(0, 0, 210, 297, style="F")390 p.set_draw_color(*INK)391 p.set_line_width(1.0)392 p.rect(10, 10, 190, 277)393 p.set_font("helvetica", "B", 10)394 p.set_text_color(*SLATE)395 p.set_xy(24, 34)396 p.cell(0, 6, "IMMO-KA · RAPPORT STATISTIQUE")397 wm = self.site.get("wordmark", "")398 try: # logo de marque (maison à la porte rouge + « Immo-Ka »)399 p.image(str(LOGO_PATH), x=22, y=64, w=96)400 except Exception:401 p.set_xy(24, 70)402 p.set_font("helvetica", "B", 40)403 p.set_text_color(*INK)404 p.cell(p.get_string_width(wm) + 2, 20, wm)405 p.set_xy(24, 100)406 p.set_font("helvetica", "", 13)407 p.set_text_color(*INK2)408 p.multi_cell(150, 7, f"{self.mode_label} — {wm}")409 now = datetime.now(ZoneInfo("America/Toronto"))410 per = self.d.get("period", {}) or {}411 p.set_xy(24, 125)412 p.set_font("helvetica", "", 10.5)413 rows = [414 ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),415 ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),416 ("Plateforme", "https://" + self.site.get("domain", "")),417 ("Type de rapport", self.mode_label),418 ]419 y = 128420 for k, v in rows:421 p.set_xy(24, y)422 p.set_text_color(*INK3)423 p.cell(40, 6, k)424 p.set_text_color(*INK)425 p.set_font("helvetica", "B", 10.5)426 p.cell(0, 6, str(v))427 p.set_font("helvetica", "", 10.5)428 y += 8429 p.set_fill_color(*INK)430 p.rect(10, 262, 190, 25, style="F")431 p.set_xy(24, 270)432 p.set_font("helvetica", "B", 12)433 p.set_text_color(*WHITE)434 p.cell(60, 8, "Immo-Ka")435 p.set_font("helvetica", "B", 10)436 p.set_xy(24, 270)437 p.set_text_color(*self.accent)438 p.cell(162, 8, "immo-ka.com", align="R")439 p.set_auto_page_break(True, margin=22)440 p.cover_mode = False441442 def _kpis(self):443 kpis = self.d.get("kpis") or []444 if not kpis:445 return446 self._section_title("Synthèse des indicateurs")447 p = self.pdf448 cols, gw, gh, gap = 3, 56, 26, 3449 x0, y = p.l_margin, p.get_y()450 for i, k in enumerate(kpis[:12]):451 x = x0 + (i % cols) * (gw + gap)452 if i and i % cols == 0:453 y += gh + gap454 if y > 250:455 p.add_page(); y = p.get_y()456 self._card(x, y, gw, gh)457 p.set_xy(x + 4, y + 4)458 p.set_font("helvetica", "B", 14)459 p.set_text_color(*INK)460 val = k.get("value")461 p.cell(gw - 8, 7, (_fr(val) if isinstance(val, (int, float)) else str(val)) + (" " + k["unit"] if k.get("unit") else ""))462 p.set_xy(x + 4, y + 12)463 p.set_font("helvetica", "", 7.6)464 p.set_text_color(*INK2)465 p.multi_cell(gw - 8, 3.6, str(k.get("label", ""))[:70])466 if k.get("delta_pct") is not None:467 up = (k.get("direction") or ("up" if k["delta_pct"] >= 0 else "down")) == "up"468 p.set_xy(x + 4, y + gh - 6.5)469 p.set_font("helvetica", "B", 8)470 p.set_text_color(*(GREEN if up else DANGER))471 arrow = "+" if k["delta_pct"] >= 0 else ""472 dv = round(float(k["delta_pct"]), 1)473 dv = int(dv) if float(dv).is_integer() else dv474 p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(dv).replace('.', ',')} % vs période préc.")475 p.set_y(y + gh + 8)476477 def _gauges(self):478 gs = self.d.get("gauges") or []479 gs = [g for g in gs if isinstance(g.get("value"), (int, float)) and g.get("max")]480 if not gs:481 return482 self._section_title("Taux & couvertures")483 p = self.pdf484 cols, gw, gh, gap = 3, 56, 34, 3485 x0, y = p.l_margin, p.get_y()486 for i, g in enumerate(gs[:9]):487 x = x0 + (i % cols) * (gw + gap)488 if i and i % cols == 0:489 y += gh + gap490 if y > 240:491 p.add_page(); y = p.get_y()492 self._card(x, y, gw, gh)493 frac = max(0.0, min(1.0, g["value"] / g["max"]))494 cx, cy, r = x + gw / 2, y + 20, 14495 # arc de fond + arc de valeur (demi-cercle en petits segments)496 for pass_col, pass_frac, lw in (((225, 223, 217), 1.0, 2.6), (self.accent, frac, 2.6)):497 p.set_draw_color(*pass_col)498 p.set_line_width(lw)499 steps = max(2, int(60 * pass_frac))500 last = None501 for st in range(steps + 1):502 a = math.pi + math.pi * pass_frac * st / steps503 pt = (cx + r * math.cos(a), cy + r * math.sin(a))504 if last:505 p.line(last[0], last[1], pt[0], pt[1])506 last = pt507 p.set_font("helvetica", "B", 11)508 p.set_text_color(*INK)509 p.set_xy(x + 4, cy - 5)510 p.cell(gw - 8, 6, f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}", align="C")511 p.set_font("helvetica", "", 6.6)512 p.set_text_color(*INK3)513 p.set_xy(x + 4, cy + 1.5)514 p.cell(gw - 8, 4, f"{frac * 100:.0f} % de {_fr(g['max'])}", align="C")515 p.set_xy(x + 3, y + gh - 7)516 p.set_font("helvetica", "", 7)517 p.set_text_color(*INK2)518 p.multi_cell(gw - 6, 3.3, str(g.get("label", ""))[:60], align="C")519 p.set_y(y + gh + 8)520521 def _serie_stats_row(self, s):522 """Ligne min/max/moyenne/médiane sous un graphique de série."""523 p = self.pdf524 vs = [pt["v"] for pt in (s.get("points") or []) if isinstance(pt.get("v"), (int, float))]525 if len(vs) < 2:526 return527 sv = sorted(vs)528 mean = sum(vs) / len(vs)529 med = sv[len(sv) // 2]530 sd = math.sqrt(sum((v - mean) ** 2 for v in vs) / len(vs))531 p.set_font("helvetica", "", 6.8)532 p.set_text_color(*INK3)533 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))}")534 p.ln(5.5)535536 def _line_chart(self, s, with_stats=False):537 p = self.pdf538 pts = s.get("points") or []539 if len(pts) < 2:540 return541 if s.get("kind") == "bar":542 self._vbars(s)543 return544 if p.get_y() > 200:545 p.add_page()546 self._chart_title(s.get("title", ""))547 x0, y0, w, h = p.l_margin, p.get_y(), 174, 52548 self._card(x0, y0, w, h, fill=WHITE)549 cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16550 vals = [pt["v"] for pt in pts] + [c["v"] for c in (s.get("compare") or [])]551 vmax = max(vals) or 1552 vmin = min(0, min(vals))553 rng = (vmax - vmin) or 1554 p.set_font("helvetica", "", 6.3)555 p.set_text_color(*INK3)556 p.set_draw_color(200, 200, 195)557 p.set_line_width(0.15)558 for g in range(5):559 gy = cy + ch - ch * g / 4560 p.line(cx, gy, cx + cw, gy)561 p.set_xy(x0 + 1, gy - 1.6)562 p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")563564 def xy(i, n, v):565 return (cx + cw * (i / (n - 1)), cy + ch - ch * ((v - vmin) / rng))566567 # aire sous la courbe (kind=area) : petits trapèzes accent pâle568 if s.get("kind") == "area":569 fill = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * 0.18) for j in range(3))570 p.set_fill_color(*fill)571 p.set_draw_color(*fill)572 n = len(pts)573 for i in range(n - 1):574 x1, y1 = xy(i, n, pts[i]["v"])575 x2, y2 = xy(i + 1, n, pts[i + 1]["v"])576 p.polygon([(x1, y1), (x2, y2), (x2, cy + ch), (x1, cy + ch)], style="DF")577578 def draw(series, color, width, dash=None):579 n = len(series)580 p.set_draw_color(*color)581 p.set_line_width(width)582 if dash:583 p.set_dash_pattern(dash=1.2, gap=1.2)584 last = None585 for i, pt in enumerate(series):586 px, py = xy(i, n, pt["v"])587 if last:588 p.line(last[0], last[1], px, py)589 last = (px, py)590 p.set_dash_pattern()591592 if s.get("compare"):593 draw(s["compare"], INK3, 0.35, dash=True)594 draw(pts, self.accent, 0.7)595 p.set_text_color(*INK3)596 for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):597 p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)598 p.cell(18, 3, str(pts[idx].get("t", ""))[:10], align="C")599 p.set_y(y0 + h + 4)600 if s.get("compare"):601 p.set_font("helvetica", "", 6.8)602 p.set_text_color(*INK3)603 p.cell(0, 4, "— période courante (accent) · ---- période comparée")604 p.ln(5.5)605 if with_stats:606 self._serie_stats_row(s)607 p.ln(1.5)608609 def _vbars(self, s):610 """Barres verticales : série kind=bar ou distribution (bins)."""611 p = self.pdf612 pts = s.get("points") or [{"t": b.get("label"), "v": b.get("value")} for b in (s.get("bins") or [])]613 pts = [pt for pt in pts if isinstance(pt.get("v"), (int, float))]614 if not pts:615 return616 if p.get_y() > 205:617 p.add_page()618 self._chart_title(s.get("title", ""))619 x0, y0, w, h = p.l_margin, p.get_y(), 174, 48620 self._card(x0, y0, w, h, fill=WHITE)621 cx, cy, cw, ch = x0 + 12, y0 + 5, w - 20, h - 14622 vmax = max(pt["v"] for pt in pts) or 1623 p.set_font("helvetica", "", 6.3)624 p.set_text_color(*INK3)625 p.set_draw_color(200, 200, 195)626 p.set_line_width(0.15)627 for g in range(5):628 gy = cy + ch - ch * g / 4629 p.line(cx, gy, cx + cw, gy)630 p.set_xy(x0 + 1, gy - 1.6)631 p.cell(10, 3, _fr(vmax * g / 4), align="R")632 n = len(pts)633 bw = max(0.8, cw / n - 0.6)634 p.set_fill_color(*self.accent)635 p.set_draw_color(*INK)636 p.set_line_width(0.15)637 for i, pt in enumerate(pts):638 bh = ch * (pt["v"] / vmax)639 p.rect(cx + cw * i / n + 0.3, cy + ch - bh, bw, max(bh, 0.4 if pt["v"] > 0 else 0), style="DF")640 p.set_text_color(*INK3)641 for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):642 p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)643 p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")644 p.set_y(y0 + h + 5)645646 def _multiline(self, ms):647 """Multi-séries (≤4) : accent plein / encre fin / accent pointillé /648 gris pointillé — l'identité passe par le motif, pas la couleur seule."""649 p = self.pdf650 series = [s for s in (ms.get("series") or []) if len(s.get("points") or []) > 1][:4]651 if not series:652 return653 if p.get_y() > 195:654 p.add_page()655 self._chart_title(ms.get("title", ""))656 x0, y0, w, h = p.l_margin, p.get_y(), 174, 52657 self._card(x0, y0, w, h, fill=WHITE)658 cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16659 vals = [pt["v"] for s in series for pt in s["points"]]660 vmax = max(vals) or 1661 vmin = min(0, min(vals))662 rng = (vmax - vmin) or 1663 p.set_font("helvetica", "", 6.3)664 p.set_text_color(*INK3)665 p.set_draw_color(200, 200, 195)666 p.set_line_width(0.15)667 for g in range(5):668 gy = cy + ch - ch * g / 4669 p.line(cx, gy, cx + cw, gy)670 p.set_xy(x0 + 1, gy - 1.6)671 p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")672 styles = [673 (self.accent, 0.7, None),674 (INK, 0.45, None),675 (self.accent, 0.55, True),676 (INK3, 0.5, True),677 ]678 for si, s in enumerate(series):679 col, lw, dash = styles[si]680 p.set_draw_color(*col)681 p.set_line_width(lw)682 if dash:683 p.set_dash_pattern(dash=1.4, gap=1.2)684 n = len(s["points"])685 last = None686 for i, pt in enumerate(s["points"]):687 px = cx + cw * (i / (n - 1))688 py = cy + ch - ch * ((pt["v"] - vmin) / rng)689 if last:690 p.line(last[0], last[1], px, py)691 last = (px, py)692 p.set_dash_pattern()693 ref = series[0]["points"]694 p.set_text_color(*INK3)695 for frac, idx in ((0, 0), (0.5, len(ref) // 2), (1, -1)):696 p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)697 p.cell(18, 3, str(ref[idx].get("t", ""))[:10], align="C")698 p.set_y(y0 + h + 4)699 p.set_font("helvetica", "", 6.8)700 p.set_text_color(*INK3)701 marks = ["—", "—", "----", "----"]702 leg = " · ".join(f"{marks[i]} {s.get('label', '')}" for i, s in enumerate(series))703 p.cell(0, 4, leg[:120])704 p.ln(6)705706 def _stacked(self, st):707 p = self.pdf708 keys = (st.get("keys") or [])[:6]709 pts = st.get("points") or []710 if not keys or not pts:711 return712 if p.get_y() > 195:713 p.add_page()714 self._chart_title(st.get("title", ""))715 x0, y0, w, h = p.l_margin, p.get_y(), 174, 52716 self._card(x0, y0, w, h, fill=WHITE)717 cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16718 totals = [sum(v or 0 for v in pt.get("values", [])[: len(keys)]) for pt in pts]719 vmax = max(totals) or 1720 p.set_font("helvetica", "", 6.3)721 p.set_text_color(*INK3)722 p.set_draw_color(200, 200, 195)723 p.set_line_width(0.15)724 for g in range(5):725 gy = cy + ch - ch * g / 4726 p.line(cx, gy, cx + cw, gy)727 p.set_xy(x0 + 1, gy - 1.6)728 p.cell(10, 3, _fr(vmax * g / 4), align="R")729 n = len(pts)730 bw = max(0.8, cw / n - 0.6)731 p.set_draw_color(*WHITE)732 p.set_line_width(0.12)733 for i, pt in enumerate(pts):734 yacc = cy + ch735 for j, k in enumerate(keys):736 v = (pt.get("values") or [0] * len(keys))[j] if j < len(pt.get("values", [])) else 0737 if not v:738 continue739 bh = ch * (v / vmax)740 yacc -= bh741 p.set_fill_color(*self._shade(j))742 p.rect(cx + cw * i / n + 0.3, yacc, bw, max(bh - 0.15, 0.3), style="DF")743 p.set_text_color(*INK3)744 for frac, idx in ((0, 0), (0.5, n // 2), (1, -1)):745 p.set_xy(cx + cw * frac - 10, cy + ch + 1.5)746 p.cell(20, 3, str(pts[idx].get("t", ""))[:12], align="C")747 p.set_y(y0 + h + 4)748 # légende749 p.set_font("helvetica", "", 6.8)750 lx = p.l_margin751 for j, k in enumerate(keys):752 p.set_fill_color(*self._shade(j))753 p.set_draw_color(*INK)754 p.set_line_width(0.2)755 p.rect(lx, p.get_y() + 0.6, 3, 3, style="DF")756 p.set_xy(lx + 4, p.get_y())757 p.set_text_color(*INK2)758 txt = str(k)[:22]759 p.cell(p.get_string_width(txt) + 3, 4, txt)760 lx = p.get_x() + 3761 if lx > 165:762 break763 p.ln(7)764765 def _bars(self, title, items, unit=""):766 p = self.pdf767 items = [it for it in (items or []) if isinstance(it.get("value"), (int, float))][:12]768 if not items:769 return770 need = 10 + len(items) * 7771 if p.get_y() + need > 265:772 p.add_page()773 self._chart_title(title)774 p.ln(1)775 vmax = max(it["value"] for it in items) or 1776 for it in items:777 y = p.get_y()778 p.set_font("helvetica", "", 7.6)779 p.set_text_color(*INK)780 p.set_x(p.l_margin)781 p.cell(46, 5, str(it["label"])[:34])782 bw = 86 * (it["value"] / vmax)783 p.set_fill_color(*self.accent)784 p.set_draw_color(*INK)785 p.set_line_width(0.25)786 p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF")787 p.set_xy(p.l_margin + 136, y)788 p.set_font("helvetica", "B", 7.6)789 p.cell(24, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")790 if it.get("delta_pct") is not None:791 up = it["delta_pct"] >= 0792 p.set_font("helvetica", "B", 6.6)793 p.set_text_color(*(GREEN if up else DANGER))794 p.cell(14, 5, f"{'+' if up else ''}{str(round(it['delta_pct'], 1)).replace('.', ',')} %", align="R")795 p.ln(6.4)796 p.ln(3)797798 def _donut(self, b):799 p = self.pdf800 items = [it for it in (b.get("items") or []) if it.get("value")][:8]801 total = sum(it["value"] for it in items)802 if not items or not total:803 return804 if p.get_y() > 210:805 p.add_page()806 self._chart_title(b.get("title", ""))807 p.ln(1)808 cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20809 start = -90.0810 for i, it in enumerate(items):811 frac = it["value"] / total812 col = self._shade(i)813 steps = max(2, int(72 * frac))814 p.set_fill_color(*col)815 p.set_draw_color(*col)816 for st in range(steps):817 a0 = math.radians(start + 360 * frac * st / steps)818 a1 = math.radians(start + 360 * frac * (st + 1) / steps)819 p.polygon(820 [(cx, cy),821 (cx + r * math.cos(a0), cy + r * math.sin(a0)),822 (cx + r * math.cos(a1), cy + r * math.sin(a1))],823 style="DF",824 )825 start += 360 * frac826 p.set_fill_color(*WHITE)827 p.set_draw_color(*INK)828 p.set_line_width(0.4)829 p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")830 p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")831 ly = cy - 22832 for i, it in enumerate(items):833 col = self._shade(i)834 p.set_fill_color(*col)835 p.set_draw_color(*INK)836 p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")837 p.set_xy(p.l_margin + 66, ly)838 p.set_font("helvetica", "", 7.6)839 p.set_text_color(*INK)840 pct = 100 * it["value"] / total841 p.cell(0, 5.6, f"{str(it['label'])[:40]} — {_fr(it['value'])} ({pct:.1f} %)".replace(".", ","))842 ly += 5.6843 p.set_y(max(cy + r, ly) + 6)844845 def _hourly(self):846 hh = self.d.get("hourly") or {}847 cells = hh.get("cells") or []848 if not cells:849 return850 p = self.pdf851 if p.get_y() > 190:852 p.add_page()853 self._chart_title(hh.get("title", "Activité par jour et heure"))854 x0, y0 = p.l_margin, p.get_y()855 cw, chh, lx, ly = 6.4, 6.4, 12, 5856 vmax = max((c.get("value") or 0) for c in cells) or 1857 grid = {(c.get("dow"), c.get("hour")): c.get("value") or 0 for c in cells}858 dows = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"]859 p.set_font("helvetica", "", 5.8)860 p.set_text_color(*INK3)861 for h in (0, 6, 12, 18, 23):862 p.set_xy(x0 + lx + h * cw, y0)863 p.cell(cw, 3, f"{h}h", align="C")864 for d in range(7):865 p.set_xy(x0, y0 + ly + d * chh + 1.5)866 p.cell(lx - 1, 3, dows[d], align="R")867 for h in range(24):868 v = grid.get((d, h), 0)869 f = 0.1 + 0.9 * (v / vmax) if v else 0.0870 col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3)) if v else (235, 233, 228)871 p.set_fill_color(*col)872 p.set_draw_color(215, 213, 207)873 p.set_line_width(0.1)874 p.rect(x0 + lx + h * cw, y0 + ly + d * chh, cw - 0.5, chh - 0.5, style="DF")875 p.set_y(y0 + ly + 7 * chh + 5)876877 def _calheat(self, hm):878 """v3 — calendrier de chaleur 26 semaines (équivalent PDF du879 CalendarHeatmap du kit front) : colonnes = semaines, lignes = jours."""880 from datetime import date as _date, timedelta as _td881 cells = hm.get("cells") or []882 vals = {c.get("date"): c.get("value") or 0 for c in cells if c.get("date")}883 if not vals:884 return885 p = self.pdf886 if p.get_y() > 215:887 p.add_page()888 self._chart_title(hm.get("title", "Calendrier d'activité"))889 try:890 end = _date.fromisoformat(max(vals))891 except ValueError:892 return893 weeks = 26894 start = end - _td(days=weeks * 7 - 1)895 start -= _td(days=start.weekday()) # lundi896 vmax = max(vals.values()) or 1897 x0, y0 = p.l_margin, p.get_y()898 cw, lx, ly = 6.3, 10, 4899 dows = ["Lun", "", "Mer", "", "Ven", "", "Dim"]900 p.set_font("helvetica", "", 5.8)901 p.set_text_color(*INK3)902 for d in range(7):903 if dows[d]:904 p.set_xy(x0, y0 + ly + d * cw + 1.2)905 p.cell(lx - 1, 3, dows[d], align="R")906 for w in range(weeks):907 monday = start + _td(days=7 * w)908 if monday.day <= 7: # étiquette de mois à la 1re semaine du mois909 p.set_xy(x0 + lx + w * cw, y0)910 p.cell(cw * 4, 3, monday.strftime("%m"))911 for d in range(7):912 day = monday + _td(days=d)913 v = vals.get(day.isoformat(), 0)914 f = 0.15 + 0.85 * (v / vmax) if v else 0.0915 col = (tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f)916 for j in range(3)) if v else (235, 233, 228))917 p.set_fill_color(*col)918 p.set_draw_color(215, 213, 207)919 p.set_line_width(0.1)920 p.rect(x0 + lx + w * cw, y0 + ly + d * cw, cw - 0.5, cw - 0.5,921 style="DF")922 p.set_y(y0 + ly + 7 * cw + 5)923924 # ---------- v3 : conversions bloc → tableau ----------925 @staticmethod926 def _serie_as_table(s):927 unit = s.get("unit") or "Valeur"928 cols = ["Date", unit.capitalize()]929 cmp_ = s.get("compare") or []930 if cmp_:931 cols.append("Période comparée")932 rows = []933 for i, pt in enumerate(s.get("points") or []):934 row = [str(pt.get("t", "")), pt.get("v", "")]935 if cmp_:936 row.append(cmp_[i]["v"] if i < len(cmp_) else "")937 rows.append(row)938 return {"id": s.get("id"), "title": s.get("title", ""),939 "columns": cols, "rows": rows}940941 @staticmethod942 def _multi_as_table(ms):943 labels = [s.get("label", "") for s in (ms.get("series") or [])][:4]944 by_t: dict[str, dict] = {}945 for s in (ms.get("series") or [])[:4]:946 for pt in s.get("points") or []:947 by_t.setdefault(str(pt.get("t", "")), {})[s.get("label", "")] = pt.get("v")948 rows = [[t] + [by_t[t].get(lbl, "") for lbl in labels]949 for t in sorted(by_t)]950 return {"id": ms.get("id"), "title": ms.get("title", ""),951 "columns": ["Date"] + labels, "rows": rows}952953 @staticmethod954 def _stacked_as_table(st):955 keys = (st.get("keys") or [])[:6]956 rows = []957 for pt in st.get("points") or []:958 vs = [(pt.get("values") or [])[j] if j < len(pt.get("values") or []) else 0959 for j in range(len(keys))]960 rows.append([str(pt.get("t", ""))] + vs + [sum(v or 0 for v in vs)])961 return {"id": st.get("id"), "title": st.get("title", ""),962 "columns": ["Date"] + list(keys) + ["Total"], "rows": rows}963964 @staticmethod965 def _items_as_table(id_, title, items, label_col="Libellé"):966 items = items or []967 with_delta = any(it.get("delta_pct") is not None for it in items)968 cols = [label_col, "Valeur"] + (["delta %"] if with_delta else [])969 rows = []970 for it in items:971 row = [str(it.get("label", "")), it.get("value", "")]972 if with_delta:973 d = it.get("delta_pct")974 row.append("" if d is None else f"{'+' if d >= 0 else ''}{d} %")975 rows.append(row)976 return {"id": id_, "title": title, "columns": cols, "rows": rows}977978 def _kpis_as_table(self):979 rows = []980 for k in self.d.get("kpis") or []:981 v = k.get("value")982 val = (_fr(v) if isinstance(v, (int, float)) else str(v)) + \983 ((" " + k["unit"]) if k.get("unit") else "")984 d = k.get("delta_pct")985 rows.append([str(k.get("label", "")), val,986 "" if d is None else f"{'+' if d >= 0 else ''}{d} %"])987 return {"id": "kpis", "title": "Indicateurs clés",988 "columns": ["Indicateur", "Valeur", "delta %"], "rows": rows}989990 def _gauges_as_table(self):991 rows = [[str(g.get("label", "")),992 f"{_fr(g['value'])}{' ' + g['unit'] if g.get('unit') else ''}",993 _fr(g["max"]), f"{100.0 * g['value'] / g['max']:.0f} %"]994 for g in self.d.get("gauges") or []995 if isinstance(g.get("value"), (int, float)) and g.get("max")]996 return {"id": "gauges", "title": "Taux & couvertures",997 "columns": ["Mesure", "Valeur", "Max", "Part"], "rows": rows}998999 def _records_as_table(self):1000 rows = [[str(r.get("label", "")), str(r.get("value", "")),1001 str(r.get("date", "") or "")]1002 for r in self.d.get("records") or []]1003 return {"id": "records", "title": "Records & faits marquants",1004 "columns": ["Fait marquant", "Valeur", "Date"], "rows": rows}10051006 @staticmethod1007 def _heatmap_as_table(hm, title):1008 cells = sorted((hm.get("cells") or []),1009 key=lambda c: -(c.get("value") or 0))[:40]1010 return {"id": "heatmap", "title": title + " — jours les plus chargés",1011 "columns": ["Date", "Valeur"],1012 "rows": [[c.get("date", ""), c.get("value") or 0] for c in cells]}10131014 @staticmethod1015 def _hourly_as_table(hr, title):1016 days = ["Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi",1017 "Dimanche"]1018 cells = sorted((hr.get("cells") or []),1019 key=lambda c: -(c.get("value") or 0))[:40]1020 return {"id": "hourly", "title": title + " — créneaux les plus actifs",1021 "columns": ["Jour", "Heure", "Valeur"],1022 "rows": [[days[c["dow"]] if 0 <= c.get("dow", -1) <= 6 else "?",1023 f"{c.get('hour', '?')} h", c.get("value") or 0]1024 for c in cells]}10251026 # ---------- v3 : rendu d'un bloc du rapport personnalisé ----------1027 def _find(self, coll: str, id_: str):1028 for it in self.d.get(coll) or []:1029 if str(it.get("id")) == id_:1030 return it1031 return None10321033 def _toc_mark(self, title: str):1034 """Blocs graphiques du mode personnalisé : entrée de sommaire sans1035 _section_title (le graphique porte déjà son titre)."""1036 if self.pdf.get_y() > 235:1037 self.pdf.add_page()1038 self.toc.append((title, self.pdf.page_no()))10391040 def _render_block(self, key: str, render: str):1041 section, _, id_ = key.partition(":")1042 if section == "kpis":1043 self._table(self._kpis_as_table()) if render == "table" else self._kpis()1044 elif section == "gauges":1045 self._table(self._gauges_as_table()) if render == "table" else self._gauges()1046 elif section == "records":1047 self._table(self._records_as_table()) if render == "table" else self._records()1048 elif section == "series":1049 s = self._find("series", id_)1050 if not s:1051 return1052 if render == "table":1053 self._table(self._serie_as_table(s), max_rows=400)1054 else:1055 s2 = dict(s)1056 if render in ("line", "area", "bar"):1057 s2["kind"] = render1058 self._toc_mark(s2.get("title", ""))1059 if s2.get("kind") == "bar":1060 self._vbars(s2)1061 else:1062 self._line_chart(s2, with_stats=True)1063 elif section == "multiseries":1064 ms = self._find("multiseries", id_)1065 if not ms:1066 return1067 if render == "table":1068 self._table(self._multi_as_table(ms), max_rows=400)1069 else:1070 self._toc_mark(ms.get("title", ""))1071 self._multiline(ms)1072 elif section == "stacked":1073 st = self._find("stacked", id_)1074 if not st:1075 return1076 if render == "table":1077 self._table(self._stacked_as_table(st), max_rows=400)1078 else:1079 self._toc_mark(st.get("title", ""))1080 self._stacked(st)1081 elif section == "breakdowns":1082 b = self._find("breakdowns", id_)1083 if not b:1084 return1085 if render == "table":1086 self._table(self._items_as_table(id_, b.get("title", ""),1087 b.get("items")), max_rows=400)1088 else:1089 self._toc_mark(b.get("title", ""))1090 if render == "donut":1091 self._donut(b)1092 else:1093 self._bars(b.get("title", ""), b.get("items"))1094 elif section == "distributions":1095 d = self._find("distributions", id_)1096 if not d:1097 return1098 if render == "table":1099 bins = [{"label": bn.get("label"), "value": bn.get("value")}1100 for bn in d.get("bins") or []]1101 self._table(self._items_as_table(id_, d.get("title", ""), bins,1102 label_col="Tranche"))1103 else:1104 self._toc_mark(d.get("title", ""))1105 self._vbars(d)1106 elif section == "geo":1107 geo = self.d.get("geo") or {}1108 if not geo.get("items"):1109 return1110 title = geo.get("title", "Répartition géographique")1111 if render == "table":1112 self._table(self._items_as_table("geo", title, geo["items"],1113 label_col="Zone"), max_rows=400)1114 else:1115 self._toc_mark(title)1116 self._bars(title, geo["items"])1117 elif section == "heatmap":1118 hm = self.d.get("heatmap") or {}1119 if not hm.get("cells"):1120 return1121 title = hm.get("title", "Calendrier d'activité")1122 if render == "table":1123 self._table(self._heatmap_as_table(hm, title))1124 else:1125 self._toc_mark(title)1126 self._calheat(hm)1127 elif section == "hourly":1128 hr = self.d.get("hourly") or {}1129 if not hr.get("cells"):1130 return1131 title = hr.get("title", "Activité par jour et heure")1132 if render == "table":1133 self._table(self._hourly_as_table(hr, title))1134 else:1135 self._toc_mark(title)1136 self._hourly()1137 elif section == "tables":1138 t = self._find("tables", id_)1139 if t:1140 self._table(t, max_rows=400)11411142 def _table(self, t, max_rows=200):1143 p = self.pdf1144 cols = t.get("columns") or []1145 rows = t.get("rows") or []1146 if not cols or not rows:1147 return1148 self._section_title(t.get("title", "Tableau"))1149 w = 174 / len(cols)1150 def head():1151 p.set_font("helvetica", "B", 7.6)1152 p.set_fill_color(*INK)1153 p.set_text_color(*WHITE)1154 for c in cols:1155 p.cell(w, 6, " " + str(c)[:30], fill=True)1156 p.ln(6)1157 head()1158 p.set_text_color(*INK)1159 for i, row in enumerate(rows[:max_rows]):1160 if p.get_y() > 262:1161 p.add_page()1162 head()1163 p.set_text_color(*INK)1164 p.set_font("helvetica", "", 7.4)1165 p.set_fill_color(*(SURFACE2 if i % 2 else WHITE))1166 for cell in row:1167 txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)1168 p.cell(w, 5.4, " " + txt[:34], fill=True)1169 p.ln(5.4)1170 if len(rows) > max_rows:1171 p.set_font("helvetica", "", 7)1172 p.set_text_color(*INK3)1173 p.cell(0, 5, f"… {len(rows) - max_rows} lignes supplémentaires non imprimées")1174 p.ln(6)11751176 def _records(self):1177 recs = self.d.get("records") or []1178 if not recs:1179 return1180 self._section_title("Records & faits marquants")1181 p = self.pdf1182 for r in recs[:14]:1183 if p.get_y() > 258:1184 p.add_page()1185 y = p.get_y()1186 self._card(p.l_margin, y, 174, 11, fill=SURFACE2)1187 p.set_xy(p.l_margin + 4, y + 2)1188 p.set_font("helvetica", "", 8.6)1189 p.set_text_color(*INK2)1190 p.cell(96, 7, str(r.get("label", ""))[:70])1191 p.set_font("helvetica", "B", 9)1192 p.set_text_color(*INK)1193 p.cell(52, 7, str(r.get("value", ""))[:36], align="R")1194 p.set_font("helvetica", "", 7.6)1195 p.set_text_color(*INK3)1196 p.cell(20, 7, str(r.get("date", "") or ""), align="R")1197 p.set_y(y + 13.5)1198 p.ln(4)11991200 def _final_page(self):1201 p = self.pdf1202 p.add_page()1203 self._kicker("Contact")1204 p.set_font("helvetica", "B", 15)1205 p.set_text_color(*INK)1206 p.cell(0, 8, "Coordonnées d'Immo-Ka")1207 p.ln(12)1208 for email, role in EMAILS:1209 p.set_font("helvetica", "B", 10.5)1210 p.set_text_color(*INK)1211 p.cell(0, 6, email)1212 p.ln(5.5)1213 p.set_font("helvetica", "", 8.6)1214 p.set_text_color(*INK3)1215 p.cell(0, 5, role)1216 p.ln(8)1217 p.ln(2)1218 p.set_font("helvetica", "B", 10)1219 p.set_text_color(*GREEN)1220 p.cell(0, 6, "immo-ka.com — toutes les propriétés à vendre au Québec")1221 p.ln(10)1222 p.set_draw_color(*self.accent)1223 p.set_line_width(0.8)1224 p.line(p.l_margin, p.get_y(), p.l_margin + 30, p.get_y())1225 p.ln(4)1226 p.set_font("helvetica", "", 8.6)1227 p.set_text_color(*INK2)1228 p.multi_cell(160, 4.6, DISCLAIMER)1229 p.ln(4)1230 p.set_font("helvetica", "", 7.6)1231 p.set_text_color(*INK3)1232 p.multi_cell(1233 160, 4.2,1234 "Mentions : rapport généré automatiquement à partir des données réelles de la "1235 "plateforme au moment indiqué en couverture. Conditions d'utilisation, politique "1236 "de confidentialité et protection des renseignements personnels (Loi 25) : "1237 "immo-ka.com/conditions · /confidentialite.",1238 )12391240 # ---------- groupes de sections ----------1241 def _all_series(self, with_stats=True):1242 for s in self.d.get("series") or []:1243 self._line_chart(s, with_stats=with_stats)1244 for ms in self.d.get("multiseries") or []:1245 self._multiline(ms)1246 for st in self.d.get("stacked") or []:1247 self._stacked(st)12481249 def _all_breakdowns(self):1250 for b in self.d.get("breakdowns") or []:1251 if b.get("kind") == "donut":1252 self._donut(b)1253 else:1254 self._bars(b.get("title", ""), b.get("items"))1255 for dist in self.d.get("distributions") or []:1256 self._vbars(dist)1257 geo = self.d.get("geo")1258 if geo:1259 self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))1260 self._hourly()12611262 def build(self) -> bytes:1263 p = self.pdf1264 p.alias_nb_pages()1265 self._cover()1266 with_toc = self.mode in ("complet", "donnees", CUSTOM_MODE)1267 toc_page_no = None1268 if self.mode == "synthese":1269 p.add_page()1270 self._kpis()1271 self._gauges()1272 self._records()1273 self._final_page()1274 elif self.mode == "tendances":1275 p.add_page()1276 self._kpis()1277 self._section_title("Évolution & tendances")1278 self._all_series(with_stats=True)1279 self._records()1280 self._final_page()1281 elif self.mode == "repartitions":1282 p.add_page()1283 self._section_title("Répartitions, distributions & géographie")1284 self._all_breakdowns()1285 self._final_page()1286 elif self.mode == "donnees":1287 p.add_page()1288 toc_page_no = p.page_no()1289 for t in self.d.get("tables") or []:1290 self._table(t, max_rows=400)1291 self._final_page()1292 elif self.mode == CUSTOM_MODE:1293 p.add_page()1294 toc_page_no = p.page_no()1295 p.add_page()1296 known = {b["key"]: b for b in catalog(self.d)}1297 for blk in self.spec.get("blocks") or []:1298 key = str(blk.get("key", ""))1299 b = known.get(key)1300 if not b:1301 continue1302 render = str(blk.get("render") or "")1303 if render not in b["renders"]:1304 render = b["default_render"]1305 self._render_block(key, render)1306 self._final_page()1307 else: # complet1308 p.add_page()1309 toc_page_no = p.page_no()1310 p.add_page()1311 self._kpis()1312 self._gauges()1313 if (self.d.get("series") or self.d.get("multiseries") or self.d.get("stacked")):1314 self._section_title("Évolution & tendances")1315 self._all_series(with_stats=True)1316 if (self.d.get("breakdowns") or self.d.get("distributions") or self.d.get("geo") or self.d.get("hourly")):1317 self._section_title("Répartitions, distributions & géographie")1318 self._all_breakdowns()1319 for t in self.d.get("tables") or []:1320 self._table(t)1321 self._records()1322 self._final_page()1323 # sommaire écrit sur la page réservée1324 if toc_page_no is not None:1325 last_page = p.page1326 p.page = toc_page_no1327 p.set_y(22)1328 p.set_font("helvetica", "B", 15)1329 p.set_text_color(*INK)1330 p.cell(0, 8, "Sommaire")1331 p.ln(12)1332 p.set_font("helvetica", "", 9.5)1333 for title, page_no in self.toc:1334 p.set_text_color(*INK)1335 p.cell(140, 6.5, title[:80])1336 p.set_text_color(*INK3)1337 p.cell(0, 6.5, str(page_no), align="R")1338 p.ln(6.5)1339 p.page = last_page1340 return bytes(p.output())134113421343def filename(platform_id: str, period: str, mode: str = "complet") -> str:1344 today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")1345 suffix = "" if mode in ("", "complet") else f"_{mode}"1346 return f"{platform_id}_stats_{period}{suffix}_{today}.pdf"1347