Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/report-portfolio.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-08-0912 * Last Modified : 2026-08-0913 *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 PDF de parc immobilier — couverture agrégée (tuiles, historique du parc,44 * répartitions, table des propriétés) puis une page condensée par propriété.45 * 100 % vectoriel, identité Vrai-Prix.46 */47import PDFDocument from "pdfkit";48import path from "path";49import type { PortfolioResult, UnitEstimate } from "./estimator";5051const INK = "#141814";52const INK3 = "#8b928c";53const PAPER = "#f5f3ee";54const SURFACE2 = "#faf9f5";55const GREEN = "#9e2a25";56const LIME = "#ff5148";57const LIME_SOFT = "#ffe3e0";58const AMBER_SOFT = "#fdf3e2";59const DANGER_SOFT = "#fbe9e7";60const LINE = "#dedcd4";6162const W = 612;63const H = 792;64const M = 44;6566const F = (f: string) => path.join(process.cwd(), "assets", "fonts", f);67const fmt = (v: number | null | undefined) =>68 v == null69 ? "—"70 : new Intl.NumberFormat("fr-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(v);71const CONF_BG: Record<string, string> = { A: LIME, B: LIME_SOFT, C: AMBER_SOFT, D: DANGER_SOFT };72const TYPE_FR: Record<string, string> = {73 unifamilial: "Unifamiliale", plex: "Plex", condo_ou_multi: "Condo/multi",74 chalet: "Chalet", maison_mobile: "Maison mobile", terrain: "Terrain", autre: "Autre",75};7677type Doc = InstanceType<typeof PDFDocument>;7879function logo(doc: Doc, x: number, y: number, scale = 1) {80 doc.save();81 doc.font("SG-Bold").fontSize(24 * scale);82 doc.fillColor(PAPER).text("Vrai", x, y, { lineBreak: false });83 const w = doc.widthOfString("Vrai");84 const bx = x + w + 4 * scale;85 doc.save();86 doc.rotate(-3, { origin: [bx, y + 12 * scale] });87 const bw = doc.widthOfString("Prix") + 12 * scale;88 doc.roundedRect(bx, y - 3 * scale, bw, 30 * scale, 5 * scale).fill(LIME);89 doc.fillColor(INK).text("Prix", bx + 6 * scale, y, { lineBreak: false });90 doc.restore();91 doc.restore();92}9394function kicker(doc: Doc, txt: string, x: number, y: number) {95 doc.rect(x, y + 3.5, 20, 2).fill(GREEN);96 doc.font("JB-Bold").fontSize(8).fillColor(GREEN)97 .text(txt.toUpperCase(), x + 26, y, { characterSpacing: 1.4, lineBreak: false });98}99100function pageFrame(doc: Doc, page: number, total: number, generated: string) {101 doc.rect(0, 0, W, H).fill(PAPER);102 doc.rect(M, H - 46, W - 2 * M, 1.2).fill(INK);103 doc.font("JB-Reg").fontSize(6.5).fillColor(INK3).text(104 "VRAI-PRIX.COM — RAPPORT DE PARC IMMOBILIER · ESTIMATION STATISTIQUE À TITRE INDICATIF · SIMON-PIERRE BOUCHER · CONTACT@SPBOUCHER.AI",105 M, H - 38, { width: W - 2 * M - 60, characterSpacing: 0.4, lineBreak: false });106 doc.font("JB-Bold").fontSize(7.5).fillColor(INK)107 .text(`${page} / ${total}`, W - M - 40, H - 39, { width: 40, align: "right" });108 doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)109 .text(generated, W - M - 160, H - 30, { width: 160, align: "right" });110}111112function card(doc: Doc, x: number, y: number, w: number, h: number, fill = "#ffffff") {113 doc.roundedRect(x + 3, y + 3, w, h, 8).fill("#e3e1d9");114 doc.roundedRect(x, y, w, h, 8).lineWidth(1.3).fillAndStroke(fill, INK);115}116117function tile(doc: Doc, x: number, y: number, w: number, h: number, k: string, v: string, hero = false) {118 card(doc, x, y, w, h, hero ? INK : "#ffffff");119 doc.font("SG-Bold").fontSize(16).fillColor(hero ? LIME : INK)120 .text(v, x + 12, y + 12, { width: w - 24, height: 22, ellipsis: true, lineBreak: false });121 doc.font("JB-Bold").fontSize(5.6).fillColor(hero ? "rgba(255,81,72,0.7)" : INK3)122 .text(k.toUpperCase(), x + 12, y + h - 16, { width: w - 24, characterSpacing: 0.7, lineBreak: false });123}124125function kvCell(doc: Doc, x: number, y: number, w: number, h: number, k: string, v: string) {126 doc.lineWidth(0.8);127 doc.roundedRect(x, y, w, h, 4).fillAndStroke(SURFACE2, LINE);128 doc.font("JB-Bold").fontSize(5.6).fillColor(INK3)129 .text(k.toUpperCase(), x + 6, y + 5.5, { width: w - 12, characterSpacing: 0.6, height: 8, ellipsis: true });130 doc.font("SG-Bold").fontSize(8.8).fillColor(INK)131 .text(v, x + 6, y + 15.5, { width: w - 12, height: h - 19, ellipsis: true });132 doc.lineWidth(1.3);133}134135function hbars(doc: Doc, x: number, y: number, w: number, rows: [string, number, string][], accentLast = true) {136 const max = Math.max(...rows.map((r) => r[1]), 1);137 rows.forEach(([label, value, txt], i) => {138 const ly = y + i * 19;139 doc.font("JB-Bold").fontSize(7).fillColor(INK).text(label, x, ly + 2, { lineBreak: false });140 const tx = x + 50;141 const tw = w - 50 - 86;142 doc.rect(tx, ly, tw, 11).fill(SURFACE2);143 doc.rect(tx, ly, Math.max(2, (value / max) * tw), 11)144 .fill(accentLast && i === rows.length - 1 ? INK : GREEN);145 doc.font("JB-Bold").fontSize(7).fillColor(INK)146 .text(txt, x + w - 82, ly + 2, { width: 82, align: "right" });147 });148}149150/** Page condensée d'une propriété du parc. */151function propertyPage(doc: Doc, item: UnitEstimate, idx: number, total: number, pageNo: number, pageTotal: number, generated: string) {152 const u = item.unit!;153 const s = u.specs;154 const r = item.result;155 doc.addPage({ size: "LETTER", margin: 0 });156 pageFrame(doc, pageNo, pageTotal, generated);157 doc.rect(0, 0, W, 8).fill(INK);158 doc.rect(0, 8, W, 2.5).fill(LIME);159160 let y = 34;161 // index de propriété162 doc.circle(M + 10, y + 12, 12).lineWidth(1.4).fillAndStroke(GREEN, INK);163 doc.font("JB-Bold").fontSize(10).fillColor(PAPER)164 .text(String(idx + 1), M - 2, y + 7.5, { width: 24, align: "center", lineBreak: false });165 doc.font("JB-Reg").fontSize(7).fillColor(INK3)166 .text(`PROPRIÉTÉ ${idx + 1} / ${total}`, M + 30, y + 2, { characterSpacing: 1 });167 doc.font("SG-Bold").fontSize(14).fillColor(INK)168 .text(`${(u.adresse ?? "").toUpperCase()}${s.apt ? " APP. " + s.apt : ""} · ${(u.municipalite ?? "").toUpperCase()}`,169 M + 30, y + 12, { width: W - 2 * M - 30 });170 y = Math.max(doc.y + 10, y + 44);171172 doc.font("SG-Bold").fontSize(34).fillColor(INK).text(fmt(r.estimate), M, y);173 y = doc.y + 6;174 doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("FOURCHETTE", M, y, { lineBreak: false });175 doc.font("SG-Bold").fontSize(11).fillColor(INK).text(`${fmt(r.low)} → ${fmt(r.high)}`, M, y + 10, { lineBreak: false });176 const confTxt = `CONFIANCE ${r.confidenceLevel} · ${r.confidencePct} %`;177 doc.font("JB-Bold").fontSize(7);178 const cw = doc.widthOfString(confTxt) + 16;179 doc.roundedRect(M + 220, y + 4, cw, 16, 4).lineWidth(1).fillAndStroke(CONF_BG[r.confidenceLevel], INK);180 doc.fillColor(INK).text(confTxt, M + 228, y + 8.5, { lineBreak: false });181 doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("RÔLE 2026", M + 380, y, { lineBreak: false });182 doc.font("SG-Bold").fontSize(11).fillColor(INK).text(fmt(u.valeurRole), M + 380, y + 10, { lineBreak: false });183 y += 34;184185 // fiche compacte186 const rows: [string, string][] = [187 ["Usage", s.cubfLibelle ?? "—"],188 ["Année constr.", u.anneeConstruction ? String(u.anneeConstruction) : "—"],189 ["Aire étages", u.aireEtagesM2 ? `${u.aireEtagesM2} m²` : "—"],190 ["Terrain", u.superficieTerrainM2 ? `${u.superficieTerrainM2} m²` : "—"],191 ["Frontage", s.frontTerrainM ? `${s.frontTerrainM} m` : "—"],192 ["Étages", s.nbEtages != null ? String(s.nbEtages) : "—"],193 ["Logements", u.nbLogements != null ? String(u.nbLogements) : "—"],194 ["Genre", s.genreConstruction ?? "—"],195 ["Lien phys.", s.lienPhysique ?? "—"],196 ["Val. terrain", fmt(s.valeurTerrain)],197 ["Val. bâtiment", fmt(s.valeurBatiment)],198 ["Matricule", s.matricule ?? "—"],199 ];200 kicker(doc, "Fiche du registre", M, y);201 y += 14;202 const cw2 = (W - 2 * M - 3 * 8) / 4;203 rows.forEach(([k, v], i) => {204 kvCell(doc, M + (i % 4) * (cw2 + 8), y + Math.floor(i / 4) * 36, cw2, 30, k, v);205 });206 y += 3 * 36 + 14;207208 // historique209 kicker(doc, "Valeur estimée 2021 → 2026", M, y);210 y += 16;211 card(doc, M, y, W - 2 * M, u.history.length * 19 + 20);212 hbars(doc, M + 14, y + 12, W - 2 * M - 28,213 u.history.map((h) => [String(h.year), h.value ?? 0, fmt(h.value)]));214 y += u.history.length * 19 + 34;215216 // top comparables217 kicker(doc, `Meilleurs comparables (${Math.min(5, r.comps.length)})`, M, y);218 y += 14;219 r.comps.slice(0, 5).forEach((c, i) => {220 const ly = y + i * 17;221 if (i % 2 === 0) doc.rect(M, ly - 2, W - 2 * M, 16).fill(SURFACE2);222 doc.font("SG-Bold").fontSize(7.5).fillColor(INK)223 .text(`${i + 1}. ${c.street ?? ""}, ${c.city ?? ""}`, M + 6, ly, { width: 300, height: 9, ellipsis: true, lineBreak: false });224 doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)225 .text(`${c.date} · ${c.distanceM < 1000 ? Math.round(c.distanceM) + " m" : (c.distanceM / 1000).toFixed(1) + " km"}`,226 M + 316, ly + 1, { lineBreak: false });227 doc.font("SG-Bold").fontSize(8).fillColor(INK)228 .text(fmt(Math.round(c.adjustedPrice)), W - M - 90, ly, { width: 84, align: "right", lineBreak: false });229 });230}231232export async function buildPortfolioReport(pf: PortfolioResult): Promise<Buffer> {233 const { items, aggregates: a } = pf;234 const generated = new Date().toISOString().slice(0, 16).replace("T", " ");235 const pageTotal = 1 + items.length;236237 const doc = new PDFDocument({ size: "LETTER", margin: 0, info: { Title: "Vrai-Prix — Rapport de parc immobilier" } });238 doc.registerFont("SG-Bold", F("SpaceGrotesk-Bold.ttf"));239 doc.registerFont("SG-Med", F("SpaceGrotesk-Medium.ttf"));240 doc.registerFont("JB-Reg", F("JetBrainsMono-Regular.ttf"));241 doc.registerFont("JB-Bold", F("JetBrainsMono-Bold.ttf"));242 doc.registerFont("Inter", F("Inter-Regular.ttf"));243244 const chunks: Buffer[] = [];245 doc.on("data", (c: Buffer) => chunks.push(c));246 const done = new Promise<Buffer>((res) => doc.on("end", () => res(Buffer.concat(chunks))));247248 /* ------------------------------ COUVERTURE ------------------------------ */249 pageFrame(doc, 1, pageTotal, generated);250 doc.rect(0, 0, W, 110).fill(INK);251 logo(doc, M, 32);252 doc.font("JB-Reg").fontSize(7).fillColor(LIME)253 .text("RAPPORT DE PARC IMMOBILIER · QUÉBEC", M, 70, { characterSpacing: 1.6, lineBreak: false });254 doc.font("JB-Reg").fontSize(7).fillColor("#9aa39c")255 .text(`${a.count} PROPRIÉTÉS`, W - M - 200, 38, { width: 200, align: "right" })256 .text(`GÉNÉRÉ LE ${generated}`, W - M - 200, 50, { width: 200, align: "right" });257 doc.rect(0, 110, W, 3).fill(LIME);258259 let y = 134;260 kicker(doc, "Valeur totale estimée du parc", M, y);261 y += 16;262 doc.font("SG-Bold").fontSize(44).fillColor(INK).text(fmt(a.totalEstimate), M, y);263 y = doc.y + 8;264 doc.font("JB-Bold").fontSize(6.5).fillColor(INK3).text("FOURCHETTE CUMULÉE", M, y, { lineBreak: false });265 doc.font("SG-Bold").fontSize(12).fillColor(INK).text(`${fmt(a.totalLow)} → ${fmt(a.totalHigh)}`, M, y + 10, { lineBreak: false });266 const confTxt = `CONFIANCE PONDÉRÉE ${a.confidenceLevel} · ${a.confidencePct} %`;267 doc.font("JB-Bold").fontSize(7.5);268 const cw = doc.widthOfString(confTxt) + 20;269 doc.roundedRect(M + 260, y + 2, cw, 18, 4).lineWidth(1).fillAndStroke(CONF_BG[a.confidenceLevel], INK);270 doc.fillColor(INK).text(confTxt, M + 270, y + 7.5, { lineBreak: false });271 y += 38;272273 // tuiles274 const tiles: [string, string, boolean][] = [275 ["Propriétés", String(a.count), true],276 ["Évaluation municipale", fmt(a.totalRole), false],277 ["Écart vs rôle", a.ecartRolePct != null ? `${a.ecartRolePct >= 0 ? "+" : ""}${a.ecartRolePct.toFixed(0)} %` : "—", false],278 ["Croissance 2021→2026", a.growthPct != null ? `${a.growthPct >= 0 ? "+" : ""}${a.growthPct.toFixed(0)} %` : "—", true],279 ["Aire habitable totale", `${a.totalFloorArea.toLocaleString("fr-CA")} m²`, false],280 ["Terrain total", `${a.totalLandArea.toLocaleString("fr-CA")} m²`, false],281 ["Logements", String(a.totalDwellings), false],282 ["Année moyenne", a.avgYearBuilt ? String(a.avgYearBuilt) : "—", false],283 ];284 const tw = (W - 2 * M - 3 * 10) / 4;285 tiles.forEach(([k, v, hero], i) => {286 tile(doc, M + (i % 4) * (tw + 10), y + Math.floor(i / 4) * 58, tw, 50, k, v, hero);287 });288 y += 2 * 58 + 12;289290 // historique du parc291 kicker(doc, "Valeur du parc par année (unités couvertes)", M, y);292 y += 14;293 card(doc, M, y, (W - 2 * M - 12) * 0.58, 6 * 19 + 20);294 hbars(doc, M + 12, y + 12, (W - 2 * M - 12) * 0.58 - 24,295 a.history.map((h) => [String(h.year), h.total, fmt(h.total)]));296297 // répartitions298 const rx = M + (W - 2 * M - 12) * 0.58 + 12;299 const rw = W - M - rx;300 card(doc, rx, y, rw, 6 * 19 + 20);301 doc.font("JB-Bold").fontSize(6.2).fillColor(INK3).text("PAR MUNICIPALITÉ", rx + 12, y + 10, { characterSpacing: 0.8 });302 a.municipalities.slice(0, 3).forEach((m, i) => {303 const ly = y + 22 + i * 15;304 doc.font("SG-Bold").fontSize(7.5).fillColor(INK).text(m.name, rx + 12, ly, { width: rw - 100, height: 9, ellipsis: true, lineBreak: false });305 doc.font("JB-Reg").fontSize(6.8).fillColor(INK3).text(`${m.count} · ${fmt(m.total)}`, rx + rw - 96, ly, { width: 86, align: "right", lineBreak: false });306 });307 doc.font("JB-Bold").fontSize(6.2).fillColor(INK3).text("PAR TYPE", rx + 12, y + 72, { characterSpacing: 0.8 });308 a.types.slice(0, 3).forEach((tp, i) => {309 const ly = y + 84 + i * 15;310 doc.font("SG-Bold").fontSize(7.5).fillColor(INK).text(TYPE_FR[tp.type] ?? tp.type, rx + 12, ly, { width: rw - 100, height: 9, ellipsis: true, lineBreak: false });311 doc.font("JB-Reg").fontSize(6.8).fillColor(INK3).text(`${tp.count} · ${fmt(tp.total)}`, rx + rw - 96, ly, { width: 86, align: "right", lineBreak: false });312 });313 y += 6 * 19 + 34;314315 // table des propriétés316 kicker(doc, "Sommaire des propriétés", M, y);317 y += 14;318 items.slice(0, 14).forEach((it, i) => {319 const u = it.unit!;320 const ly = y + i * 17;321 if (i % 2 === 0) doc.rect(M, ly - 2, W - 2 * M, 16).fill(SURFACE2);322 doc.circle(M + 8, ly + 5, 6).lineWidth(0.9).fillAndStroke(GREEN, INK);323 doc.font("JB-Bold").fontSize(6).fillColor(PAPER).text(String(i + 1), M + 2, ly + 2.5, { width: 12, align: "center", lineBreak: false });324 doc.font("SG-Bold").fontSize(7.5).fillColor(INK)325 .text(`${u.adresse ?? ""} · ${u.municipalite ?? ""}`, M + 20, ly, { width: 280, height: 9, ellipsis: true, lineBreak: false });326 doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)327 .text(`CONF. ${it.result.confidenceLevel}`, M + 310, ly + 1, { lineBreak: false });328 doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)329 .text(`RÔLE ${fmt(u.valeurRole)}`, M + 360, ly + 1, { width: 90, lineBreak: false });330 doc.font("SG-Bold").fontSize(8).fillColor(INK)331 .text(fmt(it.result.estimate), W - M - 80, ly, { width: 76, align: "right", lineBreak: false });332 });333 if (items.length > 14) {334 doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)335 .text(`+ ${items.length - 14} autres propriétés — voir pages suivantes`, M, y + 14 * 17 + 2);336 }337338 /* --------------------------- PAGES PROPRIÉTÉS --------------------------- */339 items.forEach((it, i) => propertyPage(doc, it, i, items.length, i + 2, pageTotal, generated));340341 doc.end();342 return done;343}344