SPB Git

spb/vrai-prix Public

Vrai-Prix — l'évaluation du vrai prix des propriétés résidentielles au Québec.

TypeScript 96.7% CSS 3.1%
16.5 KB · 361 lines typescript
Raw Blame History
1// Auteur : Simon-Pierre Boucher — contact@spboucher.ai2/**3 * Rapport PDF Vrai-Prix — 100 % vectoriel (pdfkit), identité « éditorial sharp » :4 * logo encre/lime, fiche complète du rôle, historique en barres, plan radar des5 * comparables dessiné dans le PDF, tableau des ajustements. Format Lettre.6 */7import PDFDocument from "pdfkit";8import path from "path";9import type { UnitEstimate } from "./estimator";1011const INK = "#141814";12const INK3 = "#8b928c";13const PAPER = "#f5f3ee";14const SURFACE2 = "#faf9f5";15const GREEN = "#9e2a25";16const GREEN_DEEP = "#771f1b";17const LIME = "#ff5148";18const LIME_SOFT = "#ffe3e0";19const AMBER_SOFT = "#fdf3e2";20const DANGER_SOFT = "#fbe9e7";21const LINE = "#dedcd4";2223const W = 612;24const H = 792;25const M = 44; // marge2627const F = (f: string) => path.join(process.cwd(), "assets", "fonts", f);2829const fmt = (v: number | null | undefined) =>30  v == null31    ? "—"32    : new Intl.NumberFormat("fr-CA", {33        style: "currency",34        currency: "CAD",35        maximumFractionDigits: 0,36      }).format(v);3738const signed = (v: number) => `${v >= 0 ? "+" : "−"}${fmt(Math.abs(Math.round(v)))}`;39const fmtDist = (m: number) => (m < 1000 ? `${Math.round(m)} m` : `${(m / 1000).toFixed(1)} km`);4041const CONF_BG: Record<string, string> = { A: LIME, B: LIME_SOFT, C: AMBER_SOFT, D: DANGER_SOFT };42const CONF_TXT: Record<string, string> = {43  A: "Très fiable", B: "Fiable", C: "Indicative", D: "Peu fiable — marché mince",44};4546type Doc = InstanceType<typeof PDFDocument>;4748function logo(doc: Doc, x: number, y: number, scale = 1) {49  doc.save();50  doc.font("SG-Bold").fontSize(24 * scale);51  doc.fillColor(PAPER).text("Vrai", x, y, { lineBreak: false });52  const w = doc.widthOfString("Vrai");53  const bx = x + w + 4 * scale;54  doc.save();55  doc.rotate(-3, { origin: [bx, y + 12 * scale] });56  const bw = doc.widthOfString("Prix") + 12 * scale;57  doc.roundedRect(bx, y - 3 * scale, bw, 30 * scale, 5 * scale).fill(LIME);58  doc.fillColor(INK).text("Prix", bx + 6 * scale, y, { lineBreak: false });59  doc.restore();60  doc.restore();61}6263function kicker(doc: Doc, txt: string, x: number, y: number, color = GREEN) {64  doc.rect(x, y + 3.5, 20, 2).fill(color);65  doc.font("JB-Bold").fontSize(8).fillColor(color)66    .text(txt.toUpperCase(), x + 26, y, { characterSpacing: 1.4, lineBreak: false });67}6869function pageFrame(doc: Doc, page: number, total: number, generated: string) {70  doc.rect(0, 0, W, H).fill(PAPER);71  // filet de bas de page72  doc.rect(M, H - 46, W - 2 * M, 1.2).fill(INK);73  doc.font("JB-Reg").fontSize(6.5).fillColor(INK3).text(74    "VRAI-PRIX.COM — ESTIMATION STATISTIQUE À TITRE INDICATIF · NE REMPLACE PAS UNE ÉVALUATION PROFESSIONNELLE · SIMON-PIERRE BOUCHER · CONTACT@SPBOUCHER.AI",75    M, H - 38, { width: W - 2 * M - 60, characterSpacing: 0.4, lineBreak: false }76  );77  doc.font("JB-Bold").fontSize(7.5).fillColor(INK)78    .text(`${page} / ${total}`, W - M - 40, H - 39, { width: 40, align: "right" });79  doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)80    .text(generated, W - M - 160, H - 30, { width: 160, align: "right" });81}8283function card(doc: Doc, x: number, y: number, w: number, h: number, opts?: { shadow?: boolean; fill?: string }) {84  if (opts?.shadow !== false) doc.roundedRect(x + 3.5, y + 3.5, w, h, 8).fill("#e3e1d9");85  doc.roundedRect(x, y, w, h, 8).fillAndStroke(opts?.fill ?? "#ffffff", INK);86  doc.lineWidth(1.3);87}8889function kvCell(doc: Doc, x: number, y: number, w: number, h: number, k: string, v: string) {90  doc.lineWidth(0.8);91  doc.roundedRect(x, y, w, h, 4).fillAndStroke(SURFACE2, LINE);92  doc.font("JB-Bold").fontSize(5.8).fillColor(INK3)93    .text(k.toUpperCase(), x + 7, y + 6, { width: w - 14, characterSpacing: 0.7, height: 8, ellipsis: true });94  doc.font("SG-Bold").fontSize(9.2).fillColor(INK)95    .text(v, x + 7, y + 16.5, { width: w - 14, height: h - 20, ellipsis: true });96  doc.lineWidth(1.3);97}9899/** Plan radar vectoriel : sujet au centre, comparables par azimut/distance. */100function radar(doc: Doc, cx: number, cy: number, R: number, data: UnitEstimate) {101  const u = data.unit!;102  const comps = data.result.comps;103  const cos = Math.cos((u.lat * Math.PI) / 180);104  const pts = comps.map((c) => ({105    ...c,106    x: (c.lng - u.lng) * 111320 * cos,107    y: (c.lat - u.lat) * 110574,108  }));109  const maxM = Math.max(120, ...pts.map((p) => Math.hypot(p.x, p.y)));110  const ringSets = [111    [100, 250, 500], [250, 500, 1000], [500, 1000, 2000],112    [1000, 2500, 5000], [2500, 5000, 10000], [5000, 10000, 20000], [10000, 25000, 50000],113  ];114  const rings = ringSets.find((s) => maxM <= s[2]) ?? ringSets[ringSets.length - 1];115  const k = R / rings[2];116117  // cadre + grille118  doc.save();119  doc.roundedRect(cx - R - 16, cy - R - 16, 2 * (R + 16), 2 * (R + 16), 8).clip();120  doc.rect(cx - R - 16, cy - R - 16, 2 * (R + 16), 2 * (R + 16)).fill("#ffffff");121  doc.lineWidth(0.5).strokeColor("#eceae3");122  for (let g = -R - 16; g <= R + 16; g += 24) {123    doc.moveTo(cx + g, cy - R - 16).lineTo(cx + g, cy + R + 16).stroke();124    doc.moveTo(cx - R - 16, cy + g).lineTo(cx + R + 16, cy + g).stroke();125  }126  // anneaux127  rings.forEach((m, i) => {128    const rr = m * k;129    doc.lineWidth(i === 2 ? 1.3 : 0.8).strokeColor(i === 2 ? INK : "#b9b7ae");130    if (i !== 2) doc.dash(3, { space: 3 });131    doc.circle(cx, cy, rr).stroke();132    doc.undash();133    doc.font("JB-Reg").fontSize(5.5).fillColor(INK3)134      .text(fmtDist(m), cx + rr * 0.7071 + 2, cy - rr * 0.7071 - 7, { lineBreak: false });135  });136  // croix137  doc.lineWidth(0.6).strokeColor("#d5d3ca");138  doc.moveTo(cx, cy - R).lineTo(cx, cy + R).stroke();139  doc.moveTo(cx - R, cy).lineTo(cx + R, cy).stroke();140  // comparables numérotés141  pts.forEach((p, i) => {142    const px = cx + p.x * k;143    const py = cy - p.y * k;144    const rr = 6.5 + p.weight * 3.5;145    doc.circle(px, py, rr).lineWidth(1.1).fillAndStroke(GREEN, INK);146    doc.font("JB-Bold").fontSize(rr > 8.5 ? 7 : 6).fillColor(PAPER)147      .text(String(i + 1), px - rr, py - 3, { width: 2 * rr, align: "center", lineBreak: false });148  });149  // sujet : losange lime150  doc.save().translate(cx, cy).rotate(45);151  doc.rect(-8, -8, 16, 16).lineWidth(1.6).fillAndStroke(LIME, INK);152  doc.rect(-2.5, -2.5, 5, 5).fill(INK);153  doc.restore();154  // nord155  doc.save().translate(cx + R + 2, cy - R - 2);156  doc.path("M0,-9 L4,5 L0,2 L-4,5 Z").fill(INK);157  doc.font("JB-Bold").fontSize(6).fillColor(INK).text("N", -2.2, 8, { lineBreak: false });158  doc.restore();159  doc.restore();160  // bordure du cadre161  doc.roundedRect(cx - R - 16, cy - R - 16, 2 * (R + 16), 2 * (R + 16), 8).lineWidth(1.3).stroke(INK);162}163164export async function buildReport(data: UnitEstimate): Promise<Buffer> {165  const u = data.unit!;166  const s = u.specs;167  const r = data.result;168  const generated = new Date().toISOString().slice(0, 16).replace("T", " ");169170  const doc = new PDFDocument({ size: "LETTER", margin: 0, info: { Title: `Vrai-Prix — ${u.adresse ?? ""}` } });171  doc.registerFont("SG-Bold", F("SpaceGrotesk-Bold.ttf"));172  doc.registerFont("SG-Med", F("SpaceGrotesk-Medium.ttf"));173  doc.registerFont("JB-Reg", F("JetBrainsMono-Regular.ttf"));174  doc.registerFont("JB-Bold", F("JetBrainsMono-Bold.ttf"));175  doc.registerFont("Inter", F("Inter-Regular.ttf"));176177  const chunks: Buffer[] = [];178  doc.on("data", (c: Buffer) => chunks.push(c));179  const done = new Promise<Buffer>((res) => doc.on("end", () => res(Buffer.concat(chunks))));180181  /* =============================== PAGE 1 =============================== */182  pageFrame(doc, 1, 2, generated);183184  // bandeau encre185  doc.rect(0, 0, W, 96).fill(INK);186  logo(doc, M, 30);187  doc.font("JB-Reg").fontSize(7).fillColor(LIME)188    .text("RAPPORT D'ÉVALUATION · QUÉBEC", M, 66, { characterSpacing: 1.6, lineBreak: false });189  doc.font("JB-Reg").fontSize(7).fillColor("#9aa39c")190    .text(`ID ${u.id}`, W - M - 200, 34, { width: 200, align: "right" })191    .text(`GÉNÉRÉ LE ${generated}`, W - M - 200, 46, { width: 200, align: "right" })192    .text(`MATRICULE ${s.matricule ?? "—"}`, W - M - 200, 58, { width: 200, align: "right" });193  doc.rect(0, 96, W, 3).fill(LIME);194195  // adresse + estimation196  let y = 122;197  kicker(doc, "Valeur estimée au marché", M, y);198  y += 16;199  doc.font("SG-Bold").fontSize(15).fillColor(INK)200    .text(`${(u.adresse ?? "").toUpperCase()}${s.apt ? " APP. " + s.apt : ""} · ${(u.municipalite ?? "").toUpperCase()}`,201      M, y, { width: W - 2 * M });202  y = doc.y + 6;203  doc.font("SG-Bold").fontSize(46).fillColor(INK).text(fmt(r.estimate), M, y);204  y = doc.y + 10;205206  // rangée fourchette / confiance / rôle / écart207  const rowY = y;208  const cols = [209    ["FOURCHETTE HONNÊTE", `${fmt(r.low)} → ${fmt(r.high)}`],210    ["ÉVALUATION MUNICIPALE 2026", fmt(u.valeurRole)],211    ["ÉCART VS RÔLE", u.valeurRole ? `${((r.estimate / u.valeurRole - 1) * 100).toFixed(0)} %` : "—"],212  ] as const;213  let cx0 = M;214  for (const [k, v] of cols) {215    doc.font("JB-Bold").fontSize(6.5).fillColor(INK3).text(k, cx0, rowY, { characterSpacing: 0.8, lineBreak: false });216    const lw = doc.widthOfString(k) + cols.length * 0.8;217    doc.font("SG-Bold").fontSize(13).fillColor(INK).text(v, cx0, rowY + 11, { lineBreak: false });218    cx0 += Math.max(doc.widthOfString(v), lw) + 34;219  }220  // pastille confiance221  const confTxt = `CONFIANCE ${r.confidenceLevel} · ${r.confidencePct} % — ${CONF_TXT[r.confidenceLevel].toUpperCase()}`;222  doc.font("JB-Bold").fontSize(7.5);223  const cw = doc.widthOfString(confTxt) + 20;224  doc.roundedRect(M, rowY + 34, cw, 18, 4).lineWidth(1).fillAndStroke(CONF_BG[r.confidenceLevel], INK);225  doc.fillColor(r.confidenceLevel === "D" ? "#b3423a" : INK).text(confTxt, M + 10, rowY + 39.5, { lineBreak: false });226227  // fiche de la propriété228  y = rowY + 72;229  kicker(doc, "Fiche de la propriété — registre officiel (rôle 2026)", M, y);230  y += 16;231  const groups: [string, [string, string][]][] = [232    ["BÂTIMENT", [233      ["Année constr.", u.anneeConstruction ? `${u.anneeConstruction}${s.anneeEstimee === "E" ? " (est.)" : ""}` : "—"],234      ["Aire étages", u.aireEtagesM2 ? `${u.aireEtagesM2} m²` : "—"],235      ["Étages", u.specs.nbEtages != null ? String(u.specs.nbEtages) : "—"],236      ["Genre", s.genreConstruction ?? "—"],237      ["Lien phys.", s.lienPhysique ?? "—"],238      ["Logements", u.nbLogements != null ? String(u.nbLogements) : "—"],239      ["Locaux n-rés.", s.nbLocauxNonResid != null ? String(s.nbLocauxNonResid) : "—"],240      ["Chambres loc.", s.nbChambresLocatives != null ? String(s.nbChambresLocatives) : "—"],241    ]],242    ["TERRAIN", [243      ["Superficie", u.superficieTerrainM2 ? `${u.superficieTerrainM2} m²` : "—"],244      ["Mes. frontale", s.frontTerrainM ? `${s.frontTerrainM} m` : "—"],245      ["CUBF", s.cubf ? String(s.cubf) : "—"],246      ["Usage", s.cubfLibelle ?? "—"],247      ["Unité voisin.", s.uniteVoisinage || "—"],248      ["Arrond.", s.arrond || "—"],249    ]],250    ["RÔLE D'ÉVALUATION", [251      ["Val. terrain", fmt(s.valeurTerrain)],252      ["Val. bâtiment", fmt(s.valeurBatiment)],253      ["Val. totale", fmt(u.valeurRole)],254      ["Rôle antér.", fmt(s.valeurAnterieure)],255      ["Cond. marché", s.datCondMarche ?? "—"],256      ["Adresses", s.nAdresses != null ? String(s.nAdresses) : "—"],257    ]],258  ];259  const gW = (W - 2 * M - 2 * 14) / 3;260  const cellH = 30;261  const gH = 4 * (cellH + 6) + 34;262  groups.forEach(([title, rows], gi) => {263    const gx = M + gi * (gW + 14);264    card(doc, gx, y, gW, gH);265    doc.font("JB-Bold").fontSize(7).fillColor(GREEN_DEEP)266      .text(title, gx + 12, y + 11, { characterSpacing: 1.2, lineBreak: false });267    doc.moveTo(gx + 12, y + 24).lineTo(gx + gW - 12, y + 24).dash(2, { space: 3 }).lineWidth(0.8).stroke(LINE).undash();268    const cw2 = (gW - 24 - 6) / 2;269    rows.forEach(([k, v], i) => {270      const col = i % 2, row = Math.floor(i / 2);271      kvCell(doc, gx + 12 + col * (cw2 + 6), y + 32 + row * (cellH + 6), cw2, cellH, k, v);272    });273  });274  y += gH + 24;275276  // historique277  kicker(doc, "Valeur estimée par année — 2021 → 2026", M, y);278  y += 16;279  const hist = u.history;280  const hMax = Math.max(...hist.map((h) => h.value ?? 0), 1);281  const histH = hist.length * 21 + 24;282  card(doc, M, y, W - 2 * M, histH);283  hist.forEach((h, i) => {284    const ly = y + 14 + i * 21;285    doc.font("JB-Bold").fontSize(7.5).fillColor(INK).text(String(h.year), M + 14, ly + 2, { lineBreak: false });286    const trackX = M + 52, trackW = W - 2 * M - 52 - 100;287    doc.rect(trackX, ly, trackW, 12).fill(SURFACE2);288    doc.rect(trackX, ly, Math.max(2, ((h.value ?? 0) / hMax) * trackW), 12).fill(h.year === 2026 ? INK : GREEN);289    doc.font("JB-Bold").fontSize(7.5).fillColor(INK)290      .text(fmt(h.value), W - M - 92, ly + 2, { width: 80, align: "right" });291  });292293  /* =============================== PAGE 2 =============================== */294  doc.addPage({ size: "LETTER", margin: 0 });295  pageFrame(doc, 2, 2, generated);296  doc.rect(0, 0, W, 8).fill(INK);297  doc.rect(0, 8, W, 2.5).fill(LIME);298299  y = 34;300  kicker(doc, "Pourquoi ce prix — le calcul, sans boîte noire", M, y);301  y += 16;302  const tileW = (W - 2 * M - 14) / 2;303  card(doc, M, y, tileW, 64);304  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 });305  doc.font("SG-Bold").fontSize(21).fillColor(INK).text(fmt(r.modelEstimate), M + 14, y + 24);306  doc.font("JB-Reg").fontSize(7).fillColor(GREEN_DEEP).text(`POIDS : ${(r.modelWeight * 100).toFixed(0)} %`, M + 14, y + 49);307  card(doc, M + tileW + 14, y, tileW, 64);308  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 });309  doc.font("SG-Bold").fontSize(21).fillColor(INK).text(fmt(r.compsEstimate), M + tileW + 28, y + 24);310  doc.font("JB-Reg").fontSize(7).fillColor(GREEN_DEEP).text(311    `POIDS : ${((1 - r.modelWeight) * 100).toFixed(0)} % · ${r.nCompsUsed} COMPS${r.compsDispersionPct != null ? ` · ±${r.compsDispersionPct} %` : ""}`,312    M + tileW + 28, y + 49);313  y += 88;314315  // radar + tableau316  kicker(doc, `Plan des comparables — ${r.nCompsUsed} ventes réelles · azimut + distance`, M, y);317  y += 18;318  const R = 118;319  radar(doc, M + R + 16, y + R + 16, R, data);320321  const tX = M + 2 * (R + 16) + 16;322  const tW = W - M - tX;323  doc.font("JB-Bold").fontSize(6.2).fillColor(INK3);324  let ty = y + 2;325  r.comps.slice(0, 12).forEach((c, i) => {326    const rowH = 22.5;327    if (i % 2 === 0) doc.rect(tX, ty - 2, tW, rowH).fill(SURFACE2);328    doc.circle(tX + 8, ty + 7, 6).lineWidth(0.9).fillAndStroke(GREEN, INK);329    doc.font("JB-Bold").fontSize(6).fillColor(PAPER).text(String(i + 1), tX + 2, ty + 4.5, { width: 12, align: "center", lineBreak: false });330    doc.font("SG-Bold").fontSize(7.3).fillColor(INK)331      .text(`${c.street ?? ""}`, tX + 19, ty, { width: tW - 90, height: 9, ellipsis: true, lineBreak: false });332    doc.font("JB-Reg").fontSize(5.8).fillColor(INK3)333      .text(`${c.date} · ${fmtDist(c.distanceM)} · VENDU ${fmt(c.amount)} · T ${signed(c.adjTime)} · S ${signed(c.adjArea)} · Â ${signed(c.adjAge)}`,334        tX + 19, ty + 10, { width: tW - 78, height: 8, ellipsis: true, lineBreak: false });335    doc.font("SG-Bold").fontSize(8).fillColor(INK)336      .text(fmt(Math.round(c.adjustedPrice)), tX + tW - 68, ty + 3, { width: 68, align: "right", lineBreak: false });337    ty += rowH;338  });339  // légende radar340  const legY = y + 2 * (R + 16) + 8;341  doc.font("JB-Reg").fontSize(6.3).fillColor(INK3).text(342    "◆ = PROPRIÉTÉ ÉVALUÉE (CENTRE) · ● = VENTE COMPARABLE (TAILLE = POIDS) · T/S/Â = AJUSTEMENTS TEMPS / SUPERFICIE / ÂGE",343    M, legY, { width: W - 2 * M, characterSpacing: 0.4 });344345  // méthodo346  const my = Math.max(legY + 20, ty + 14);347  card(doc, M, my, W - 2 * M, 92, { fill: INK, shadow: false });348  doc.font("JB-Bold").fontSize(7).fillColor(LIME).text("MÉTHODOLOGIE", M + 16, my + 12, { characterSpacing: 1.4 });349  doc.font("Inter").fontSize(7.8).fillColor("#e8e6df").text(350    "L'estimation combine (1) un modèle hédonique de gradient boosting entraîné sur ~690 000 transactions québécoises " +351    "(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 " +352    "pondérée des ventes comparables voisines, chacune ajustée pour l'évolution du marché (indice mensuel), l'écart de " +353    "superficie (50 % du $/m²) et l'écart d'âge (0,5 %/an, plafonné à ±10 %). La fourchette correspond aux 10e et 90e " +354    "centiles du modèle recentrés sur l'estimation finale. L'indice de confiance (A-D) reflète le nombre de comparables, " +355    "leur dispersion et la largeur de la fourchette. Validation selon la norme IAAO sur études de ratios.",356    M + 16, my + 26, { width: W - 2 * M - 32, lineGap: 1.5 });357358  doc.end();359  return done;360}361