Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/report-stats.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-08-0912 * Last Modified : 2026-08-2313 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * Rapport statistique provincial — PDF vectoriel, moteur pdfkit :44 * couverture « VRAI-PRIX · RAPPORT STATISTIQUE », en-tête/pied45 * normalisés, sommaire paginé, graphiques 100 % VECTORIELS (courbes, aires,46 * barres, multi-courbes à motifs distincts, empilées, anneaux, jauges,47 * calendrier), statistiques de séries (min/max/moy/méd/σ), tableaux zébrés48 * paginés, records, page de fin avec le contact.49 *50 * 5 MODES — un mode inconnu retombe sur « complet » :51 * complet · synthese · tendances · repartitions · donnees52 * Toutes les données viennent de getDashboard() (agrégats réels du rôle).53 */54import PDFDocument from "pdfkit";55import path from "path";56import type { ProvStats } from "@/components/StatsView";57import { getDashboard, buildRecords, PERIOD_LABEL, type KaSerie, type KaRecord } from "@/lib/stats-dashboard";58import stats from "@/data/stats.json";59import { CONTACT_EMAIL } from "@/lib/seo";6061const INK = "#141814";62const INK2 = "#4d5551";63const INK3 = "#8b928c";64const PAPER = "#f5f3ee";65const SURFACE2 = "#faf9f5";66const GREEN = "#9e2a25"; // accentDeep Vrai-Prix (ecosystem.json)67const GREEN_DEEP = "#771f1b";68const LIME = "#ff5148"; // accent Vrai-Prix (ecosystem.json)69const WHITE = "#ffffff";7071/* A4 portrait */72const W = 595.28;73const H = 841.89;74const M = 44;75const CW = W - 2 * M;76const TOP = 56; // début du contenu sous l'en-tête77const BOT = H - 58; // fin du contenu au-dessus du pied7879const F = (f: string) => path.join(process.cwd(), "assets", "fonts", f);80const money = (v: number) =>81 new Intl.NumberFormat("fr-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(v);82const compact = (v: number) => {83 if (v >= 1e12) return `${(v / 1e12).toLocaleString("fr-CA", { maximumFractionDigits: 2 })} billions $`;84 if (v >= 1e9) return `${(v / 1e9).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} G$`;85 if (v >= 1e6) return `${(v / 1e6).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} M$`;86 return money(v);87};88const num = (v: number) => v.toLocaleString("fr-CA");89/** Nombre court pour axes/valeurs de graphiques. */90const short = (v: number) => {91 if (Math.abs(v) >= 1e12) return `${(v / 1e12).toLocaleString("fr-CA", { maximumFractionDigits: 2 })} B`;92 if (Math.abs(v) >= 1e9) return `${(v / 1e9).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} G`;93 if (Math.abs(v) >= 1e6) return `${(v / 1e6).toLocaleString("fr-CA", { maximumFractionDigits: 1 })} M`;94 if (Math.abs(v) >= 1e4) return `${(v / 1e3).toLocaleString("fr-CA", { maximumFractionDigits: 0 })} k`;95 return v.toLocaleString("fr-CA", { maximumFractionDigits: 1 });96};97const POP_QC = 9_111_000;98const BUDGET_QC = 165_800_000_000;99const PIB_QC = 640_000_000_000;100101export const REPORT_MODES = ["complet", "synthese", "tendances", "repartitions", "donnees"] as const;102export type ReportMode = (typeof REPORT_MODES)[number];103const MODE_FR: Record<ReportMode, string> = {104 complet: "Rapport complet",105 synthese: "Synthèse exécutive",106 tendances: "Tendances & évolution",107 repartitions: "Répartitions & géographie",108 donnees: "Données détaillées",109};110111type Doc = InstanceType<typeof PDFDocument>;112type Dash = ReturnType<typeof getDashboard>;113114/** Wordmark Vrai-Prix : « Vrai- » encre + boîte encre / accent rouge #ff5148. */115function wordmark(doc: Doc, x: number, y: number, size = 24) {116 doc.font("SG-Bold").fontSize(size);117 doc.fillColor(INK).text("Vrai-", x, y, { lineBreak: false });118 const w = doc.widthOfString("Vrai-");119 const bx = x + w + 0.18 * size;120 const bw = doc.widthOfString("Prix") + 0.5 * size;121 doc.roundedRect(bx, y - 0.14 * size, bw, 1.28 * size, 0.18 * size).fill(INK);122 doc.fillColor(LIME).text("Prix", bx + 0.25 * size, y, { lineBreak: false });123}124125function kicker(doc: Doc, txt: string, x: number, y: number, size = 8) {126 doc.rect(x, y + size * 0.44, 2.5 * size, size / 4).fill(GREEN);127 doc.font("JB-Bold").fontSize(size).fillColor(GREEN)128 .text(txt.toUpperCase(), x + 2.5 * size + 6, y, { characterSpacing: 0.175 * size, lineBreak: false, width: CW - 2.5 * size - 6, height: size * 1.6, ellipsis: true });129}130131/** En-tête + pied normalisés (numéros de page ajoutés en post-passe). */132function chrome(doc: Doc) {133 const year = new Date().getFullYear();134 doc.rect(0, 0, W, H).fill(PAPER);135 doc.font("SG-Bold").fontSize(9.5).fillColor(INK)136 .text("Vrai-Prix", M, 22, { lineBreak: false });137 doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)138 .text("RAPPORT STATISTIQUE", W - M - 180, 24.5, { width: 180, align: "right", characterSpacing: 0.8 });139 doc.rect(M, 37, CW, 1.1).fill(INK);140 doc.rect(M, H - 42, CW, 0.7).fill(INK3);141 doc.font("JB-Reg").fontSize(6.8).fillColor(INK3)142 .text(`© Vrai-Prix — ${year} — www.vrai-prix.com · ${PERIOD_LABEL}`, M, H - 34, { lineBreak: false });143}144145function card(doc: Doc, x: number, y: number, w: number, h: number, fill = "#ffffff") {146 doc.roundedRect(x + 3, y + 3, w, h, 8).fill("#e3e1d9");147 doc.roundedRect(x, y, w, h, 8).lineWidth(1.3).fillAndStroke(fill, INK);148}149150function hbarRow(doc: Doc, x: number, y: number, w: number, label: string, frac: number, txt: string, sub: string | null, dark = false) {151 doc.font("JB-Bold").fontSize(7.5).fillColor(INK).text(label, x, y + 3, { width: 82, height: 9, ellipsis: true, lineBreak: false });152 const tx = x + 88;153 const tw = w - 88 - 118;154 doc.rect(tx, y, tw, 13).fill(SURFACE2);155 doc.rect(tx, y, Math.max(2, frac * tw), 13).fill(dark ? INK : GREEN);156 doc.font("JB-Bold").fontSize(7.5).fillColor(INK).text(txt, x + w - 112, y + (sub ? 0 : 3), { width: 112, align: "right" });157 if (sub) doc.font("JB-Reg").fontSize(5.8).fillColor(INK3).text(sub, x + w - 112, y + 9, { width: 112, align: "right" });158}159160/* ============================ curseur de page ============================ */161class Cursor {162 y = TOP;163 sections: { label: string; page: number }[] = [];164 constructor(public doc: Doc) {}165 page() {166 // bufferedPageRange().count = pages déjà créées (1-based pour l'humain)167 return this.doc.bufferedPageRange().count;168 }169 ensure(h: number) {170 if (this.y + h > BOT) {171 this.doc.addPage({ size: "A4", margin: 0 });172 chrome(this.doc);173 this.y = TOP;174 }175 }176 section(label: string, remember = true) {177 this.ensure(30);178 if (remember) this.sections.push({ label, page: this.page() });179 kicker(this.doc, label, M, this.y);180 this.y += 20;181 }182}183184/* ============================ primitives graphiques ============================ */185186/** Cadre de graphique : carte + titre, renvoie la zone de tracé. */187function chartFrame(c: Cursor, title: string, h: number) {188 c.ensure(h + 34);189 const { doc } = c;190 card(doc, M, c.y, CW, h + 26);191 doc.font("SG-Bold").fontSize(9.5).fillColor(INK)192 .text(title, M + 14, c.y + 10, { width: CW - 28, height: 12, ellipsis: true, lineBreak: false });193 const area = { x: M + 52, y: c.y + 30, w: CW - 52 - 22, h: h - 14 };194 c.y += h + 26 + 12;195 return area;196}197198function axes(doc: Doc, a: { x: number; y: number; w: number; h: number }, vmin: number, vmax: number, labels: string[]) {199 for (let g = 0; g <= 4; g++) {200 const y = a.y + (a.h * g) / 4;201 const v = vmax - ((vmax - vmin) * g) / 4;202 doc.rect(a.x, y, a.w, 0.5).fill("#e3e1d9");203 doc.font("JB-Reg").fontSize(5.8).fillColor(INK3)204 .text(short(v), a.x - 40, y - 2.5, { width: 36, align: "right", lineBreak: false });205 }206 const idx = [0, Math.floor(labels.length / 2), labels.length - 1].filter((v, i, arr) => arr.indexOf(v) === i);207 idx.forEach((i) => {208 const x = a.x + (labels.length > 1 ? (a.w * i) / (labels.length - 1) : 0);209 doc.font("JB-Reg").fontSize(5.8).fillColor(INK3)210 .text(labels[i] ?? "", x - 24, a.y + a.h + 4, { width: 48, align: "center", lineBreak: false });211 });212}213214function linePdf(c: Cursor, s: KaSerie, h = 120) {215 const pts = s.points ?? [];216 if (pts.length < 2) return;217 const a = chartFrame(c, s.title, h);218 const { doc } = c;219 const vmax = Math.max(...pts.map((p) => p.v), 1);220 const vmin = Math.min(0, ...pts.map((p) => p.v));221 axes(doc, a, vmin, vmax, pts.map((p) => p.t));222 const X = (i: number) => a.x + (a.w * i) / (pts.length - 1);223 const Y = (v: number) => a.y + a.h * (1 - (v - vmin) / (vmax - vmin || 1));224 if (s.kind === "bar") {225 const bw = Math.max(1.2, a.w / pts.length - 1.2);226 pts.forEach((p, i) => {227 const bh = a.h * ((p.v - Math.max(0, vmin)) / (vmax - vmin || 1));228 doc.rect(a.x + (a.w * i) / pts.length, a.y + a.h - bh, bw, Math.max(bh, 0.6)).fill(GREEN);229 });230 return;231 }232 if (s.kind === "area") {233 doc.moveTo(X(0), Y(pts[0].v));234 pts.forEach((p, i) => doc.lineTo(X(i), Y(p.v)));235 doc.lineTo(X(pts.length - 1), a.y + a.h).lineTo(a.x, a.y + a.h).closePath();236 doc.fillOpacity(0.16).fill(GREEN).fillOpacity(1);237 }238 doc.moveTo(X(0), Y(pts[0].v));239 pts.forEach((p, i) => doc.lineTo(X(i), Y(p.v)));240 doc.lineWidth(1.6).strokeColor(GREEN).stroke();241 // point final + valeur242 const lastX = X(pts.length - 1), lastY = Y(pts[pts.length - 1].v);243 doc.circle(lastX, lastY, 2).fill(INK);244 doc.font("JB-Bold").fontSize(6).fillColor(INK)245 .text(short(pts[pts.length - 1].v), lastX - 60, lastY - 10, { width: 58, align: "right", lineBreak: false });246}247248/** Min/max/moyenne/médiane/écart-type sous une courbe (SPEC §1.4). */249function statLine(c: Cursor, s: KaSerie) {250 const vs = (s.points ?? []).map((p) => p.v);251 if (vs.length < 2) return;252 const sorted = [...vs].sort((x, y) => x - y);253 const mean = vs.reduce((x, y) => x + y, 0) / vs.length;254 const sd = Math.sqrt(vs.reduce((x, v) => x + (v - mean) ** 2, 0) / vs.length);255 const items: [string, number][] = [256 ["MIN", sorted[0]], ["MAX", sorted[sorted.length - 1]], ["MOYENNE", mean],257 ["MÉDIANE", sorted[Math.floor(sorted.length / 2)]], ["ÉCART-TYPE", sd],258 ];259 c.ensure(16);260 c.y -= 6;261 const w = CW / items.length;262 items.forEach(([l, v], i) => {263 c.doc.font("JB-Reg").fontSize(5.5).fillColor(INK3).text(l, M + i * w, c.y, { width: w - 6, lineBreak: false });264 c.doc.font("JB-Bold").fontSize(7).fillColor(INK).text(short(v), M + i * w, c.y + 7.5, { width: w - 6, lineBreak: false });265 });266 c.y += 24;267}268269const MULTI_PDF = [270 { color: GREEN, dash: null as number[] | null, width: 1.8 },271 { color: INK, dash: null, width: 1.2 },272 { color: GREEN_DEEP, dash: [5, 2.5], width: 1.5 },273 { color: INK3, dash: [1.5, 2.5], width: 1.5 },274];275276function multiLinePdf(c: Cursor, ms: { title: string; unit?: string; series: { label: string; points: { t: string; v: number }[] }[] }, h = 130) {277 const series = (ms.series ?? []).filter((s) => (s.points ?? []).length > 1).slice(0, 4);278 if (!series.length) return;279 const a = chartFrame(c, ms.title + (ms.unit ? ` (${ms.unit})` : ""), h + 14);280 const { doc } = c;281 // légende (motif + libellé — jamais la couleur seule)282 let lx = a.x;283 series.forEach((s, i) => {284 const st = MULTI_PDF[i];285 doc.lineWidth(2).strokeColor(st.color);286 if (st.dash) doc.dash(st.dash[0], { space: st.dash[1] }); else doc.undash();287 doc.moveTo(lx, a.y + 2).lineTo(lx + 16, a.y + 2).stroke();288 doc.undash();289 doc.font("JB-Bold").fontSize(6).fillColor(INK).text(s.label.toUpperCase(), lx + 20, a.y - 1, { lineBreak: false });290 lx += 26 + doc.widthOfString(s.label.toUpperCase()) + 14;291 });292 const area = { ...a, y: a.y + 12, h: a.h - 12 };293 const all = series.flatMap((s) => s.points.map((p) => p.v));294 const vmax = Math.max(...all, 1);295 const vmin = Math.min(0, ...all);296 axes(doc, area, vmin, vmax, series[0].points.map((p) => p.t));297 series.forEach((s, i) => {298 const st = MULTI_PDF[i];299 const X = (j: number) => area.x + (area.w * j) / (s.points.length - 1);300 const Y = (v: number) => area.y + area.h * (1 - (v - vmin) / (vmax - vmin || 1));301 doc.moveTo(X(0), Y(s.points[0].v));302 s.points.forEach((p, j) => doc.lineTo(X(j), Y(p.v)));303 doc.lineWidth(st.width).strokeColor(st.color);304 if (st.dash) doc.dash(st.dash[0], { space: st.dash[1] }); else doc.undash();305 doc.stroke();306 doc.undash();307 });308}309310const SHADES = [1, 0.72, 0.5, 0.34, 0.22, 0.13];311312function stackedPdf(c: Cursor, st: { title: string; unit?: string; keys: string[]; points: { t: string; values: number[] }[] }, h = 130) {313 const keys = (st.keys ?? []).slice(0, 6);314 const pts = st.points ?? [];315 if (!keys.length || !pts.length) return;316 const a = chartFrame(c, st.title, h + 14);317 const { doc } = c;318 let lx = a.x;319 keys.forEach((k, i) => {320 doc.fillOpacity(SHADES[i]).rect(lx, a.y - 1, 8, 8).fill(GREEN).fillOpacity(1);321 doc.rect(lx, a.y - 1, 8, 8).lineWidth(0.5).stroke(INK);322 doc.font("JB-Bold").fontSize(6).fillColor(INK).text(k.toUpperCase(), lx + 12, a.y, { lineBreak: false });323 lx += 18 + doc.widthOfString(k.toUpperCase()) + 12;324 });325 const area = { ...a, y: a.y + 12, h: a.h - 12 };326 const totals = pts.map((p) => p.values.slice(0, keys.length).reduce((s, v) => s + (v || 0), 0));327 const vmax = Math.max(...totals, 1);328 axes(doc, area, 0, vmax, pts.map((p) => p.t));329 const bw = Math.max(1, area.w / pts.length - 1);330 pts.forEach((p, i) => {331 const x = area.x + (area.w * i) / pts.length;332 let yAcc = area.y + area.h;333 keys.forEach((k, j) => {334 const v = p.values[j] || 0;335 const bh = area.h * (v / vmax);336 yAcc -= bh;337 if (bh > 0.3) {338 doc.fillOpacity(SHADES[j]).rect(x, yAcc, bw, bh).fill(GREEN).fillOpacity(1);339 }340 });341 });342}343344/** Anneau vectoriel (arcs tracés en petits segments) + légende. */345function donutPdf(c: Cursor, title: string, items: { label: string; value: number }[]) {346 const rows = (items ?? []).filter((i) => i.value > 0).slice(0, 8);347 const total = rows.reduce((s, r) => s + r.value, 0);348 if (!total) return;349 const h = 150;350 c.ensure(h + 40);351 const { doc } = c;352 card(doc, M, c.y, CW, h + 26);353 doc.font("SG-Bold").fontSize(9.5).fillColor(INK).text(title, M + 14, c.y + 10, { lineBreak: false });354 const cx = M + 90, cy = c.y + 30 + (h - 20) / 2, R = 52;355 let angle = -Math.PI / 2;356 rows.forEach((r, i) => {357 const sweep = (2 * Math.PI * r.value) / total;358 const steps = Math.max(2, Math.ceil(sweep / 0.06));359 doc.lineWidth(24).strokeColor(GREEN).strokeOpacity(SHADES[i % SHADES.length] * 0.9 + 0.1);360 doc.moveTo(cx + R * Math.cos(angle), cy + R * Math.sin(angle));361 for (let s = 1; s <= steps; s++) {362 const t = angle + (sweep * s) / steps;363 doc.lineTo(cx + R * Math.cos(t), cy + R * Math.sin(t));364 }365 doc.stroke().strokeOpacity(1);366 angle += sweep;367 });368 doc.circle(cx, cy, R + 12).lineWidth(0.7).strokeOpacity(0.5).stroke(INK).strokeOpacity(1);369 // légende370 const lx = M + 190;371 let ly = c.y + 34;372 rows.forEach((r, i) => {373 doc.fillOpacity(SHADES[i % SHADES.length]).rect(lx, ly, 8, 8).fill(GREEN).fillOpacity(1);374 doc.rect(lx, ly, 8, 8).lineWidth(0.5).stroke(INK);375 doc.font("SG-Bold").fontSize(7.5).fillColor(INK).text(r.label, lx + 14, ly, { width: 200, height: 9, ellipsis: true, lineBreak: false });376 doc.font("JB-Bold").fontSize(7).fillColor(INK2)377 .text(`${((100 * r.value) / total).toFixed(1).replace(".", ",")} % · ${short(r.value)}$`, lx + 220, ly + 0.5, { width: CW - 220 - (lx - M) - 14, align: "right", lineBreak: false });378 ly += Math.min(17, (h - 10) / rows.length);379 });380 c.y += h + 26 + 12;381}382383/** Barres horizontales (répartitions / géo). */384function hbarsPdf(c: Cursor, title: string, items: { label: string; value: number }[], fmt: (v: number) => string = compact) {385 const rows = (items ?? []).slice(0, 15);386 if (!rows.length) return;387 const boxH = rows.length * 17 + 24;388 c.ensure(boxH + 30);389 const { doc } = c;390 c.section(title, false);391 card(doc, M, c.y, CW, boxH);392 const max = Math.max(...rows.map((r) => r.value), 1);393 rows.forEach((r, i) => {394 hbarRow(doc, M + 14, c.y + 12 + i * 17, CW - 28, r.label, r.value / max, fmt(r.value), null, i === 0);395 });396 c.y += boxH + 14;397}398399/** Jauges demi-arc (accent), 4 par rangée. */400function gaugesPdf(c: Cursor, gauges: Dash["gauges"]) {401 if (!gauges?.length) return;402 const gw = (CW - 3 * 10) / 4;403 const rowsN = Math.ceil(gauges.length / 4);404 c.ensure(rowsN * 86 + 10);405 const { doc } = c;406 gauges.forEach((g, i) => {407 const x = M + (i % 4) * (gw + 10);408 const y = c.y + Math.floor(i / 4) * 86;409 card(doc, x, y, gw, 78);410 const cx = x + gw / 2, cy = y + 44, R = 26;411 const arc = (from: number, to: number, color: string, lw: number) => {412 const steps = Math.max(2, Math.ceil(((to - from) / Math.PI) * 24));413 doc.lineWidth(lw).strokeColor(color);414 doc.moveTo(cx + R * Math.cos(from), cy + R * Math.sin(from));415 for (let s = 1; s <= steps; s++) {416 const t = from + ((to - from) * s) / steps;417 doc.lineTo(cx + R * Math.cos(t), cy + R * Math.sin(t));418 }419 doc.stroke();420 };421 arc(Math.PI, 2 * Math.PI, "#e3e1d9", 8);422 const frac = Math.max(0, Math.min(1, g.max ? g.value / g.max : 0));423 if (frac > 0.01) arc(Math.PI, Math.PI + Math.PI * frac, GREEN, 8);424 doc.font("SG-Bold").fontSize(13).fillColor(INK)425 .text(`${g.value.toLocaleString("fr-CA", { maximumFractionDigits: 1 })}${g.unit ?? ""}`, x, cy - 12, { width: gw, align: "center", lineBreak: false });426 doc.font("JB-Bold").fontSize(5.2).fillColor(INK3)427 .text(g.label.toUpperCase(), x + 8, y + 58, { width: gw - 16, align: "center", characterSpacing: 0.3, height: 16 });428 });429 c.y += rowsN * 86 + 8;430}431432/** Grille de cartes KPI (valeur, libellé, delta coloré à 1 décimale). */433function kpiGridPdf(c: Cursor, kpis: Dash["kpis"]) {434 const kw = (CW - 3 * 10) / 4;435 const rowsN = Math.ceil(kpis.length / 4);436 c.ensure(rowsN * 64 + 6);437 const { doc } = c;438 kpis.forEach((k, i) => {439 const x = M + (i % 4) * (kw + 10);440 const y = c.y + Math.floor(i / 4) * 64;441 card(doc, x, y, kw, 56);442 const val = typeof k.value === "number" ? num(k.value) : k.value;443 doc.font("SG-Bold").fontSize(12).fillColor(INK)444 .text(val + (k.unit && typeof k.value === "number" ? ` ${k.unit}` : ""), x + 9, y + 9, { width: kw - 18, height: 15, ellipsis: true, lineBreak: false });445 if (k.delta_pct !== undefined && k.delta_pct !== null) {446 const up = (k.direction ?? (k.delta_pct >= 0 ? "up" : "down")) === "up";447 doc.font("JB-Bold").fontSize(6.5).fillColor(up ? "#1c5c41" : "#b3423a")448 .text(`${up ? "▲" : "▼"} ${k.delta_pct >= 0 ? "+" : ""}${k.delta_pct.toLocaleString("fr-CA", { maximumFractionDigits: 1 })} %`, x + 9, y + 26, { lineBreak: false });449 }450 doc.font("JB-Bold").fontSize(5).fillColor(INK3)451 .text(k.label.toUpperCase(), x + 9, y + 37, { width: kw - 18, characterSpacing: 0.3, height: 15 });452 });453 c.y += rowsN * 64 + 10;454}455456/** Calendrier d'activité (grille par semaine, opacité ∝ valeur). */457function heatmapPdf(c: Cursor, hm: { title: string; cells: { date: string; value: number }[] }) {458 if (!hm?.cells?.length) return;459 const byDate = new Map(hm.cells.map((x) => [x.date, x.value]));460 const dates = hm.cells.map((x) => x.date).sort();461 const end = new Date(dates[dates.length - 1] + "T12:00:00");462 const max = Math.max(...hm.cells.map((x) => x.value), 1);463 const weeks = 26;464 const cell = (CW - 28) / weeks;465 const gridH = 7 * cell;466 c.ensure(gridH + 60);467 const { doc } = c;468 c.section(hm.title, false);469 card(doc, M, c.y, CW, gridH + 24);470 const cur = new Date(end);471 cur.setDate(cur.getDate() - (weeks * 7 - 1));472 for (let w = 0; w < weeks; w++) {473 for (let d = 0; d < 7; d++) {474 const iso = cur.toISOString().slice(0, 10);475 const v = byDate.get(iso) ?? 0;476 const x = M + 14 + w * cell;477 const y = c.y + 12 + d * cell;478 if (v > 0) {479 doc.fillOpacity(0.2 + 0.8 * (v / max)).rect(x, y, cell - 1.6, cell - 1.6).fill(GREEN).fillOpacity(1);480 } else {481 doc.rect(x, y, cell - 1.6, cell - 1.6).fill("#eceae2");482 }483 cur.setDate(cur.getDate() + 1);484 }485 }486 c.y += gridH + 24 + 14;487}488489/** Tableau zébré paginé proprement (jamais de ligne coupée). */490function tablePdf(c: Cursor, t: { title: string; columns: string[]; rows: (string | number | null)[][] }, maxRows: number, remember = true) {491 const rows = t.rows.slice(0, maxRows);492 if (!rows.length) return;493 const { doc } = c;494 c.ensure(90);495 if (remember) c.sections.push({ label: t.title, page: c.page() });496 kicker(doc, t.title, M, c.y);497 c.y += 18;498 // largeur des colonnes : numériques 88 pt à droite, texte se partage le reste499 const isNum = t.columns.map((_, ci) => rows.every((r) => r[ci] === null || typeof r[ci] === "number"));500 const numW = 88;501 const rankW = 30;502 const widths: number[] = t.columns.map((col, ci) => {503 if (ci === 0 && (col === "Rang" || col === "#")) return rankW;504 return isNum[ci] ? numW : 0;505 });506 const fixed = widths.reduce((a, b) => a + b, 0);507 const flexN = widths.filter((w) => w === 0).length || 1;508 const flexW = (CW - fixed) / flexN;509 const xs: number[] = [];510 let xAcc = M;511 widths.forEach((w) => { xs.push(xAcc); xAcc += w || flexW; });512 const header = () => {513 doc.rect(M, c.y, CW, 15).fill(INK);514 doc.font("JB-Bold").fontSize(5.6).fillColor(WHITE);515 t.columns.forEach((col, ci) => {516 const w = (widths[ci] || flexW) - 10;517 doc.text(col.toUpperCase(), xs[ci] + 5, c.y + 5, { width: w, align: isNum[ci] && ci > 0 ? "right" : "left", lineBreak: false });518 });519 c.y += 15;520 };521 header();522 const fmtCell = (v: string | number | null, ci: number) => {523 if (v === null || v === undefined) return "—";524 if (typeof v !== "number") return String(v);525 if (/\$/.test(t.columns[ci]) && Math.abs(v) >= 1e6) return compact(v);526 return num(v);527 };528 rows.forEach((r, ri) => {529 if (c.y + 13 > BOT) {530 doc.rect(M, c.y, CW, 0.9).fill(INK);531 doc.addPage({ size: "A4", margin: 0 });532 chrome(doc);533 c.y = TOP;534 kicker(doc, `${t.title} (suite)`, M, c.y);535 c.y += 18;536 header();537 }538 if (ri % 2 === 0) doc.rect(M, c.y, CW, 13).fill(SURFACE2);539 t.columns.forEach((col, ci) => {540 const w = (widths[ci] || flexW) - 10;541 const right = isNum[ci] && ci > 0;542 doc.font(ci === 1 && !isNum[1] ? "SG-Bold" : "JB-Reg").fontSize(6.6).fillColor(INK)543 .text(fmtCell(r[ci], ci), xs[ci] + 5, c.y + 3.6, { width: w, align: right ? "right" : "left", height: 9, ellipsis: true, lineBreak: false });544 });545 c.y += 13;546 });547 doc.rect(M, c.y, CW, 0.9).fill(INK);548 c.y += 14;549}550551/** Records & faits marquants — cartes compactes 2 par rangée. */552function recordsPdf(c: Cursor, records: KaRecord[], remember = true) {553 if (!records?.length) return;554 c.section("Records & faits marquants", remember);555 const { doc } = c;556 const rw = (CW - 10) / 2;557 records.forEach((r, i) => {558 if (i % 2 === 0) c.ensure(52);559 const x = M + (i % 2) * (rw + 10);560 const y = c.y;561 card(doc, x, y, rw, 44, SURFACE2);562 doc.font("SG-Bold").fontSize(9).fillColor(INK)563 .text(r.value, x + 10, y + 8, { width: rw - 20, height: 11, ellipsis: true, lineBreak: false });564 doc.font("JB-Bold").fontSize(5.2).fillColor(INK3)565 .text(r.label.toUpperCase() + (r.date ? ` · ${r.date}` : ""), x + 10, y + 24, { width: rw - 20, characterSpacing: 0.3, height: 14 });566 if (i % 2 === 1 || i === records.length - 1) c.y += 52;567 });568 c.y += 6;569}570571/* ------------------------------- COUVERTURE ------------------------------- */572function cover(doc: Doc, s: ProvStats, generated: string, modeLabel: string) {573 doc.rect(0, 0, W, H).fill(PAPER);574 doc.lineWidth(2).rect(28, 28, W - 56, H - 56).stroke(INK);575 kicker(doc, "Vrai-Prix · Rapport statistique", 64, 100, 10.5);576 wordmark(doc, 64, 172, 46);577 doc.font("Inter").fontSize(13).fillColor(INK2).text(578 "La valeur réelle de chaque propriété — rapport statistique provincial du parc immobilier québécois.",579 64, 256, { width: W - 168, lineGap: 3 });580 const rows: [string, string][] = [581 ["Type de rapport", modeLabel],582 ["Période couverte", "Instantané du rôle d'évaluation 2026 (millésime)"],583 ["Généré le", `${generated} (heure de l'Est)`],584 ["Plateforme", "www.vrai-prix.com"],585 ["Données", `${num(s.unites)} propriétés · ${num(s.municipalites)} municipalités`],586 ];587 doc.rect(64, 318, 34, 3).fill(LIME);588 let y = 336;589 rows.forEach(([k, v]) => {590 doc.font("JB-Reg").fontSize(8).fillColor(INK3)591 .text(k.toUpperCase(), 64, y + 2.5, { width: 150, characterSpacing: 0.6, lineBreak: false });592 doc.font("SG-Bold").fontSize(11.5).fillColor(INK)593 .text(v, 214, y, { width: W - 214 - 64, height: 14, ellipsis: true, lineBreak: false });594 y += 24;595 });596 doc.rect(28, H - 28 - 64, W - 56, 64).fill(INK);597 const by = H - 28 - 64 + 24;598 doc.font("SG-Bold").fontSize(15).fillColor(WHITE).text("Vrai-Prix", 64, by, { lineBreak: false });599 doc.font("JB-Bold").fontSize(9.5).fillColor(LIME)600 .text("www.vrai-prix.com", W - 64 - 180, by + 4, { width: 180, align: "right", characterSpacing: 0.8 });601}602603/* --------------------- VUE D'ENSEMBLE (le chiffre + comparaisons) --------------------- */604function overview(c: Cursor, s: ProvStats) {605 const { doc } = c;606 c.section("Valeur totale du parc immobilier québécois");607 card(doc, M, c.y, CW, 96, INK);608 doc.font("SG-Bold").fontSize(34).fillColor(LIME).text(money(s.valeur_totale_2026), M + 20, c.y + 18);609 doc.font("JB-Reg").fontSize(7.5).fillColor("rgba(255,81,72,0.75)")610 .text(`≈ ${compact(s.valeur_totale_2026).toUpperCase()} · ${num(s.unites)} PROPRIÉTÉS · ${num(s.municipalites)} MUNICIPALITÉS`,611 M + 20, c.y + 62, { characterSpacing: 0.8 });612 c.y += 112;613 const comps: [string, string][] = [614 ["Par Québécois·e", money(s.valeur_totale_2026 / POP_QC)],615 ["Budgets annuels du Québec", `× ${(s.valeur_totale_2026 / BUDGET_QC).toLocaleString("fr-CA", { maximumFractionDigits: 1 })}`],616 ["Fois le PIB du Québec", `× ${(s.valeur_totale_2026 / PIB_QC).toLocaleString("fr-CA", { maximumFractionDigits: 1 })}`],617 ["Croissance 2021→2026*", `+${s.croissance_2021_2026_pct.toLocaleString("fr-CA")} %`],618 ];619 const tw2 = (CW - 3 * 10) / 4;620 comps.forEach(([k, v], i) => {621 const tx = M + (i % 4) * (tw2 + 10);622 card(doc, tx, c.y, tw2, 48);623 doc.font("SG-Bold").fontSize(12.5).fillColor(INK).text(v, tx + 10, c.y + 10, { width: tw2 - 20, height: 16, ellipsis: true, lineBreak: false });624 doc.font("JB-Bold").fontSize(5.5).fillColor(INK3).text(k.toUpperCase(), tx + 10, c.y + 32, { width: tw2 - 20, characterSpacing: 0.5, height: 12 });625 });626 c.y += 56 + 6;627 doc.font("JB-Reg").fontSize(6).fillColor(INK3)628 .text("* À PÉRIMÈTRE CONSTANT (UNITÉS PRÉSENTES AUX DEUX MILLÉSIMES)", M, c.y, { characterSpacing: 0.5 });629 c.y += 18;630}631632/* ------------------------------ PAGE DE FIN ------------------------------ */633function finalPage(doc: Doc) {634 let y = 60;635 kicker(doc, "Vrai-Prix · Contact", M, y);636 y += 20;637 doc.font("SG-Bold").fontSize(21).fillColor(INK).text("Contact", M, y);638 y += 40;639 doc.font("SG-Bold").fontSize(12.5).fillColor(INK).text(CONTACT_EMAIL, M, y, { lineBreak: false });640 doc.font("JB-Reg").fontSize(8).fillColor(INK3).text("QUESTIONS, CORRECTIONS, VIE PRIVÉE, MÉDIAS", M, y + 17, { characterSpacing: 0.5, lineBreak: false });641 y += 48;642 doc.font("JB-Bold").fontSize(9.5).fillColor(GREEN)643 .text("www.vrai-prix.com", M, y, { lineBreak: false });644 y += 26;645 doc.rect(M, y, 44, 3).fill(LIME);646 y += 14;647 doc.font("Inter").fontSize(10).fillColor(INK2)648 .text("Données lues à la source (rôles d'évaluation du Québec, ventes publiées), rien d'inventé, tout est traçable.", M, y, { width: 420, lineGap: 3 });649 y = doc.y + 16;650 doc.font("Inter").fontSize(8).fillColor(INK3).text(651 "Mentions : rapport généré automatiquement à partir des données réelles de la plateforme au moment " +652 "indiqué en couverture. Les valeurs sont des estimations statistiques (modèle hédonique, rôle " +653 "d'évaluation 2026) et ne remplacent pas une évaluation professionnelle. Conditions d'utilisation, " +654 "politique de confidentialité et protection des renseignements personnels (Loi 25) : " +655 "www.vrai-prix.com/conditions · /confidentialite.",656 M, y, { width: 420, lineGap: 2.5 });657 wordmark(doc, M, H - 92, 15);658}659660/* --------------------------------- RAPPORT -------------------------------- */661export async function buildStatsReport(mode: ReportMode = "complet"): Promise<Buffer> {662 const s = stats as ProvStats;663 const dash = getDashboard();664 const generated = new Date().toLocaleString("fr-CA", {665 timeZone: "America/Toronto", year: "numeric", month: "2-digit", day: "2-digit",666 hour: "2-digit", minute: "2-digit", hour12: false,667 }).replace(",", " ·");668669 const doc = new PDFDocument({670 size: "A4", margin: 0, bufferPages: true,671 info: { Title: `Vrai-Prix — Rapport statistique (${MODE_FR[mode]})`, Author: "Vrai-Prix — www.vrai-prix.com" },672 });673 doc.registerFont("SG-Bold", F("SpaceGrotesk-Bold.ttf"));674 doc.registerFont("JB-Reg", F("JetBrainsMono-Regular.ttf"));675 doc.registerFont("JB-Bold", F("JetBrainsMono-Bold.ttf"));676 doc.registerFont("Inter", F("Inter-Regular.ttf"));677678 const chunks: Buffer[] = [];679 doc.on("data", (b: Buffer) => chunks.push(b));680 const done = new Promise<Buffer>((res) => doc.on("end", () => res(Buffer.concat(chunks))));681682 /* ------ PAGE 1 : COUVERTURE ------ */683 cover(doc, s, generated, MODE_FR[mode]);684685 const withToc = mode === "complet" || mode === "donnees";686 if (withToc) {687 doc.addPage({ size: "A4", margin: 0 }); // page 2 réservée au sommaire (remplie en post-passe)688 }689690 doc.addPage({ size: "A4", margin: 0 });691 chrome(doc);692 const c = new Cursor(doc);693694 if (mode === "complet") {695 c.sections.push({ label: "Vue d'ensemble provinciale", page: c.page() });696 overview(c, s);697 c.section("Indicateurs clés");698 kpiGridPdf(c, dash.kpis);699 c.section("Couverture & complétude du rôle");700 gaugesPdf(c, dash.gauges);701 c.section("Évolution — millésimes & corpus de ventes");702 dash.series.forEach((se) => { linePdf(c, se as KaSerie); statLine(c, se as KaSerie); });703 c.section("Marché — indices & prix au m²");704 dash.multiseries.forEach((ms) => multiLinePdf(c, ms));705 dash.stacked.forEach((st) => stackedPdf(c, st));706 c.section("Répartitions");707 dash.breakdowns.forEach((b) => {708 if (b.kind === "donut") donutPdf(c, b.title, b.items);709 else hbarsPdf(c, b.title, b.items, b.id === "types_n" ? num : compact);710 });711 dash.distributions.forEach((d) => linePdf(c, { id: d.id, title: d.title, unit: d.unit, kind: "bar", points: d.bins.map((b) => ({ t: b.label, v: b.value })) }));712 hbarsPdf(c, dash.geo.title, dash.geo.items);713 heatmapPdf(c, dash.heatmap);714 dash.tables.forEach((t) => tablePdf(c, t, 200));715 recordsPdf(c, dash.records);716 } else if (mode === "synthese") {717 overview(c, s);718 c.section("Indicateurs clés");719 kpiGridPdf(c, dash.kpis);720 c.section("Couverture & complétude du rôle");721 gaugesPdf(c, dash.gauges);722 recordsPdf(c, dash.records);723 } else if (mode === "tendances") {724 c.section("Indicateurs clés");725 kpiGridPdf(c, dash.kpis);726 c.section("Évolution — millésimes & corpus de ventes");727 dash.series.forEach((se) => { linePdf(c, se as KaSerie); statLine(c, se as KaSerie); });728 c.section("Marché — indices & prix au m²");729 dash.multiseries.forEach((ms) => multiLinePdf(c, ms));730 dash.stacked.forEach((st) => stackedPdf(c, st));731 recordsPdf(c, dash.records);732 } else if (mode === "repartitions") {733 c.section("Répartitions");734 dash.breakdowns.forEach((b) => {735 if (b.kind === "donut") donutPdf(c, b.title, b.items);736 else hbarsPdf(c, b.title, b.items, b.id === "types_n" ? num : compact);737 });738 c.section("Distributions");739 dash.distributions.forEach((d) => linePdf(c, { id: d.id, title: d.title, unit: d.unit, kind: "bar", points: d.bins.map((b) => ({ t: b.label, v: b.value })) }));740 c.section("Répartition géographique");741 hbarsPdf(c, dash.geo.title, dash.geo.items);742 heatmapPdf(c, dash.heatmap);743 } else {744 // donnees : tous les tableaux en version longue (≤ 400 lignes)745 dash.tables.forEach((t) => tablePdf(c, t, 400));746 }747748 /* ------ DERNIÈRE PAGE : COORDONNÉES & MENTIONS ------ */749 doc.addPage({ size: "A4", margin: 0 });750 chrome(doc);751 finalPage(doc);752753 /* ------ POST-PASSE : sommaire (page 2) + numéros de page ------ */754 const range = doc.bufferedPageRange();755 const total = range.count;756 if (withToc) {757 doc.switchToPage(1);758 chrome(doc);759 let y = TOP + 4;760 kicker(doc, MODE_FR[mode], M, y);761 y += 20;762 doc.font("SG-Bold").fontSize(21).fillColor(INK).text("Sommaire", M, y);763 y += 40;764 const entries: [string, string][] = [765 ...c.sections.map((sec) => [sec.label, String(sec.page)] as [string, string]),766 ["Contact et mentions", String(total)],767 ];768 entries.slice(0, 16).forEach(([label, pg]) => {769 doc.rect(M, y + 22, CW, 0.7).fill("#e3e1d9");770 doc.font("SG-Bold").fontSize(11).fillColor(INK).text(label, M, y, { width: CW - 70, height: 26, ellipsis: true });771 doc.font("JB-Bold").fontSize(10.5).fillColor(GREEN).text(pg, W - M - 60, y + 1, { width: 60, align: "right" });772 y += 34;773 });774 y += 8;775 doc.font("JB-Reg").fontSize(7).fillColor(INK3).text(776 `PÉRIODE : ${PERIOD_LABEL.toUpperCase()} · STATISTIQUES GÉNÉRÉES LE ${s.generated} · SOURCE : RÔLE D'ÉVALUATION FONCIÈRE + CORPUS DE VENTES + MODÈLE HÉDONIQUE VRAI-PRIX`,777 M, y, { characterSpacing: 0.4, width: CW });778 }779 for (let i = 1; i < total; i++) {780 doc.switchToPage(i);781 doc.font("JB-Bold").fontSize(7.5).fillColor(INK)782 .text(`p. ${i + 1}/${total}`, W - M - 60, H - 34.5, { width: 60, align: "right", lineBreak: false });783 }784785 doc.end();786 return done;787}788789/** Nom de fichier normalisé — pas de suffixe pour `complet`. */790export function reportFilename(mode: ReportMode | "personnalise" = "complet"): string {791 const today = new Date().toLocaleDateString("fr-CA", { timeZone: "America/Toronto" });792 const suffix = mode === "complet" ? "" : `_${mode}`;793 return `vrai-prix_stats_instantane${suffix}_${today}.pdf`;794}795796/* ===================== v3 : rapports personnalisés (SPEC §3bis) =====================797 Catalogue de blocs dérivé du dashboard + génération d'un PDF composé bloc798 par bloc (rendu au choix), même gabarit. */799export type CatalogBlock = {800 key: string; section: string; title: string;801 renders: string[]; default_render: string; count?: number;802};803export type CustomBlock = { key: string; render?: string };804export type CustomSpec = { title?: string; blocks?: CustomBlock[] };805806export function catalogFromDashboard(dash: Dash = getDashboard()): CatalogBlock[] {807 const out: CatalogBlock[] = [];808 const add = (key: string, title: string, renders: string[], def?: string, count?: number) =>809 out.push({ key, section: key.split(":")[0], title, renders,810 default_render: def ?? renders[0],811 ...(count !== undefined ? { count } : {}) });812 if (dash.kpis?.length) add("kpis", "Indicateurs clés (KPI)", ["cards", "table"], undefined, dash.kpis.length);813 if (dash.gauges?.length) add("gauges", "Taux & couvertures (jauges)", ["gauges", "table"], undefined, dash.gauges.length);814 for (const s of dash.series ?? []) {815 if ((s.points?.length ?? 0) < 2) continue;816 const kind = (s as KaSerie).kind ?? "line";817 add(`series:${s.id}`, s.title, ["line", "area", "bar", "table"],818 ["line", "area", "bar"].includes(kind) ? kind : "line", s.points.length);819 }820 for (const ms of dash.multiseries ?? []) {821 if (!ms.series?.length) continue;822 add(`multiseries:${ms.id}`, ms.title, ["lines", "table"], undefined, ms.series.length);823 }824 for (const st of dash.stacked ?? []) {825 if (!st.points?.length) continue;826 add(`stacked:${st.id}`, st.title, ["stacked", "table"], undefined, st.keys?.length);827 }828 for (const b of dash.breakdowns ?? []) {829 if (!b.items?.length) continue;830 add(`breakdowns:${b.id}`, b.title, ["donut", "bars", "table"],831 b.kind === "donut" ? "donut" : "bars", b.items.length);832 }833 for (const d of dash.distributions ?? []) {834 if (!d.bins?.length) continue;835 add(`distributions:${d.id}`, d.title, ["histogram", "table"], undefined, d.bins.length);836 }837 if (dash.geo?.items?.length) add("geo", dash.geo.title ?? "Répartition géographique", ["bars", "table"], undefined, dash.geo.items.length);838 if (dash.heatmap?.cells?.length) add("heatmap", dash.heatmap.title ?? "Calendrier d'activité", ["heatmap", "table"]);839 for (const t of dash.tables ?? []) {840 if (!t.rows?.length) continue;841 add(`tables:${t.id}`, t.title, ["table"], undefined, t.rows.length);842 }843 if (dash.records?.length) add("records", "Records & faits marquants", ["cards", "table"], undefined, dash.records.length);844 return out;845}846847type AnyRow = (string | number | null)[];848const seriesAsTable = (s: KaSerie) => ({849 title: s.title,850 columns: ["Date", (s.unit ?? "Valeur")] as string[],851 rows: (s.points ?? []).map((p) => [p.t, p.v] as AnyRow),852});853854function renderCustomBlock(c: Cursor, dash: Dash, key: string, render: string, title: string) {855 const [section, id] = [key.split(":")[0], key.split(":").slice(1).join(":")];856 const mark = () => { c.ensure(160); c.sections.push({ label: title, page: c.page() }); };857 if (section === "kpis") {858 if (render === "table") {859 tablePdf(c, { title: "Indicateurs clés", columns: ["Indicateur", "Valeur", "Δ %"],860 rows: dash.kpis.map((k) => [k.label, typeof k.value === "number" ? num(k.value) + (k.unit ? ` ${k.unit}` : "") : String(k.value),861 k.delta_pct == null ? "" : `${k.delta_pct >= 0 ? "+" : ""}${k.delta_pct} %`] as AnyRow) }, 400);862 } else { c.section("Indicateurs clés"); kpiGridPdf(c, dash.kpis); }863 } else if (section === "gauges") {864 if (render === "table") {865 tablePdf(c, { title: "Taux & couvertures", columns: ["Mesure", "Valeur", "Max", "Part"],866 rows: dash.gauges.map((g) => [g.label, `${num(g.value)}${g.unit ? ` ${g.unit}` : ""}`, num(g.max),867 `${Math.round((100 * g.value) / (g.max || 1))} %`] as AnyRow) }, 400);868 } else { c.section("Taux & couvertures"); gaugesPdf(c, dash.gauges); }869 } else if (section === "records") {870 if (render === "table") {871 tablePdf(c, { title: "Records & faits marquants", columns: ["Fait marquant", "Valeur", "Date"],872 rows: dash.records.map((r) => [r.label, r.value, r.date ?? ""] as AnyRow) }, 400);873 } else recordsPdf(c, dash.records);874 } else if (section === "series") {875 const s = (dash.series ?? []).find((x) => String(x.id) === id) as KaSerie | undefined;876 if (!s) return;877 if (render === "table") tablePdf(c, seriesAsTable(s), 400);878 else {879 mark();880 linePdf(c, { ...s, kind: (["line", "area", "bar"].includes(render) ? render : s.kind) as KaSerie["kind"] });881 statLine(c, s);882 }883 } else if (section === "multiseries") {884 const ms = (dash.multiseries ?? []).find((x) => String(x.id) === id);885 if (!ms) return;886 if (render === "table") {887 const labels = ms.series.slice(0, 4).map((x) => x.label);888 const byT = new Map<string, Record<string, number>>();889 for (const se of ms.series.slice(0, 4))890 for (const p of se.points) {891 const m = byT.get(p.t) ?? {};892 m[se.label] = p.v; byT.set(p.t, m);893 }894 tablePdf(c, { title: ms.title, columns: ["Date", ...labels],895 rows: [...byT.keys()].sort().map((t) => [t, ...labels.map((l) => byT.get(t)?.[l] ?? "")] as AnyRow) }, 400);896 } else { mark(); multiLinePdf(c, ms); }897 } else if (section === "stacked") {898 const st = (dash.stacked ?? []).find((x) => String(x.id) === id);899 if (!st) return;900 if (render === "table") {901 const keys = (st.keys ?? []).slice(0, 6);902 tablePdf(c, { title: st.title, columns: ["Date", ...keys, "Total"],903 rows: st.points.map((p) => {904 const vs = keys.map((_, j) => p.values[j] ?? 0);905 return [p.t, ...vs, vs.reduce((a, b) => a + b, 0)] as AnyRow;906 }) }, 400);907 } else { mark(); stackedPdf(c, st); }908 } else if (section === "breakdowns") {909 const b = (dash.breakdowns ?? []).find((x) => String(x.id) === id);910 if (!b) return;911 if (render === "table") {912 tablePdf(c, { title: b.title, columns: ["Libellé", "Valeur"],913 rows: b.items.map((it) => [it.label, it.value] as AnyRow) }, 400);914 } else {915 mark();916 if (render === "donut") donutPdf(c, b.title, b.items);917 else hbarsPdf(c, b.title, b.items, b.id === "types_n" ? num : compact);918 }919 } else if (section === "distributions") {920 const d = (dash.distributions ?? []).find((x) => String(x.id) === id);921 if (!d) return;922 if (render === "table") {923 tablePdf(c, { title: d.title, columns: ["Tranche", "Valeur"],924 rows: d.bins.map((b) => [b.label, b.value] as AnyRow) }, 400);925 } else {926 mark();927 linePdf(c, { id: d.id, title: d.title, unit: d.unit, kind: "bar",928 points: d.bins.map((b) => ({ t: b.label, v: b.value })) });929 }930 } else if (section === "geo") {931 if (!dash.geo?.items?.length) return;932 if (render === "table") {933 tablePdf(c, { title: dash.geo.title, columns: ["Zone", "Valeur"],934 rows: dash.geo.items.map((it) => [it.label, it.value] as AnyRow) }, 400);935 } else { mark(); hbarsPdf(c, dash.geo.title, dash.geo.items); }936 } else if (section === "heatmap") {937 if (!dash.heatmap?.cells?.length) return;938 if (render === "table") {939 const cells = [...dash.heatmap.cells].sort((a, b) => b.value - a.value).slice(0, 40);940 tablePdf(c, { title: `${dash.heatmap.title} — jours les plus chargés`,941 columns: ["Date", "Valeur"], rows: cells.map((x) => [x.date, x.value] as AnyRow) }, 400);942 } else { mark(); heatmapPdf(c, dash.heatmap); }943 } else if (section === "tables") {944 const t = (dash.tables ?? []).find((x) => String(x.id) === id);945 if (t) tablePdf(c, t, 400);946 }947}948949/** PDF personnalisé — lève Error("aucun-bloc") si la composition est vide. */950export async function buildCustomReport(spec: CustomSpec): Promise<Buffer> {951 const s = stats as ProvStats;952 const dash = getDashboard();953 const cat = new Map(catalogFromDashboard(dash).map((b) => [b.key, b]));954 const blocks = (spec.blocks ?? [])955 .filter((b): b is CustomBlock => !!b && typeof b === "object" && cat.has(String(b.key)))956 .slice(0, 40);957 if (!blocks.length) throw new Error("aucun-bloc");958 const title = String(spec.title ?? "").slice(0, 80).trim();959 const label = title ? `Rapport personnalisé — ${title}` : "Rapport personnalisé";960961 const generated = new Date().toLocaleString("fr-CA", {962 timeZone: "America/Toronto", year: "numeric", month: "2-digit", day: "2-digit",963 hour: "2-digit", minute: "2-digit", hour12: false,964 }).replace(",", " ·");965 const doc = new PDFDocument({966 size: "A4", margin: 0, bufferPages: true,967 info: { Title: `Vrai-Prix — ${label}`, Author: "Vrai-Prix — www.vrai-prix.com" },968 });969 doc.registerFont("SG-Bold", F("SpaceGrotesk-Bold.ttf"));970 doc.registerFont("JB-Reg", F("JetBrainsMono-Regular.ttf"));971 doc.registerFont("JB-Bold", F("JetBrainsMono-Bold.ttf"));972 doc.registerFont("Inter", F("Inter-Regular.ttf"));973 const chunks: Buffer[] = [];974 doc.on("data", (b: Buffer) => chunks.push(b));975 const done = new Promise<Buffer>((res) => doc.on("end", () => res(Buffer.concat(chunks))));976977 cover(doc, s, generated, label);978 doc.addPage({ size: "A4", margin: 0 }); // page 2 : sommaire (post-passe)979 doc.addPage({ size: "A4", margin: 0 });980 chrome(doc);981 const c = new Cursor(doc);982 for (const blk of blocks) {983 const b = cat.get(String(blk.key))!;984 const render = b.renders.includes(String(blk.render ?? "")) ? String(blk.render) : b.default_render;985 renderCustomBlock(c, dash, b.key, render, b.title);986 }987 doc.addPage({ size: "A4", margin: 0 });988 chrome(doc);989 finalPage(doc);990991 const range = doc.bufferedPageRange();992 const total = range.count;993 doc.switchToPage(1);994 chrome(doc);995 let y = TOP + 4;996 kicker(doc, label, M, y);997 y += 20;998 doc.font("SG-Bold").fontSize(21).fillColor(INK).text("Sommaire", M, y);999 y += 40;1000 const entries: [string, string][] = [1001 ...c.sections.map((sec) => [sec.label, String(sec.page)] as [string, string]),1002 ["Contact et mentions", String(total)],1003 ];1004 entries.slice(0, 16).forEach(([lab, pg]) => {1005 doc.rect(M, y + 22, CW, 0.7).fill("#e3e1d9");1006 doc.font("SG-Bold").fontSize(11).fillColor(INK).text(lab, M, y, { width: CW - 70, height: 26, ellipsis: true });1007 doc.font("JB-Bold").fontSize(10.5).fillColor(GREEN).text(pg, W - M - 60, y + 1, { width: 60, align: "right" });1008 y += 34;1009 });1010 for (let i = 1; i < total; i++) {1011 doc.switchToPage(i);1012 doc.font("JB-Bold").fontSize(7.5).fillColor(INK)1013 .text(`p. ${i + 1}/${total}`, W - M - 60, H - 34.5, { width: 60, align: "right", lineBreak: false });1014 }1015 doc.end();1016 return done;1017}10181019/** Compat : buildRecords ré-exporté pour les consommateurs historiques. */1020export { buildRecords };1021