SPB Git forge

spb/fabri-ka

Public

Agrégateur de produits québécois — www.fabri-ka.com

217commits 1branches 0releases
66.1 MBsize
maindefault branch
5 h agolast push
Python 38.4% HTML 30.3% TypeScript 17.2% CSS 11% JavaScript 3.2%
20.6 KB · 559 lines python
Raw Blame History
1# Auteur : Simon-Pierre Boucher — contact@spboucher.ai2# ka-ui/stats/kapdf.py — moteur PDF commun Groupe KA (fpdf2).3# Consomme le JSON du contrat /api/stats/dashboard (voir SPEC.md) et produit4# le rapport estampillé Groupe-KA : couverture, sommaire, KPI, graphiques5# VECTORIELS (courbes/barres/anneaux), tableaux paginés, records, page de fin.6# Usage :7#   from kapdf import GroupeKAReport8#   pdf_bytes = GroupeKAReport(site={"wordmark":"Lou·Ka","accent":"#ff6a00",9#       "domain":"www.lou-ka.com","tagline":"…"}, dashboard=dash_json,10#       mode="complet").build()11# Dépendance : pip install fpdf2  (aucune autre)12from __future__ import annotations1314import math15from datetime import datetime16from zoneinfo import ZoneInfo1718from fpdf import FPDF1920INK = (20, 24, 20)21INK2 = (77, 85, 81)22INK3 = (139, 146, 140)23PAPER = (245, 243, 238)24SURFACE2 = (250, 249, 245)25GREEN = (28, 92, 65)26DANGER = (179, 66, 58)27WHITE = (255, 255, 255)2829EMAILS = [30    ("contact@groupe-ka.com", "Projets, partenariats & données"),31    ("info@groupe-ka.com", "Médias & questions générales"),32    ("admin@groupe-ka.com", "Légal, vie privée & Loi 25"),33]34DISCLAIMER = (35    "Groupe KA est un agrégateur de contenu : nous ne vendons rien, ne louons "36    "rien et ne sommes partie à aucune transaction. Données lues à la source, "37    "rien d'inventé, tout est traçable."38)394041def _hex(c: str) -> tuple[int, int, int]:42    c = c.lstrip("#")43    return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4))  # type: ignore444546def _fr(n) -> str:47    if isinstance(n, float) and not n.is_integer():48        return f"{n:,.2f}".replace(",", " ").replace(".", ",")49    return f"{int(n):,}".replace(",", " ")505152_SUBST = {53    "—": "-", "–": "-", "→": "->", "▲": "+", "▼": "-",54    "…": "...", "’": "'", "‘": "'", "“": '"', "”": '"',55    "œ": "oe", "Œ": "OE", "−": "-", " ": " ", " ": " ",56}575859def _latin1(s: str) -> str:60    for k, v in _SUBST.items():61        s = s.replace(k, v)62    return s.encode("latin-1", "replace").decode("latin-1")636465class _PDF(FPDF):66    """FPDF avec en-tête/pied Groupe-KA sur chaque page (sauf couverture).67    Les polices core sont latin-1 : normalize_text sanitise en amont."""6869    def normalize_text(self, text):70        return super().normalize_text(_latin1(text))7172    def __init__(self, brand: str, accent: tuple, period_label: str):73        super().__init__(orientation="P", unit="mm", format="A4")74        self.brand = brand75        self.accent = accent76        self.period_label = period_label77        self.cover_mode = False78        self.set_margins(18, 20, 18)79        self.set_auto_page_break(True, margin=22)8081    def header(self):82        if self.cover_mode:83            return84        self.set_font("helvetica", "B", 8.5)85        self.set_text_color(*INK)86        self.set_xy(18, 9)87        self.cell(0, 5, f"Groupe KA · {self.brand}")88        self.set_font("helvetica", "", 8)89        self.set_text_color(*INK3)90        self.set_xy(18, 9)91        self.cell(0, 5, "Rapport statistique", align="R")92        self.set_draw_color(*INK)93        self.set_line_width(0.5)94        self.line(18, 15.5, 192, 15.5)95        self.set_y(20)9697    def footer(self):98        if self.cover_mode:99            return100        self.set_y(-15)101        self.set_draw_color(*INK3)102        self.set_line_width(0.2)103        self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5)104        self.set_font("helvetica", "", 7.5)105        self.set_text_color(*INK3)106        year = datetime.now(ZoneInfo("America/Toronto")).year107        self.cell(130, 5, f"© Groupe-KA — {year} — groupe-ka.com · {self.period_label}")108        self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R")109110111class GroupeKAReport:112    def __init__(self, site: dict, dashboard: dict, mode: str = "complet"):113        self.site = site114        self.d = dashboard115        self.mode = mode116        self.accent = _hex(site.get("accent", "#d9f26b"))117        period = dashboard.get("period", {}) or {}118        self.period_label = period.get("label") or "toute la période"119        self.pdf = _PDF(site.get("wordmark", ""), self.accent, self.period_label)120        self.toc: list[tuple[str, int]] = []121122    # ---------- primitives ----------123    def _card(self, x, y, w, h, fill=WHITE):124        p = self.pdf125        p.set_draw_color(*INK)126        p.set_line_width(0.45)127        p.set_fill_color(*fill)128        p.rect(x, y, w, h, style="DF", round_corners=True, corner_radius=2.2)129130    def _kicker(self, text):131        p = self.pdf132        p.set_font("helvetica", "B", 8)133        p.set_text_color(*GREEN)134        p.set_draw_color(*GREEN)135        p.set_line_width(0.6)136        y = p.get_y() + 2137        p.line(p.l_margin, y, p.l_margin + 7, y)138        p.set_xy(p.l_margin + 9, y - 2.5)139        p.cell(0, 5, text.upper())140        p.ln(8)141142    def _section_title(self, title):143        if self.pdf.get_y() > 240:144            self.pdf.add_page()145        self._kicker("Groupe KA · " + self.site.get("wordmark", ""))146        self.pdf.set_font("helvetica", "B", 15)147        self.pdf.set_text_color(*INK)148        self.pdf.set_x(self.pdf.l_margin)149        self.pdf.cell(0, 8, title)150        self.toc.append((title, self.pdf.page_no()))151        self.pdf.ln(11)152153    # ---------- pages ----------154    def _cover(self):155        p = self.pdf156        p.cover_mode = True157        p.set_auto_page_break(False)158        p.add_page()159        p.set_fill_color(*PAPER)160        p.rect(0, 0, 210, 297, style="F")161        p.set_draw_color(*INK)162        p.set_line_width(1.0)163        p.rect(10, 10, 190, 277)164        # kicker165        p.set_font("helvetica", "B", 10)166        p.set_text_color(*GREEN)167        p.set_xy(24, 34)168        p.cell(0, 6, "GROUPE KA · RAPPORT STATISTIQUE")169        # wordmark : partie gauche + boîte encre/accent170        wm = self.site.get("wordmark", "")171        left, boxed = (wm.split("·") + [None])[:2] if "·" in wm else (wm, None)172        p.set_xy(24, 70)173        p.set_font("helvetica", "B", 40)174        p.set_text_color(*INK)175        p.cell(p.get_string_width(left) + 2, 20, left)176        if boxed:177            bw = p.get_string_width(boxed) + 12178            x = p.get_x() + 2179            p.set_fill_color(*INK)180            p.rect(x, 68, bw, 22, style="F", round_corners=True, corner_radius=3)181            p.set_text_color(*self.accent)182            p.set_xy(x + 6, 70)183            p.cell(bw - 12, 18, boxed)184        p.set_xy(24, 100)185        p.set_font("helvetica", "", 13)186        p.set_text_color(*INK2)187        p.multi_cell(150, 7, f"Rapport statistique — {wm}")188        now = datetime.now(ZoneInfo("America/Toronto"))189        per = self.d.get("period", {}) or {}190        p.set_xy(24, 125)191        p.set_font("helvetica", "", 10.5)192        rows = [193            ("Période couverte", self.period_label + (f" ({per.get('from')} → {per.get('to')})" if per.get("from") else "")),194            ("Généré le", now.strftime("%Y-%m-%d à %H:%M") + " (heure de l'Est)"),195            ("Plateforme", "https://" + self.site.get("domain", "")),196            ("Mode", "Rapport complet" if self.mode == "complet" else "Synthèse"),197        ]198        y = 128199        for k, v in rows:200            p.set_xy(24, y)201            p.set_text_color(*INK3)202            p.cell(40, 6, k)203            p.set_text_color(*INK)204            p.set_font("helvetica", "B", 10.5)205            p.cell(0, 6, str(v))206            p.set_font("helvetica", "", 10.5)207            y += 8208        # bande encre au pied209        p.set_fill_color(*INK)210        p.rect(10, 262, 190, 25, style="F")211        p.set_xy(24, 270)212        p.set_font("helvetica", "B", 12)213        p.set_text_color(*WHITE)214        p.cell(60, 8, "par Groupe ")215        p.set_text_color(*self.accent)216        p.set_xy(24 + p.get_string_width("par Groupe ") + 1, 270)217        p.cell(20, 8, "KA")218        p.set_font("helvetica", "B", 10)219        p.set_xy(24, 270)220        p.set_text_color(*self.accent)221        p.cell(162, 8, "groupe-ka.com", align="R")222        p.set_auto_page_break(True, margin=22)223        p.cover_mode = False224225    def _kpis(self):226        kpis = self.d.get("kpis") or []227        if not kpis:228            return229        self._section_title("Synthèse des indicateurs")230        p = self.pdf231        cols, gw, gh, gap = 3, 56, 26, 3232        x0, y = p.l_margin, p.get_y()233        for i, k in enumerate(kpis[:9]):234            x = x0 + (i % cols) * (gw + gap)235            if i and i % cols == 0:236                y += gh + gap237            if y > 250:238                p.add_page(); y = p.get_y()239            self._card(x, y, gw, gh)240            p.set_xy(x + 4, y + 4)241            p.set_font("helvetica", "B", 14)242            p.set_text_color(*INK)243            val = k.get("value")244            p.cell(gw - 8, 7, (_fr(val) if isinstance(val, (int, float)) else str(val)) + (" " + k["unit"] if k.get("unit") else ""))245            p.set_xy(x + 4, y + 12)246            p.set_font("helvetica", "", 7.6)247            p.set_text_color(*INK2)248            p.multi_cell(gw - 8, 3.6, str(k.get("label", ""))[:70])249            if k.get("delta_pct") is not None:250                up = (k.get("direction") or ("up" if k["delta_pct"] >= 0 else "down")) == "up"251                p.set_xy(x + 4, y + gh - 6.5)252                p.set_font("helvetica", "B", 8)253                p.set_text_color(*(GREEN if up else DANGER))254                arrow = "+" if k["delta_pct"] >= 0 else ""255                p.cell(gw - 8, 4, f"{'▲' if up else '▼'} {arrow}{str(k['delta_pct']).replace('.', ',')} % vs période préc.")256        p.set_y(y + gh + 8)257258    def _line_chart(self, s):259        p = self.pdf260        pts = s.get("points") or []261        if len(pts) < 2:262            return263        if p.get_y() > 200:264            p.add_page()265        p.set_font("helvetica", "B", 10)266        p.set_text_color(*INK)267        p.cell(0, 6, s.get("title", ""))268        p.ln(7)269        x0, y0, w, h = p.l_margin, p.get_y(), 174, 52270        self._card(x0, y0, w, h, fill=WHITE)271        cx, cy, cw, ch = x0 + 12, y0 + 6, w - 20, h - 16272        vals = [pt["v"] for pt in pts] + [c["v"] for c in (s.get("compare") or [])]273        vmax = max(vals) or 1274        vmin = min(0, min(vals))275        rng = (vmax - vmin) or 1276        # grille + graduations277        p.set_font("helvetica", "", 6.3)278        p.set_text_color(*INK3)279        p.set_draw_color(200, 200, 195)280        p.set_line_width(0.15)281        for g in range(5):282            gy = cy + ch - ch * g / 4283            p.line(cx, gy, cx + cw, gy)284            p.set_xy(x0 + 1, gy - 1.6)285            p.cell(10, 3, _fr(vmin + rng * g / 4), align="R")286287        def draw(series, color, width, dash=None):288            n = len(series)289            p.set_draw_color(*color)290            p.set_line_width(width)291            if dash:292                p.set_dash_pattern(dash=1.2, gap=1.2)293            last = None294            for i, pt in enumerate(series):295                px = cx + cw * (i / (n - 1))296                py = cy + ch - ch * ((pt["v"] - vmin) / rng)297                if last:298                    p.line(last[0], last[1], px, py)299                last = (px, py)300            p.set_dash_pattern()301302        if s.get("compare"):303            draw(s["compare"], INK3, 0.35, dash=True)304        draw(pts, self.accent, 0.7)305        # libellés d'axe X (premier / milieu / dernier)306        p.set_text_color(*INK3)307        for frac, idx in ((0, 0), (0.5, len(pts) // 2), (1, -1)):308            p.set_xy(cx + cw * frac - 9, cy + ch + 1.5)309            p.cell(18, 3, str(pts[idx].get("t", ""))[:10], align="C")310        p.set_y(y0 + h + 4)311        if s.get("compare"):312            p.set_font("helvetica", "", 6.8)313            p.set_text_color(*INK3)314            p.cell(0, 4, "— période courante (accent) · ---- période comparée")315            p.ln(6)316        else:317            p.ln(2)318319    def _bars(self, title, items, unit=""):320        p = self.pdf321        items = [it for it in (items or []) if isinstance(it.get("value"), (int, float))][:12]322        if not items:323            return324        need = 10 + len(items) * 7325        if p.get_y() + need > 265:326            p.add_page()327        p.set_font("helvetica", "B", 10)328        p.set_text_color(*INK)329        p.cell(0, 6, title)330        p.ln(8)331        vmax = max(it["value"] for it in items) or 1332        for it in items:333            y = p.get_y()334            p.set_font("helvetica", "", 7.6)335            p.set_text_color(*INK)336            p.set_x(p.l_margin)337            p.cell(46, 5, str(it["label"])[:34])338            bw = 96 * (it["value"] / vmax)339            p.set_fill_color(*self.accent)340            p.set_draw_color(*INK)341            p.set_line_width(0.25)342            p.rect(p.l_margin + 48, y + 0.7, max(bw, 0.8), 3.6, style="DF")343            p.set_xy(p.l_margin + 148, y)344            p.set_font("helvetica", "B", 7.6)345            p.cell(26, 5, _fr(it["value"]) + (" " + unit if unit else ""), align="R")346            p.ln(6.4)347        p.ln(3)348349    def _donut(self, b):350        # anneau vectoriel simple (arcs) + légende351        p = self.pdf352        items = [it for it in (b.get("items") or []) if it.get("value")][:8]353        total = sum(it["value"] for it in items)354        if not items or not total:355            return356        if p.get_y() > 210:357            p.add_page()358        p.set_font("helvetica", "B", 10)359        p.set_text_color(*INK)360        p.cell(0, 6, b.get("title", ""))361        p.ln(8)362        cx, cy, r = p.l_margin + 26, p.get_y() + 24, 20363        shades = [1.0, 0.78, 0.58, 0.42, 0.30, 0.22, 0.15, 0.10]364        start = -90.0365        for i, it in enumerate(items):366            frac = it["value"] / total367            f = shades[i % len(shades)]368            col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))369            steps = max(2, int(72 * frac))370            p.set_fill_color(*col)371            p.set_draw_color(*col)372            for st in range(steps):373                a0 = math.radians(start + 360 * frac * st / steps)374                a1 = math.radians(start + 360 * frac * (st + 1) / steps)375                p.polygon(376                    [(cx, cy),377                     (cx + r * math.cos(a0), cy + r * math.sin(a0)),378                     (cx + r * math.cos(a1), cy + r * math.sin(a1))],379                    style="DF",380                )381            start += 360 * frac382        p.set_fill_color(*WHITE)383        p.set_draw_color(*INK)384        p.set_line_width(0.4)385        p.ellipse(cx - 11, cy - 11, 22, 22, style="DF")386        p.ellipse(cx - r, cy - r, 2 * r, 2 * r, style="D")387        # légende388        ly = cy - 22389        for i, it in enumerate(items):390            f = shades[i % len(shades)]391            col = tuple(int(PAPER[j] + (self.accent[j] - PAPER[j]) * f) for j in range(3))392            p.set_fill_color(*col)393            p.set_draw_color(*INK)394            p.rect(p.l_margin + 60, ly + 0.8, 4, 4, style="DF")395            p.set_xy(p.l_margin + 66, ly)396            p.set_font("helvetica", "", 7.6)397            p.set_text_color(*INK)398            pct = 100 * it["value"] / total399            p.cell(0, 5.6, f"{str(it['label'])[:40]} — {_fr(it['value'])} ({pct:.1f} %)".replace(".", ","))400            ly += 5.6401        p.set_y(max(cy + r, ly) + 6)402403    def _table(self, t):404        p = self.pdf405        cols = t.get("columns") or []406        rows = t.get("rows") or []407        if not cols or not rows:408            return409        self._section_title(t.get("title", "Tableau"))410        w = 174 / len(cols)411        def head():412            p.set_font("helvetica", "B", 7.6)413            p.set_fill_color(*INK)414            p.set_text_color(*WHITE)415            for c in cols:416                p.cell(w, 6, " " + str(c)[:30], fill=True)417            p.ln(6)418        head()419        p.set_text_color(*INK)420        for i, row in enumerate(rows[:200]):421            if p.get_y() > 262:422                p.add_page()423                head()424                p.set_text_color(*INK)425            p.set_font("helvetica", "", 7.4)426            p.set_fill_color(*(SURFACE2 if i % 2 else WHITE))427            for cell in row:428                txt = _fr(cell) if isinstance(cell, (int, float)) else str(cell)429                p.cell(w, 5.4, " " + txt[:34], fill=True)430            p.ln(5.4)431        if len(rows) > 200:432            p.set_font("helvetica", "", 7)433            p.set_text_color(*INK3)434            p.cell(0, 5, f"… {len(rows) - 200} lignes supplémentaires non imprimées")435        p.ln(6)436437    def _records(self):438        recs = self.d.get("records") or []439        if not recs:440            return441        self._section_title("Records & faits marquants")442        p = self.pdf443        for r in recs[:10]:444            if p.get_y() > 258:445                p.add_page()446            y = p.get_y()447            self._card(p.l_margin, y, 174, 11, fill=SURFACE2)448            p.set_xy(p.l_margin + 4, y + 2)449            p.set_font("helvetica", "", 8.6)450            p.set_text_color(*INK2)451            p.cell(96, 7, str(r.get("label", ""))[:70])452            p.set_font("helvetica", "B", 9)453            p.set_text_color(*INK)454            p.cell(52, 7, str(r.get("value", ""))[:36], align="R")455            p.set_font("helvetica", "", 7.6)456            p.set_text_color(*INK3)457            p.cell(20, 7, str(r.get("date", "") or ""), align="R")458            p.set_y(y + 13.5)459        p.ln(4)460461    def _final_page(self):462        p = self.pdf463        p.add_page()464        self._kicker("Groupe KA · contact")465        p.set_font("helvetica", "B", 15)466        p.set_text_color(*INK)467        p.cell(0, 8, "Coordonnées du Groupe KA")468        p.ln(12)469        for email, role in EMAILS:470            p.set_font("helvetica", "B", 10.5)471            p.set_text_color(*INK)472            p.cell(0, 6, email)473            p.ln(5.5)474            p.set_font("helvetica", "", 8.6)475            p.set_text_color(*INK3)476            p.cell(0, 5, role)477            p.ln(8)478        p.ln(2)479        p.set_font("helvetica", "B", 10)480        p.set_text_color(*GREEN)481        p.cell(0, 6, "groupe-ka.com — le portail de l'écosystème ·Ka")482        p.ln(10)483        p.set_draw_color(*self.accent)484        p.set_line_width(0.8)485        p.line(p.l_margin, p.get_y(), p.l_margin + 30, p.get_y())486        p.ln(4)487        p.set_font("helvetica", "", 8.6)488        p.set_text_color(*INK2)489        p.multi_cell(160, 4.6, DISCLAIMER)490        p.ln(4)491        p.set_font("helvetica", "", 7.6)492        p.set_text_color(*INK3)493        p.multi_cell(494            160, 4.2,495            "Mentions : rapport généré automatiquement à partir des données réelles de la "496            "plateforme au moment indiqué en couverture. Conditions d'utilisation, politique "497            "de confidentialité et protection des renseignements personnels (Loi 25) : "498            "groupe-ka.com/conditions · /confidentialite · /loi-25.",499        )500501    def _toc_page(self):502        # insérée après coup ? fpdf ne réordonne pas : on écrit le sommaire en503        # page 2 en réservant la page lors du build (voir build()).504        pass505506    def build(self) -> bytes:507        p = self.pdf508        p.alias_nb_pages()509        self._cover()510        if self.mode == "synthese":511            p.add_page()512            self._kpis()513            self._records()514            self._final_page()515        else:516            p.add_page()517            toc_page_no = p.page_no()518            p.add_page()519            self._kpis()520            for s in self.d.get("series") or []:521                if s.get("kind") == "bar":522                    self._bars(s.get("title", ""), [{"label": pt.get("t"), "value": pt.get("v")} for pt in (s.get("points") or [])], s.get("unit", ""))523                else:524                    self._line_chart(s)525            for b in self.d.get("breakdowns") or []:526                if b.get("kind") == "donut":527                    self._donut(b)528                else:529                    self._bars(b.get("title", ""), b.get("items"))530            geo = self.d.get("geo")531            if geo:532                self._bars(geo.get("title", "Répartition géographique"), geo.get("items"))533            for t in self.d.get("tables") or []:534                self._table(t)535            self._records()536            self._final_page()537            # sommaire écrit sur la page réservée (page 2)538            last_page = p.page539            p.page = toc_page_no540            p.set_y(22)541            p.set_font("helvetica", "B", 15)542            p.set_text_color(*INK)543            p.cell(0, 8, "Sommaire")544            p.ln(12)545            p.set_font("helvetica", "", 9.5)546            for title, page_no in self.toc:547                p.set_text_color(*INK)548                p.cell(140, 6.5, title[:80])549                p.set_text_color(*INK3)550                p.cell(0, 6.5, str(page_no), align="R")551                p.ln(6.5)552            p.page = last_page553        return bytes(p.output())554555556def filename(platform_id: str, period: str) -> str:557    today = datetime.now(ZoneInfo("America/Toronto")).strftime("%Y-%m-%d")558    return f"groupe-ka_{platform_id}_stats_{period}_{today}.pdf"559