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.2%
14.6 KB · 304 lines typescript
Raw Blame History
1// Auteur : Simon-Pierre Boucher — contact@spboucher.ai2/**3 * Rapport PDF de parc immobilier — couverture agrégée (tuiles, historique du parc,4 * répartitions, table des propriétés) puis une page condensée par propriété.5 * 100 % vectoriel, identité Vrai-Prix.6 */7import PDFDocument from "pdfkit";8import path from "path";9import type { PortfolioResult, UnitEstimate } from "./estimator";1011const INK = "#141814";12const INK3 = "#8b928c";13const PAPER = "#f5f3ee";14const SURFACE2 = "#faf9f5";15const GREEN = "#9e2a25";16const LIME = "#ff5148";17const LIME_SOFT = "#ffe3e0";18const AMBER_SOFT = "#fdf3e2";19const DANGER_SOFT = "#fbe9e7";20const LINE = "#dedcd4";2122const W = 612;23const H = 792;24const M = 44;2526const F = (f: string) => path.join(process.cwd(), "assets", "fonts", f);27const fmt = (v: number | null | undefined) =>28  v == null29    ? "—"30    : new Intl.NumberFormat("fr-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(v);31const CONF_BG: Record<string, string> = { A: LIME, B: LIME_SOFT, C: AMBER_SOFT, D: DANGER_SOFT };32const TYPE_FR: Record<string, string> = {33  unifamilial: "Unifamiliale", plex: "Plex", condo_ou_multi: "Condo/multi",34  chalet: "Chalet", maison_mobile: "Maison mobile", terrain: "Terrain", autre: "Autre",35};3637type Doc = InstanceType<typeof PDFDocument>;3839function logo(doc: Doc, x: number, y: number, scale = 1) {40  doc.save();41  doc.font("SG-Bold").fontSize(24 * scale);42  doc.fillColor(PAPER).text("Vrai", x, y, { lineBreak: false });43  const w = doc.widthOfString("Vrai");44  const bx = x + w + 4 * scale;45  doc.save();46  doc.rotate(-3, { origin: [bx, y + 12 * scale] });47  const bw = doc.widthOfString("Prix") + 12 * scale;48  doc.roundedRect(bx, y - 3 * scale, bw, 30 * scale, 5 * scale).fill(LIME);49  doc.fillColor(INK).text("Prix", bx + 6 * scale, y, { lineBreak: false });50  doc.restore();51  doc.restore();52}5354function kicker(doc: Doc, txt: string, x: number, y: number) {55  doc.rect(x, y + 3.5, 20, 2).fill(GREEN);56  doc.font("JB-Bold").fontSize(8).fillColor(GREEN)57    .text(txt.toUpperCase(), x + 26, y, { characterSpacing: 1.4, lineBreak: false });58}5960function pageFrame(doc: Doc, page: number, total: number, generated: string) {61  doc.rect(0, 0, W, H).fill(PAPER);62  doc.rect(M, H - 46, W - 2 * M, 1.2).fill(INK);63  doc.font("JB-Reg").fontSize(6.5).fillColor(INK3).text(64    "VRAI-PRIX.COM — RAPPORT DE PARC IMMOBILIER · ESTIMATION STATISTIQUE À TITRE INDICATIF · SIMON-PIERRE BOUCHER · CONTACT@SPBOUCHER.AI",65    M, H - 38, { width: W - 2 * M - 60, characterSpacing: 0.4, lineBreak: false });66  doc.font("JB-Bold").fontSize(7.5).fillColor(INK)67    .text(`${page} / ${total}`, W - M - 40, H - 39, { width: 40, align: "right" });68  doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)69    .text(generated, W - M - 160, H - 30, { width: 160, align: "right" });70}7172function card(doc: Doc, x: number, y: number, w: number, h: number, fill = "#ffffff") {73  doc.roundedRect(x + 3, y + 3, w, h, 8).fill("#e3e1d9");74  doc.roundedRect(x, y, w, h, 8).lineWidth(1.3).fillAndStroke(fill, INK);75}7677function tile(doc: Doc, x: number, y: number, w: number, h: number, k: string, v: string, hero = false) {78  card(doc, x, y, w, h, hero ? INK : "#ffffff");79  doc.font("SG-Bold").fontSize(16).fillColor(hero ? LIME : INK)80    .text(v, x + 12, y + 12, { width: w - 24, height: 22, ellipsis: true, lineBreak: false });81  doc.font("JB-Bold").fontSize(5.6).fillColor(hero ? "rgba(255,81,72,0.7)" : INK3)82    .text(k.toUpperCase(), x + 12, y + h - 16, { width: w - 24, characterSpacing: 0.7, lineBreak: false });83}8485function kvCell(doc: Doc, x: number, y: number, w: number, h: number, k: string, v: string) {86  doc.lineWidth(0.8);87  doc.roundedRect(x, y, w, h, 4).fillAndStroke(SURFACE2, LINE);88  doc.font("JB-Bold").fontSize(5.6).fillColor(INK3)89    .text(k.toUpperCase(), x + 6, y + 5.5, { width: w - 12, characterSpacing: 0.6, height: 8, ellipsis: true });90  doc.font("SG-Bold").fontSize(8.8).fillColor(INK)91    .text(v, x + 6, y + 15.5, { width: w - 12, height: h - 19, ellipsis: true });92  doc.lineWidth(1.3);93}9495function hbars(doc: Doc, x: number, y: number, w: number, rows: [string, number, string][], accentLast = true) {96  const max = Math.max(...rows.map((r) => r[1]), 1);97  rows.forEach(([label, value, txt], i) => {98    const ly = y + i * 19;99    doc.font("JB-Bold").fontSize(7).fillColor(INK).text(label, x, ly + 2, { lineBreak: false });100    const tx = x + 50;101    const tw = w - 50 - 86;102    doc.rect(tx, ly, tw, 11).fill(SURFACE2);103    doc.rect(tx, ly, Math.max(2, (value / max) * tw), 11)104      .fill(accentLast && i === rows.length - 1 ? INK : GREEN);105    doc.font("JB-Bold").fontSize(7).fillColor(INK)106      .text(txt, x + w - 82, ly + 2, { width: 82, align: "right" });107  });108}109110/** Page condensée d'une propriété du parc. */111function propertyPage(doc: Doc, item: UnitEstimate, idx: number, total: number, pageNo: number, pageTotal: number, generated: string) {112  const u = item.unit!;113  const s = u.specs;114  const r = item.result;115  doc.addPage({ size: "LETTER", margin: 0 });116  pageFrame(doc, pageNo, pageTotal, generated);117  doc.rect(0, 0, W, 8).fill(INK);118  doc.rect(0, 8, W, 2.5).fill(LIME);119120  let y = 34;121  // index de propriété122  doc.circle(M + 10, y + 12, 12).lineWidth(1.4).fillAndStroke(GREEN, INK);123  doc.font("JB-Bold").fontSize(10).fillColor(PAPER)124    .text(String(idx + 1), M - 2, y + 7.5, { width: 24, align: "center", lineBreak: false });125  doc.font("JB-Reg").fontSize(7).fillColor(INK3)126    .text(`PROPRIÉTÉ ${idx + 1} / ${total}`, M + 30, y + 2, { characterSpacing: 1 });127  doc.font("SG-Bold").fontSize(14).fillColor(INK)128    .text(`${(u.adresse ?? "").toUpperCase()}${s.apt ? " APP. " + s.apt : ""} · ${(u.municipalite ?? "").toUpperCase()}`,129      M + 30, y + 12, { width: W - 2 * M - 30 });130  y = Math.max(doc.y + 10, y + 44);131132  doc.font("SG-Bold").fontSize(34).fillColor(INK).text(fmt(r.estimate), M, y);133  y = doc.y + 6;134  doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("FOURCHETTE", M, y, { lineBreak: false });135  doc.font("SG-Bold").fontSize(11).fillColor(INK).text(`${fmt(r.low)} → ${fmt(r.high)}`, M, y + 10, { lineBreak: false });136  const confTxt = `CONFIANCE ${r.confidenceLevel} · ${r.confidencePct} %`;137  doc.font("JB-Bold").fontSize(7);138  const cw = doc.widthOfString(confTxt) + 16;139  doc.roundedRect(M + 220, y + 4, cw, 16, 4).lineWidth(1).fillAndStroke(CONF_BG[r.confidenceLevel], INK);140  doc.fillColor(INK).text(confTxt, M + 228, y + 8.5, { lineBreak: false });141  doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("RÔLE 2026", M + 380, y, { lineBreak: false });142  doc.font("SG-Bold").fontSize(11).fillColor(INK).text(fmt(u.valeurRole), M + 380, y + 10, { lineBreak: false });143  y += 34;144145  // fiche compacte146  const rows: [string, string][] = [147    ["Usage", s.cubfLibelle ?? "—"],148    ["Année constr.", u.anneeConstruction ? String(u.anneeConstruction) : "—"],149    ["Aire étages", u.aireEtagesM2 ? `${u.aireEtagesM2} m²` : "—"],150    ["Terrain", u.superficieTerrainM2 ? `${u.superficieTerrainM2} m²` : "—"],151    ["Frontage", s.frontTerrainM ? `${s.frontTerrainM} m` : "—"],152    ["Étages", s.nbEtages != null ? String(s.nbEtages) : "—"],153    ["Logements", u.nbLogements != null ? String(u.nbLogements) : "—"],154    ["Genre", s.genreConstruction ?? "—"],155    ["Lien phys.", s.lienPhysique ?? "—"],156    ["Val. terrain", fmt(s.valeurTerrain)],157    ["Val. bâtiment", fmt(s.valeurBatiment)],158    ["Matricule", s.matricule ?? "—"],159  ];160  kicker(doc, "Fiche du registre", M, y);161  y += 14;162  const cw2 = (W - 2 * M - 3 * 8) / 4;163  rows.forEach(([k, v], i) => {164    kvCell(doc, M + (i % 4) * (cw2 + 8), y + Math.floor(i / 4) * 36, cw2, 30, k, v);165  });166  y += 3 * 36 + 14;167168  // historique169  kicker(doc, "Valeur estimée 2021 → 2026", M, y);170  y += 16;171  card(doc, M, y, W - 2 * M, u.history.length * 19 + 20);172  hbars(doc, M + 14, y + 12, W - 2 * M - 28,173    u.history.map((h) => [String(h.year), h.value ?? 0, fmt(h.value)]));174  y += u.history.length * 19 + 34;175176  // top comparables177  kicker(doc, `Meilleurs comparables (${Math.min(5, r.comps.length)})`, M, y);178  y += 14;179  r.comps.slice(0, 5).forEach((c, i) => {180    const ly = y + i * 17;181    if (i % 2 === 0) doc.rect(M, ly - 2, W - 2 * M, 16).fill(SURFACE2);182    doc.font("SG-Bold").fontSize(7.5).fillColor(INK)183      .text(`${i + 1}. ${c.street ?? ""}, ${c.city ?? ""}`, M + 6, ly, { width: 300, height: 9, ellipsis: true, lineBreak: false });184    doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)185      .text(`${c.date} · ${c.distanceM < 1000 ? Math.round(c.distanceM) + " m" : (c.distanceM / 1000).toFixed(1) + " km"}`,186        M + 316, ly + 1, { lineBreak: false });187    doc.font("SG-Bold").fontSize(8).fillColor(INK)188      .text(fmt(Math.round(c.adjustedPrice)), W - M - 90, ly, { width: 84, align: "right", lineBreak: false });189  });190}191192export async function buildPortfolioReport(pf: PortfolioResult): Promise<Buffer> {193  const { items, aggregates: a } = pf;194  const generated = new Date().toISOString().slice(0, 16).replace("T", " ");195  const pageTotal = 1 + items.length;196197  const doc = new PDFDocument({ size: "LETTER", margin: 0, info: { Title: "Vrai-Prix — Rapport de parc immobilier" } });198  doc.registerFont("SG-Bold", F("SpaceGrotesk-Bold.ttf"));199  doc.registerFont("SG-Med", F("SpaceGrotesk-Medium.ttf"));200  doc.registerFont("JB-Reg", F("JetBrainsMono-Regular.ttf"));201  doc.registerFont("JB-Bold", F("JetBrainsMono-Bold.ttf"));202  doc.registerFont("Inter", F("Inter-Regular.ttf"));203204  const chunks: Buffer[] = [];205  doc.on("data", (c: Buffer) => chunks.push(c));206  const done = new Promise<Buffer>((res) => doc.on("end", () => res(Buffer.concat(chunks))));207208  /* ------------------------------ COUVERTURE ------------------------------ */209  pageFrame(doc, 1, pageTotal, generated);210  doc.rect(0, 0, W, 110).fill(INK);211  logo(doc, M, 32);212  doc.font("JB-Reg").fontSize(7).fillColor(LIME)213    .text("RAPPORT DE PARC IMMOBILIER · QUÉBEC", M, 70, { characterSpacing: 1.6, lineBreak: false });214  doc.font("JB-Reg").fontSize(7).fillColor("#9aa39c")215    .text(`${a.count} PROPRIÉTÉS`, W - M - 200, 38, { width: 200, align: "right" })216    .text(`GÉNÉRÉ LE ${generated}`, W - M - 200, 50, { width: 200, align: "right" });217  doc.rect(0, 110, W, 3).fill(LIME);218219  let y = 134;220  kicker(doc, "Valeur totale estimée du parc", M, y);221  y += 16;222  doc.font("SG-Bold").fontSize(44).fillColor(INK).text(fmt(a.totalEstimate), M, y);223  y = doc.y + 8;224  doc.font("JB-Bold").fontSize(6.5).fillColor(INK3).text("FOURCHETTE CUMULÉE", M, y, { lineBreak: false });225  doc.font("SG-Bold").fontSize(12).fillColor(INK).text(`${fmt(a.totalLow)} → ${fmt(a.totalHigh)}`, M, y + 10, { lineBreak: false });226  const confTxt = `CONFIANCE PONDÉRÉE ${a.confidenceLevel} · ${a.confidencePct} %`;227  doc.font("JB-Bold").fontSize(7.5);228  const cw = doc.widthOfString(confTxt) + 20;229  doc.roundedRect(M + 260, y + 2, cw, 18, 4).lineWidth(1).fillAndStroke(CONF_BG[a.confidenceLevel], INK);230  doc.fillColor(INK).text(confTxt, M + 270, y + 7.5, { lineBreak: false });231  y += 38;232233  // tuiles234  const tiles: [string, string, boolean][] = [235    ["Propriétés", String(a.count), true],236    ["Évaluation municipale", fmt(a.totalRole), false],237    ["Écart vs rôle", a.ecartRolePct != null ? `${a.ecartRolePct >= 0 ? "+" : ""}${a.ecartRolePct.toFixed(0)} %` : "—", false],238    ["Croissance 2021→2026", a.growthPct != null ? `${a.growthPct >= 0 ? "+" : ""}${a.growthPct.toFixed(0)} %` : "—", true],239    ["Aire habitable totale", `${a.totalFloorArea.toLocaleString("fr-CA")} m²`, false],240    ["Terrain total", `${a.totalLandArea.toLocaleString("fr-CA")} m²`, false],241    ["Logements", String(a.totalDwellings), false],242    ["Année moyenne", a.avgYearBuilt ? String(a.avgYearBuilt) : "—", false],243  ];244  const tw = (W - 2 * M - 3 * 10) / 4;245  tiles.forEach(([k, v, hero], i) => {246    tile(doc, M + (i % 4) * (tw + 10), y + Math.floor(i / 4) * 58, tw, 50, k, v, hero);247  });248  y += 2 * 58 + 12;249250  // historique du parc251  kicker(doc, "Valeur du parc par année (unités couvertes)", M, y);252  y += 14;253  card(doc, M, y, (W - 2 * M - 12) * 0.58, 6 * 19 + 20);254  hbars(doc, M + 12, y + 12, (W - 2 * M - 12) * 0.58 - 24,255    a.history.map((h) => [String(h.year), h.total, fmt(h.total)]));256257  // répartitions258  const rx = M + (W - 2 * M - 12) * 0.58 + 12;259  const rw = W - M - rx;260  card(doc, rx, y, rw, 6 * 19 + 20);261  doc.font("JB-Bold").fontSize(6.2).fillColor(INK3).text("PAR MUNICIPALITÉ", rx + 12, y + 10, { characterSpacing: 0.8 });262  a.municipalities.slice(0, 3).forEach((m, i) => {263    const ly = y + 22 + i * 15;264    doc.font("SG-Bold").fontSize(7.5).fillColor(INK).text(m.name, rx + 12, ly, { width: rw - 100, height: 9, ellipsis: true, lineBreak: false });265    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 });266  });267  doc.font("JB-Bold").fontSize(6.2).fillColor(INK3).text("PAR TYPE", rx + 12, y + 72, { characterSpacing: 0.8 });268  a.types.slice(0, 3).forEach((tp, i) => {269    const ly = y + 84 + i * 15;270    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 });271    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 });272  });273  y += 6 * 19 + 34;274275  // table des propriétés276  kicker(doc, "Sommaire des propriétés", M, y);277  y += 14;278  items.slice(0, 14).forEach((it, i) => {279    const u = it.unit!;280    const ly = y + i * 17;281    if (i % 2 === 0) doc.rect(M, ly - 2, W - 2 * M, 16).fill(SURFACE2);282    doc.circle(M + 8, ly + 5, 6).lineWidth(0.9).fillAndStroke(GREEN, INK);283    doc.font("JB-Bold").fontSize(6).fillColor(PAPER).text(String(i + 1), M + 2, ly + 2.5, { width: 12, align: "center", lineBreak: false });284    doc.font("SG-Bold").fontSize(7.5).fillColor(INK)285      .text(`${u.adresse ?? ""} · ${u.municipalite ?? ""}`, M + 20, ly, { width: 280, height: 9, ellipsis: true, lineBreak: false });286    doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)287      .text(`CONF. ${it.result.confidenceLevel}`, M + 310, ly + 1, { lineBreak: false });288    doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)289      .text(`RÔLE ${fmt(u.valeurRole)}`, M + 360, ly + 1, { width: 90, lineBreak: false });290    doc.font("SG-Bold").fontSize(8).fillColor(INK)291      .text(fmt(it.result.estimate), W - M - 80, ly, { width: 76, align: "right", lineBreak: false });292  });293  if (items.length > 14) {294    doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)295      .text(`+ ${items.length - 14} autres propriétés — voir pages suivantes`, M, y + 14 * 17 + 2);296  }297298  /* --------------------------- PAGES PROPRIÉTÉS --------------------------- */299  items.forEach((it, i) => propertyPage(doc, it, i, items.length, i + 2, pageTotal, generated));300301  doc.end();302  return done;303}304