Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/report.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 Vrai-Prix — 100 % vectoriel (pdfkit), identité « éditorial sharp » :44 * logo encre/lime, fiche complète du rôle, historique en barres, plan radar des45 * comparables dessiné dans le PDF, tableau des ajustements. Format Lettre.46 */47import PDFDocument from "pdfkit";48import path from "path";49import type { UnitEstimate } from "./estimator";5051const INK = "#141814";52const INK3 = "#8b928c";53const PAPER = "#f5f3ee";54const SURFACE2 = "#faf9f5";55const GREEN = "#9e2a25";56const GREEN_DEEP = "#771f1b";57const LIME = "#ff5148";58const LIME_SOFT = "#ffe3e0";59const AMBER_SOFT = "#fdf3e2";60const DANGER_SOFT = "#fbe9e7";61const LINE = "#dedcd4";6263const W = 612;64const H = 792;65const M = 44; // marge6667const F = (f: string) => path.join(process.cwd(), "assets", "fonts", f);6869const fmt = (v: number | null | undefined) =>70 v == null71 ? "—"72 : new Intl.NumberFormat("fr-CA", {73 style: "currency",74 currency: "CAD",75 maximumFractionDigits: 0,76 }).format(v);7778const signed = (v: number) => `${v >= 0 ? "+" : "−"}${fmt(Math.abs(Math.round(v)))}`;79const fmtDist = (m: number) => (m < 1000 ? `${Math.round(m)} m` : `${(m / 1000).toFixed(1)} km`);8081const CONF_BG: Record<string, string> = { A: LIME, B: LIME_SOFT, C: AMBER_SOFT, D: DANGER_SOFT };82const CONF_TXT: Record<string, string> = {83 A: "Très fiable", B: "Fiable", C: "Indicative", D: "Peu fiable — marché mince",84};8586type Doc = InstanceType<typeof PDFDocument>;8788function logo(doc: Doc, x: number, y: number, scale = 1) {89 doc.save();90 doc.font("SG-Bold").fontSize(24 * scale);91 doc.fillColor(PAPER).text("Vrai", x, y, { lineBreak: false });92 const w = doc.widthOfString("Vrai");93 const bx = x + w + 4 * scale;94 doc.save();95 doc.rotate(-3, { origin: [bx, y + 12 * scale] });96 const bw = doc.widthOfString("Prix") + 12 * scale;97 doc.roundedRect(bx, y - 3 * scale, bw, 30 * scale, 5 * scale).fill(LIME);98 doc.fillColor(INK).text("Prix", bx + 6 * scale, y, { lineBreak: false });99 doc.restore();100 doc.restore();101}102103function kicker(doc: Doc, txt: string, x: number, y: number, color = GREEN) {104 doc.rect(x, y + 3.5, 20, 2).fill(color);105 doc.font("JB-Bold").fontSize(8).fillColor(color)106 .text(txt.toUpperCase(), x + 26, y, { characterSpacing: 1.4, lineBreak: false });107}108109function pageFrame(doc: Doc, page: number, total: number, generated: string) {110 doc.rect(0, 0, W, H).fill(PAPER);111 // filet de bas de page112 doc.rect(M, H - 46, W - 2 * M, 1.2).fill(INK);113 doc.font("JB-Reg").fontSize(6.5).fillColor(INK3).text(114 "VRAI-PRIX.COM — ESTIMATION STATISTIQUE À TITRE INDICATIF · NE REMPLACE PAS UNE ÉVALUATION PROFESSIONNELLE · SIMON-PIERRE BOUCHER · CONTACT@SPBOUCHER.AI",115 M, H - 38, { width: W - 2 * M - 60, characterSpacing: 0.4, lineBreak: false }116 );117 doc.font("JB-Bold").fontSize(7.5).fillColor(INK)118 .text(`${page} / ${total}`, W - M - 40, H - 39, { width: 40, align: "right" });119 doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)120 .text(generated, W - M - 160, H - 30, { width: 160, align: "right" });121}122123function card(doc: Doc, x: number, y: number, w: number, h: number, opts?: { shadow?: boolean; fill?: string }) {124 if (opts?.shadow !== false) doc.roundedRect(x + 3.5, y + 3.5, w, h, 8).fill("#e3e1d9");125 doc.roundedRect(x, y, w, h, 8).fillAndStroke(opts?.fill ?? "#ffffff", INK);126 doc.lineWidth(1.3);127}128129function kvCell(doc: Doc, x: number, y: number, w: number, h: number, k: string, v: string) {130 doc.lineWidth(0.8);131 doc.roundedRect(x, y, w, h, 4).fillAndStroke(SURFACE2, LINE);132 doc.font("JB-Bold").fontSize(5.8).fillColor(INK3)133 .text(k.toUpperCase(), x + 7, y + 6, { width: w - 14, characterSpacing: 0.7, height: 8, ellipsis: true });134 doc.font("SG-Bold").fontSize(9.2).fillColor(INK)135 .text(v, x + 7, y + 16.5, { width: w - 14, height: h - 20, ellipsis: true });136 doc.lineWidth(1.3);137}138139/** Plan radar vectoriel : sujet au centre, comparables par azimut/distance. */140function radar(doc: Doc, cx: number, cy: number, R: number, data: UnitEstimate) {141 const u = data.unit!;142 const comps = data.result.comps;143 const cos = Math.cos((u.lat * Math.PI) / 180);144 const pts = comps.map((c) => ({145 ...c,146 x: (c.lng - u.lng) * 111320 * cos,147 y: (c.lat - u.lat) * 110574,148 }));149 const maxM = Math.max(120, ...pts.map((p) => Math.hypot(p.x, p.y)));150 const ringSets = [151 [100, 250, 500], [250, 500, 1000], [500, 1000, 2000],152 [1000, 2500, 5000], [2500, 5000, 10000], [5000, 10000, 20000], [10000, 25000, 50000],153 ];154 const rings = ringSets.find((s) => maxM <= s[2]) ?? ringSets[ringSets.length - 1];155 const k = R / rings[2];156157 // cadre + grille158 doc.save();159 doc.roundedRect(cx - R - 16, cy - R - 16, 2 * (R + 16), 2 * (R + 16), 8).clip();160 doc.rect(cx - R - 16, cy - R - 16, 2 * (R + 16), 2 * (R + 16)).fill("#ffffff");161 doc.lineWidth(0.5).strokeColor("#eceae3");162 for (let g = -R - 16; g <= R + 16; g += 24) {163 doc.moveTo(cx + g, cy - R - 16).lineTo(cx + g, cy + R + 16).stroke();164 doc.moveTo(cx - R - 16, cy + g).lineTo(cx + R + 16, cy + g).stroke();165 }166 // anneaux167 rings.forEach((m, i) => {168 const rr = m * k;169 doc.lineWidth(i === 2 ? 1.3 : 0.8).strokeColor(i === 2 ? INK : "#b9b7ae");170 if (i !== 2) doc.dash(3, { space: 3 });171 doc.circle(cx, cy, rr).stroke();172 doc.undash();173 doc.font("JB-Reg").fontSize(5.5).fillColor(INK3)174 .text(fmtDist(m), cx + rr * 0.7071 + 2, cy - rr * 0.7071 - 7, { lineBreak: false });175 });176 // croix177 doc.lineWidth(0.6).strokeColor("#d5d3ca");178 doc.moveTo(cx, cy - R).lineTo(cx, cy + R).stroke();179 doc.moveTo(cx - R, cy).lineTo(cx + R, cy).stroke();180 // comparables numérotés181 pts.forEach((p, i) => {182 const px = cx + p.x * k;183 const py = cy - p.y * k;184 const rr = 6.5 + p.weight * 3.5;185 doc.circle(px, py, rr).lineWidth(1.1).fillAndStroke(GREEN, INK);186 doc.font("JB-Bold").fontSize(rr > 8.5 ? 7 : 6).fillColor(PAPER)187 .text(String(i + 1), px - rr, py - 3, { width: 2 * rr, align: "center", lineBreak: false });188 });189 // sujet : losange lime190 doc.save().translate(cx, cy).rotate(45);191 doc.rect(-8, -8, 16, 16).lineWidth(1.6).fillAndStroke(LIME, INK);192 doc.rect(-2.5, -2.5, 5, 5).fill(INK);193 doc.restore();194 // nord195 doc.save().translate(cx + R + 2, cy - R - 2);196 doc.path("M0,-9 L4,5 L0,2 L-4,5 Z").fill(INK);197 doc.font("JB-Bold").fontSize(6).fillColor(INK).text("N", -2.2, 8, { lineBreak: false });198 doc.restore();199 doc.restore();200 // bordure du cadre201 doc.roundedRect(cx - R - 16, cy - R - 16, 2 * (R + 16), 2 * (R + 16), 8).lineWidth(1.3).stroke(INK);202}203204export async function buildReport(data: UnitEstimate): Promise<Buffer> {205 const u = data.unit!;206 const s = u.specs;207 const r = data.result;208 const generated = new Date().toISOString().slice(0, 16).replace("T", " ");209210 const doc = new PDFDocument({ size: "LETTER", margin: 0, info: { Title: `Vrai-Prix — ${u.adresse ?? ""}` } });211 doc.registerFont("SG-Bold", F("SpaceGrotesk-Bold.ttf"));212 doc.registerFont("SG-Med", F("SpaceGrotesk-Medium.ttf"));213 doc.registerFont("JB-Reg", F("JetBrainsMono-Regular.ttf"));214 doc.registerFont("JB-Bold", F("JetBrainsMono-Bold.ttf"));215 doc.registerFont("Inter", F("Inter-Regular.ttf"));216217 const chunks: Buffer[] = [];218 doc.on("data", (c: Buffer) => chunks.push(c));219 const done = new Promise<Buffer>((res) => doc.on("end", () => res(Buffer.concat(chunks))));220221 /* =============================== PAGE 1 =============================== */222 pageFrame(doc, 1, 2, generated);223224 // bandeau encre225 doc.rect(0, 0, W, 96).fill(INK);226 logo(doc, M, 30);227 doc.font("JB-Reg").fontSize(7).fillColor(LIME)228 .text("RAPPORT D'ÉVALUATION · QUÉBEC", M, 66, { characterSpacing: 1.6, lineBreak: false });229 doc.font("JB-Reg").fontSize(7).fillColor("#9aa39c")230 .text(`ID ${u.id}`, W - M - 200, 34, { width: 200, align: "right" })231 .text(`GÉNÉRÉ LE ${generated}`, W - M - 200, 46, { width: 200, align: "right" })232 .text(`MATRICULE ${s.matricule ?? "—"}`, W - M - 200, 58, { width: 200, align: "right" });233 doc.rect(0, 96, W, 3).fill(LIME);234235 // adresse + estimation236 let y = 122;237 kicker(doc, "Valeur estimée au marché", M, y);238 y += 16;239 doc.font("SG-Bold").fontSize(15).fillColor(INK)240 .text(`${(u.adresse ?? "").toUpperCase()}${s.apt ? " APP. " + s.apt : ""} · ${(u.municipalite ?? "").toUpperCase()}`,241 M, y, { width: W - 2 * M });242 y = doc.y + 6;243 doc.font("SG-Bold").fontSize(46).fillColor(INK).text(fmt(r.estimate), M, y);244 y = doc.y + 10;245246 // rangée fourchette / confiance / rôle / écart247 const rowY = y;248 const cols = [249 ["FOURCHETTE HONNÊTE", `${fmt(r.low)} → ${fmt(r.high)}`],250 ["ÉVALUATION MUNICIPALE 2026", fmt(u.valeurRole)],251 ["ÉCART VS RÔLE", u.valeurRole ? `${((r.estimate / u.valeurRole - 1) * 100).toFixed(0)} %` : "—"],252 ] as const;253 let cx0 = M;254 for (const [k, v] of cols) {255 doc.font("JB-Bold").fontSize(6.5).fillColor(INK3).text(k, cx0, rowY, { characterSpacing: 0.8, lineBreak: false });256 const lw = doc.widthOfString(k) + cols.length * 0.8;257 doc.font("SG-Bold").fontSize(13).fillColor(INK).text(v, cx0, rowY + 11, { lineBreak: false });258 cx0 += Math.max(doc.widthOfString(v), lw) + 34;259 }260 // pastille confiance261 const confTxt = `CONFIANCE ${r.confidenceLevel} · ${r.confidencePct} % — ${CONF_TXT[r.confidenceLevel].toUpperCase()}`;262 doc.font("JB-Bold").fontSize(7.5);263 const cw = doc.widthOfString(confTxt) + 20;264 doc.roundedRect(M, rowY + 34, cw, 18, 4).lineWidth(1).fillAndStroke(CONF_BG[r.confidenceLevel], INK);265 doc.fillColor(r.confidenceLevel === "D" ? "#b3423a" : INK).text(confTxt, M + 10, rowY + 39.5, { lineBreak: false });266267 // fiche de la propriété268 y = rowY + 72;269 kicker(doc, "Fiche de la propriété — registre officiel (rôle 2026)", M, y);270 y += 16;271 const groups: [string, [string, string][]][] = [272 ["BÂTIMENT", [273 ["Année constr.", u.anneeConstruction ? `${u.anneeConstruction}${s.anneeEstimee === "E" ? " (est.)" : ""}` : "—"],274 ["Aire étages", u.aireEtagesM2 ? `${u.aireEtagesM2} m²` : "—"],275 ["Étages", u.specs.nbEtages != null ? String(u.specs.nbEtages) : "—"],276 ["Genre", s.genreConstruction ?? "—"],277 ["Lien phys.", s.lienPhysique ?? "—"],278 ["Logements", u.nbLogements != null ? String(u.nbLogements) : "—"],279 ["Locaux n-rés.", s.nbLocauxNonResid != null ? String(s.nbLocauxNonResid) : "—"],280 ["Chambres loc.", s.nbChambresLocatives != null ? String(s.nbChambresLocatives) : "—"],281 ]],282 ["TERRAIN", [283 ["Superficie", u.superficieTerrainM2 ? `${u.superficieTerrainM2} m²` : "—"],284 ["Mes. frontale", s.frontTerrainM ? `${s.frontTerrainM} m` : "—"],285 ["CUBF", s.cubf ? String(s.cubf) : "—"],286 ["Usage", s.cubfLibelle ?? "—"],287 ["Unité voisin.", s.uniteVoisinage || "—"],288 ["Arrond.", s.arrond || "—"],289 ]],290 ["RÔLE D'ÉVALUATION", [291 ["Val. terrain", fmt(s.valeurTerrain)],292 ["Val. bâtiment", fmt(s.valeurBatiment)],293 ["Val. totale", fmt(u.valeurRole)],294 ["Rôle antér.", fmt(s.valeurAnterieure)],295 ["Cond. marché", s.datCondMarche ?? "—"],296 ["Adresses", s.nAdresses != null ? String(s.nAdresses) : "—"],297 ]],298 ];299 const gW = (W - 2 * M - 2 * 14) / 3;300 const cellH = 30;301 const gH = 4 * (cellH + 6) + 34;302 groups.forEach(([title, rows], gi) => {303 const gx = M + gi * (gW + 14);304 card(doc, gx, y, gW, gH);305 doc.font("JB-Bold").fontSize(7).fillColor(GREEN_DEEP)306 .text(title, gx + 12, y + 11, { characterSpacing: 1.2, lineBreak: false });307 doc.moveTo(gx + 12, y + 24).lineTo(gx + gW - 12, y + 24).dash(2, { space: 3 }).lineWidth(0.8).stroke(LINE).undash();308 const cw2 = (gW - 24 - 6) / 2;309 rows.forEach(([k, v], i) => {310 const col = i % 2, row = Math.floor(i / 2);311 kvCell(doc, gx + 12 + col * (cw2 + 6), y + 32 + row * (cellH + 6), cw2, cellH, k, v);312 });313 });314 y += gH + 24;315316 // historique317 kicker(doc, "Valeur estimée par année — 2021 → 2026", M, y);318 y += 16;319 const hist = u.history;320 const hMax = Math.max(...hist.map((h) => h.value ?? 0), 1);321 const histH = hist.length * 21 + 24;322 card(doc, M, y, W - 2 * M, histH);323 hist.forEach((h, i) => {324 const ly = y + 14 + i * 21;325 doc.font("JB-Bold").fontSize(7.5).fillColor(INK).text(String(h.year), M + 14, ly + 2, { lineBreak: false });326 const trackX = M + 52, trackW = W - 2 * M - 52 - 100;327 doc.rect(trackX, ly, trackW, 12).fill(SURFACE2);328 doc.rect(trackX, ly, Math.max(2, ((h.value ?? 0) / hMax) * trackW), 12).fill(h.year === 2026 ? INK : GREEN);329 doc.font("JB-Bold").fontSize(7.5).fillColor(INK)330 .text(fmt(h.value), W - M - 92, ly + 2, { width: 80, align: "right" });331 });332333 /* =============================== PAGE 2 =============================== */334 doc.addPage({ size: "LETTER", margin: 0 });335 pageFrame(doc, 2, 2, generated);336 doc.rect(0, 0, W, 8).fill(INK);337 doc.rect(0, 8, W, 2.5).fill(LIME);338339 y = 34;340 kicker(doc, "Pourquoi ce prix — le calcul, sans boîte noire", M, y);341 y += 16;342 const tileW = (W - 2 * M - 14) / 2;343 card(doc, M, y, tileW, 64);344 doc.font("JB-Bold").fontSize(6.5).fillColor(INK3).text("MODÈLE HÉDONIQUE (LIGHTGBM · 690 000 VENTES QC)", M + 14, y + 11, { characterSpacing: 0.6 });345 doc.font("SG-Bold").fontSize(21).fillColor(INK).text(fmt(r.modelEstimate), M + 14, y + 24);346 doc.font("JB-Reg").fontSize(7).fillColor(GREEN_DEEP).text(`POIDS : ${(r.modelWeight * 100).toFixed(0)} %`, M + 14, y + 49);347 card(doc, M + tileW + 14, y, tileW, 64);348 doc.font("JB-Bold").fontSize(6.5).fillColor(INK3).text("COMPARABLES AJUSTÉS (MÉDIANE PONDÉRÉE)", M + tileW + 28, y + 11, { characterSpacing: 0.6 });349 doc.font("SG-Bold").fontSize(21).fillColor(INK).text(fmt(r.compsEstimate), M + tileW + 28, y + 24);350 doc.font("JB-Reg").fontSize(7).fillColor(GREEN_DEEP).text(351 `POIDS : ${((1 - r.modelWeight) * 100).toFixed(0)} % · ${r.nCompsUsed} COMPS${r.compsDispersionPct != null ? ` · ±${r.compsDispersionPct} %` : ""}`,352 M + tileW + 28, y + 49);353 y += 88;354355 // radar + tableau356 kicker(doc, `Plan des comparables — ${r.nCompsUsed} ventes réelles · azimut + distance`, M, y);357 y += 18;358 const R = 118;359 radar(doc, M + R + 16, y + R + 16, R, data);360361 const tX = M + 2 * (R + 16) + 16;362 const tW = W - M - tX;363 doc.font("JB-Bold").fontSize(6.2).fillColor(INK3);364 let ty = y + 2;365 r.comps.slice(0, 12).forEach((c, i) => {366 const rowH = 22.5;367 if (i % 2 === 0) doc.rect(tX, ty - 2, tW, rowH).fill(SURFACE2);368 doc.circle(tX + 8, ty + 7, 6).lineWidth(0.9).fillAndStroke(GREEN, INK);369 doc.font("JB-Bold").fontSize(6).fillColor(PAPER).text(String(i + 1), tX + 2, ty + 4.5, { width: 12, align: "center", lineBreak: false });370 doc.font("SG-Bold").fontSize(7.3).fillColor(INK)371 .text(`${c.street ?? ""}`, tX + 19, ty, { width: tW - 90, height: 9, ellipsis: true, lineBreak: false });372 doc.font("JB-Reg").fontSize(5.8).fillColor(INK3)373 .text(`${c.date} · ${fmtDist(c.distanceM)} · VENDU ${fmt(c.amount)} · T ${signed(c.adjTime)} · S ${signed(c.adjArea)} · Â ${signed(c.adjAge)}`,374 tX + 19, ty + 10, { width: tW - 78, height: 8, ellipsis: true, lineBreak: false });375 doc.font("SG-Bold").fontSize(8).fillColor(INK)376 .text(fmt(Math.round(c.adjustedPrice)), tX + tW - 68, ty + 3, { width: 68, align: "right", lineBreak: false });377 ty += rowH;378 });379 // légende radar380 const legY = y + 2 * (R + 16) + 8;381 doc.font("JB-Reg").fontSize(6.3).fillColor(INK3).text(382 "◆ = PROPRIÉTÉ ÉVALUÉE (CENTRE) · ● = VENTE COMPARABLE (TAILLE = POIDS) · T/S/Â = AJUSTEMENTS TEMPS / SUPERFICIE / ÂGE",383 M, legY, { width: W - 2 * M, characterSpacing: 0.4 });384385 // méthodo386 const my = Math.max(legY + 20, ty + 14);387 card(doc, M, my, W - 2 * M, 92, { fill: INK, shadow: false });388 doc.font("JB-Bold").fontSize(7).fillColor(LIME).text("MÉTHODOLOGIE", M + 16, my + 12, { characterSpacing: 1.4 });389 doc.font("Inter").fontSize(7.8).fillColor("#e8e6df").text(390 "L'estimation combine (1) un modèle hédonique de gradient boosting entraîné sur ~690 000 transactions québécoises " +391 "(2021-2026) appariées au rôle d'évaluation foncière géoréférencé du MAMH — erreur médiane de 11 % — et (2) une médiane " +392 "pondérée des ventes comparables voisines, chacune ajustée pour l'évolution du marché (indice mensuel), l'écart de " +393 "superficie (50 % du $/m²) et l'écart d'âge (0,5 %/an, plafonné à ±10 %). La fourchette correspond aux 10e et 90e " +394 "centiles du modèle recentrés sur l'estimation finale. L'indice de confiance (A-D) reflète le nombre de comparables, " +395 "leur dispersion et la largeur de la fourchette. Validation selon la norme IAAO sur études de ratios.",396 M + 16, my + 26, { width: W - 2 * M - 32, lineGap: 1.5 });397398 doc.end();399 return done;400}401