SPB Git

spb/valoplex Public

ValoPlex — moteur d'évaluation spécialisé pour les plex au Québec, petit frère de Vrai-Prix.

TypeScript 90.3% Python 7.1% CSS 2.5%
14.9 KB · 309 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é ValoPlex.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 = "#b25f16";16const LIME = "#ff9f45";17const LIME_SOFT = "#ffedd9";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("Valo", x, y, { lineBreak: false });43  const w = doc.widthOfString("Valo");44  const bx = x + w + 4 * scale;45  doc.save();46  doc.rotate(-3, { origin: [bx, y + 12 * scale] });47  const bw = doc.widthOfString("Plex") + 12 * scale;48  doc.roundedRect(bx, y - 3 * scale, bw, 30 * scale, 5 * scale).fill(LIME);49  doc.fillColor(INK).text("Plex", 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    "WWW.VALOPLEX.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,159,69,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  if (u.nbLogements && u.nbLogements >= 2) {134    doc.font("JB-Bold").fontSize(7.5).fillColor("#b25f16")135      .text(`${u.nbLogements} PORTES · ${fmt(Math.round(r.estimate / u.nbLogements))} / PORTE`,136        M + 250, y + 14, { characterSpacing: 0.8, lineBreak: false });137  }138  y = doc.y + 6;139  doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("FOURCHETTE", M, y, { lineBreak: false });140  doc.font("SG-Bold").fontSize(11).fillColor(INK).text(`${fmt(r.low)} → ${fmt(r.high)}`, M, y + 10, { lineBreak: false });141  const confTxt = `CONFIANCE ${r.confidenceLevel} · ${r.confidencePct} %`;142  doc.font("JB-Bold").fontSize(7);143  const cw = doc.widthOfString(confTxt) + 16;144  doc.roundedRect(M + 220, y + 4, cw, 16, 4).lineWidth(1).fillAndStroke(CONF_BG[r.confidenceLevel], INK);145  doc.fillColor(INK).text(confTxt, M + 228, y + 8.5, { lineBreak: false });146  doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("RÔLE 2026", M + 380, y, { lineBreak: false });147  doc.font("SG-Bold").fontSize(11).fillColor(INK).text(fmt(u.valeurRole), M + 380, y + 10, { lineBreak: false });148  y += 34;149150  // fiche compacte151  const rows: [string, string][] = [152    ["Usage", s.cubfLibelle ?? "—"],153    ["Année constr.", u.anneeConstruction ? String(u.anneeConstruction) : "—"],154    ["Aire étages", u.aireEtagesM2 ? `${u.aireEtagesM2} m²` : "—"],155    ["Terrain", u.superficieTerrainM2 ? `${u.superficieTerrainM2} m²` : "—"],156    ["Frontage", s.frontTerrainM ? `${s.frontTerrainM} m` : "—"],157    ["Étages", s.nbEtages != null ? String(s.nbEtages) : "—"],158    ["Logements", u.nbLogements != null ? String(u.nbLogements) : "—"],159    ["Genre", s.genreConstruction ?? "—"],160    ["Lien phys.", s.lienPhysique ?? "—"],161    ["Val. terrain", fmt(s.valeurTerrain)],162    ["Val. bâtiment", fmt(s.valeurBatiment)],163    ["Matricule", s.matricule ?? "—"],164  ];165  kicker(doc, "Fiche du registre", M, y);166  y += 14;167  const cw2 = (W - 2 * M - 3 * 8) / 4;168  rows.forEach(([k, v], i) => {169    kvCell(doc, M + (i % 4) * (cw2 + 8), y + Math.floor(i / 4) * 36, cw2, 30, k, v);170  });171  y += 3 * 36 + 14;172173  // historique174  kicker(doc, "Valeur estimée 2021 → 2026", M, y);175  y += 16;176  card(doc, M, y, W - 2 * M, u.history.length * 19 + 20);177  hbars(doc, M + 14, y + 12, W - 2 * M - 28,178    u.history.map((h) => [String(h.year), h.value ?? 0, fmt(h.value)]));179  y += u.history.length * 19 + 34;180181  // top comparables182  kicker(doc, `Meilleurs comparables (${Math.min(5, r.comps.length)})`, M, y);183  y += 14;184  r.comps.slice(0, 5).forEach((c, i) => {185    const ly = y + i * 17;186    if (i % 2 === 0) doc.rect(M, ly - 2, W - 2 * M, 16).fill(SURFACE2);187    doc.font("SG-Bold").fontSize(7.5).fillColor(INK)188      .text(`${i + 1}. ${c.street ?? ""}, ${c.city ?? ""}`, M + 6, ly, { width: 300, height: 9, ellipsis: true, lineBreak: false });189    doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)190      .text(`${c.date} · ${c.distanceM < 1000 ? Math.round(c.distanceM) + " m" : (c.distanceM / 1000).toFixed(1) + " km"}`,191        M + 316, ly + 1, { lineBreak: false });192    doc.font("SG-Bold").fontSize(8).fillColor(INK)193      .text(fmt(Math.round(c.adjustedPrice)), W - M - 90, ly, { width: 84, align: "right", lineBreak: false });194  });195}196197export async function buildPortfolioReport(pf: PortfolioResult): Promise<Buffer> {198  const { items, aggregates: a } = pf;199  const generated = new Date().toISOString().slice(0, 16).replace("T", " ");200  const pageTotal = 1 + items.length;201202  const doc = new PDFDocument({ size: "LETTER", margin: 0, info: { Title: "ValoPlex — Rapport de parc immobilier" } });203  doc.registerFont("SG-Bold", F("SpaceGrotesk-Bold.ttf"));204  doc.registerFont("SG-Med", F("SpaceGrotesk-Medium.ttf"));205  doc.registerFont("JB-Reg", F("JetBrainsMono-Regular.ttf"));206  doc.registerFont("JB-Bold", F("JetBrainsMono-Bold.ttf"));207  doc.registerFont("Inter", F("Inter-Regular.ttf"));208209  const chunks: Buffer[] = [];210  doc.on("data", (c: Buffer) => chunks.push(c));211  const done = new Promise<Buffer>((res) => doc.on("end", () => res(Buffer.concat(chunks))));212213  /* ------------------------------ COUVERTURE ------------------------------ */214  pageFrame(doc, 1, pageTotal, generated);215  doc.rect(0, 0, W, 110).fill(INK);216  logo(doc, M, 32);217  doc.font("JB-Reg").fontSize(7).fillColor(LIME)218    .text("RAPPORT DE PARC IMMOBILIER · QUÉBEC", M, 70, { characterSpacing: 1.6, lineBreak: false });219  doc.font("JB-Reg").fontSize(7).fillColor("#9aa39c")220    .text(`${a.count} PROPRIÉTÉS`, W - M - 200, 38, { width: 200, align: "right" })221    .text(`GÉNÉRÉ LE ${generated}`, W - M - 200, 50, { width: 200, align: "right" });222  doc.rect(0, 110, W, 3).fill(LIME);223224  let y = 134;225  kicker(doc, "Valeur totale estimée du parc", M, y);226  y += 16;227  doc.font("SG-Bold").fontSize(44).fillColor(INK).text(fmt(a.totalEstimate), M, y);228  y = doc.y + 8;229  doc.font("JB-Bold").fontSize(6.5).fillColor(INK3).text("FOURCHETTE CUMULÉE", M, y, { lineBreak: false });230  doc.font("SG-Bold").fontSize(12).fillColor(INK).text(`${fmt(a.totalLow)} → ${fmt(a.totalHigh)}`, M, y + 10, { lineBreak: false });231  const confTxt = `CONFIANCE PONDÉRÉE ${a.confidenceLevel} · ${a.confidencePct} %`;232  doc.font("JB-Bold").fontSize(7.5);233  const cw = doc.widthOfString(confTxt) + 20;234  doc.roundedRect(M + 260, y + 2, cw, 18, 4).lineWidth(1).fillAndStroke(CONF_BG[a.confidenceLevel], INK);235  doc.fillColor(INK).text(confTxt, M + 270, y + 7.5, { lineBreak: false });236  y += 38;237238  // tuiles239  const tiles: [string, string, boolean][] = [240    ["Propriétés", String(a.count), true],241    ["Évaluation municipale", fmt(a.totalRole), false],242    ["Écart vs rôle", a.ecartRolePct != null ? `${a.ecartRolePct >= 0 ? "+" : ""}${a.ecartRolePct.toFixed(0)} %` : "—", false],243    ["Croissance 2021→2026", a.growthPct != null ? `${a.growthPct >= 0 ? "+" : ""}${a.growthPct.toFixed(0)} %` : "—", true],244    ["Aire habitable totale", `${a.totalFloorArea.toLocaleString("fr-CA")} m²`, false],245    ["Terrain total", `${a.totalLandArea.toLocaleString("fr-CA")} m²`, false],246    ["Logements", String(a.totalDwellings), false],247    ["Année moyenne", a.avgYearBuilt ? String(a.avgYearBuilt) : "—", false],248  ];249  const tw = (W - 2 * M - 3 * 10) / 4;250  tiles.forEach(([k, v, hero], i) => {251    tile(doc, M + (i % 4) * (tw + 10), y + Math.floor(i / 4) * 58, tw, 50, k, v, hero);252  });253  y += 2 * 58 + 12;254255  // historique du parc256  kicker(doc, "Valeur du parc par année (unités couvertes)", M, y);257  y += 14;258  card(doc, M, y, (W - 2 * M - 12) * 0.58, 6 * 19 + 20);259  hbars(doc, M + 12, y + 12, (W - 2 * M - 12) * 0.58 - 24,260    a.history.map((h) => [String(h.year), h.total, fmt(h.total)]));261262  // répartitions263  const rx = M + (W - 2 * M - 12) * 0.58 + 12;264  const rw = W - M - rx;265  card(doc, rx, y, rw, 6 * 19 + 20);266  doc.font("JB-Bold").fontSize(6.2).fillColor(INK3).text("PAR MUNICIPALITÉ", rx + 12, y + 10, { characterSpacing: 0.8 });267  a.municipalities.slice(0, 3).forEach((m, i) => {268    const ly = y + 22 + i * 15;269    doc.font("SG-Bold").fontSize(7.5).fillColor(INK).text(m.name, rx + 12, ly, { width: rw - 100, height: 9, ellipsis: true, lineBreak: false });270    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 });271  });272  doc.font("JB-Bold").fontSize(6.2).fillColor(INK3).text("PAR TYPE", rx + 12, y + 72, { characterSpacing: 0.8 });273  a.types.slice(0, 3).forEach((tp, i) => {274    const ly = y + 84 + i * 15;275    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 });276    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 });277  });278  y += 6 * 19 + 34;279280  // table des propriétés281  kicker(doc, "Sommaire des propriétés", M, y);282  y += 14;283  items.slice(0, 14).forEach((it, i) => {284    const u = it.unit!;285    const ly = y + i * 17;286    if (i % 2 === 0) doc.rect(M, ly - 2, W - 2 * M, 16).fill(SURFACE2);287    doc.circle(M + 8, ly + 5, 6).lineWidth(0.9).fillAndStroke(GREEN, INK);288    doc.font("JB-Bold").fontSize(6).fillColor(PAPER).text(String(i + 1), M + 2, ly + 2.5, { width: 12, align: "center", lineBreak: false });289    doc.font("SG-Bold").fontSize(7.5).fillColor(INK)290      .text(`${u.adresse ?? ""} · ${u.municipalite ?? ""}`, M + 20, ly, { width: 280, height: 9, ellipsis: true, lineBreak: false });291    doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)292      .text(`CONF. ${it.result.confidenceLevel}`, M + 310, ly + 1, { lineBreak: false });293    doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)294      .text(`RÔLE ${fmt(u.valeurRole)}`, M + 360, ly + 1, { width: 90, lineBreak: false });295    doc.font("SG-Bold").fontSize(8).fillColor(INK)296      .text(fmt(it.result.estimate), W - M - 80, ly, { width: 76, align: "right", lineBreak: false });297  });298  if (items.length > 14) {299    doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)300      .text(`+ ${items.length - 14} autres propriétés — voir pages suivantes`, M, y + 14 * 17 + 2);301  }302303  /* --------------------------- PAGES PROPRIÉTÉS --------------------------- */304  items.forEach((it, i) => propertyPage(doc, it, i, items.length, i + 2, pageTotal, generated));305306  doc.end();307  return done;308}309