SPB Git

Repository Public

report-pro.ts 26.4 KB 464 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/report-pro.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 d'évaluation détaillé — format professionnel (présentation bancaire).44 * Structure calquée sur un rapport d'évaluation : page titre, sommaire exécutif,45 * mandat et portée, définition de la valeur marchande, méthodologie, description46 * de la propriété, grille d'ajustement des comparables, analyse hédonique,47 * réconciliation, hypothèses et conditions limitatives, certification.48 * Ton sobre, encadrés honnêtes : AVM statistique — n'est PAS un rapport OEAQ.49 */50import PDFDocument from "pdfkit";51import path from "path";52import type { UnitEstimate } from "./estimator";5354const INK = "#141814";55const INK2 = "#4d5551";56const INK3 = "#8b928c";57const SURFACE2 = "#faf9f5";58const GREEN = "#9e2a25";59const GREEN_DEEP = "#771f1b";60const LIME = "#ff5148";6162const W = 612;63const H = 792;64const M = 56;65const CW = W - 2 * M;6667const F = (f: string) => path.join(process.cwd(), "assets", "fonts", f);68const fmt = (v: number | null | undefined) =>69  v == null70    ? "—"71    : new Intl.NumberFormat("fr-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(v);72const signed = (v: number) => `${v >= 0 ? "+" : "−"}${fmt(Math.abs(Math.round(v)))}`;73const CONF_TXT: Record<string, string> = {74  A: "Très fiable", B: "Fiable", C: "Indicative", D: "Peu fiable — marché mince",75};7677type Doc = InstanceType<typeof PDFDocument>;7879interface Ctx {80  doc: Doc;81  page: number;82  dossier: string;83  generated: string;84}8586function header(c: Ctx) {87  const { doc } = c;88  doc.font("SG-Bold").fontSize(10).fillColor(INK).text("Vrai", M, 26, { lineBreak: false });89  const w = doc.widthOfString("Vrai");90  doc.rect(M + w + 2, 25, doc.widthOfString("Prix") + 6, 13).fill(INK);91  doc.fillColor(LIME).text("Prix", M + w + 5, 26, { lineBreak: false });92  doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)93    .text("RAPPORT D'ÉVALUATION DÉTAILLÉ — FORMAT PROFESSIONNEL", M + 70, 29, { characterSpacing: 0.8, lineBreak: false });94  doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)95    .text(`DOSSIER ${c.dossier}`, W - M - 160, 29, { width: 160, align: "right" });96  doc.rect(M, 44, CW, 0.8).fill(INK);97}9899function footer(c: Ctx, total: number) {100  const { doc } = c;101  doc.rect(M, H - 52, CW, 0.8).fill(INK);102  doc.font("JB-Reg").fontSize(6).fillColor(INK3).text(103    "ESTIMATION STATISTIQUE AUTOMATISÉE (AVM) — NE CONSTITUE PAS UN RAPPORT D'ÉVALUATION AU SENS DES NORMES DE L'OEAQ · VRAI-PRIX.COM · CONTACT@SPBOUCHER.AI",104    M, H - 44, { width: CW - 50, characterSpacing: 0.3, lineBreak: false });105  doc.font("JB-Bold").fontSize(7).fillColor(INK)106    .text(`${c.page} / ${total}`, W - M - 40, H - 45, { width: 40, align: "right" });107}108109function newPage(c: Ctx, total: number) {110  c.doc.addPage({ size: "LETTER", margin: 0 });111  c.page += 1;112  c.doc.rect(0, 0, W, H).fill("#ffffff");113  header(c);114  footer(c, total);115  return 62; // y de départ116}117118function sectionTitle(c: Ctx, num: string, title: string, y: number): number {119  const { doc } = c;120  doc.font("JB-Bold").fontSize(8).fillColor(GREEN)121    .text(num, M, y + 2, { lineBreak: false });122  doc.font("SG-Bold").fontSize(13).fillColor(INK)123    .text(title.toUpperCase(), M + 30, y, { lineBreak: false });124  doc.rect(M, y + 19, CW, 1.4).fill(INK);125  doc.rect(M, y + 21.5, 60, 2.2).fill(LIME);126  return y + 32;127}128129function para(c: Ctx, txt: string, y: number, opts?: { size?: number; color?: string; width?: number }): number {130  const { doc } = c;131  doc.font("Inter").fontSize(opts?.size ?? 8.6).fillColor(opts?.color ?? INK2)132    .text(txt, M, y, { width: opts?.width ?? CW, lineGap: 2.2, align: "justify" });133  return doc.y + 8;134}135136function kvTable(c: Ctx, rows: [string, string][], y: number, colW = CW): number {137  const { doc } = c;138  const rh = 17;139  rows.forEach(([k, v], i) => {140    const ry = y + i * rh;141    if (i % 2 === 0) doc.rect(M, ry, colW, rh).fill(SURFACE2);142    doc.font("JB-Bold").fontSize(6.6).fillColor(INK3)143      .text(k.toUpperCase(), M + 8, ry + 5, { characterSpacing: 0.5, lineBreak: false });144    doc.font("SG-Bold").fontSize(8.6).fillColor(INK)145      .text(v, M + colW * 0.42, ry + 4, { width: colW * 0.58 - 10, height: 11, ellipsis: true });146  });147  doc.rect(M, y, colW, rows.length * rh).lineWidth(0.9).stroke(INK);148  return y + rows.length * rh + 10;149}150151export async function buildProReport(152  data: UnitEstimate,153  marketIndex: { month: string; idx: number }[]154): Promise<Buffer> {155  const u = data.unit!;156  const s = u.specs;157  const r = data.result;158  const generated = new Date().toISOString().slice(0, 10);159  const dossier = `VP-${u.id.slice(0, 8)}-${generated.replaceAll("-", "")}`;160  const TOTAL = 6;161162  const doc = new PDFDocument({ size: "LETTER", margin: 0, info: { Title: `Rapport d'évaluation détaillé — ${u.adresse ?? ""}` } });163  doc.registerFont("SG-Bold", F("SpaceGrotesk-Bold.ttf"));164  doc.registerFont("SG-Med", F("SpaceGrotesk-Medium.ttf"));165  doc.registerFont("JB-Reg", F("JetBrainsMono-Regular.ttf"));166  doc.registerFont("JB-Bold", F("JetBrainsMono-Bold.ttf"));167  doc.registerFont("Inter", F("Inter-Regular.ttf"));168169  const chunks: Buffer[] = [];170  doc.on("data", (ch: Buffer) => chunks.push(ch));171  const done = new Promise<Buffer>((res) => doc.on("end", () => res(Buffer.concat(chunks))));172  const c: Ctx = { doc, page: 1, dossier, generated };173174  /* ------------------------------- PAGE TITRE ------------------------------- */175  doc.rect(0, 0, W, H).fill("#ffffff");176  doc.rect(0, 0, W, 6).fill(INK);177  doc.rect(0, 6, W, 2).fill(LIME);178  // logo sobre179  doc.font("SG-Bold").fontSize(26).fillColor(INK).text("Vrai", M, 70, { lineBreak: false });180  const lw = doc.widthOfString("Vrai");181  doc.rect(M + lw + 4, 68, doc.widthOfString("Prix") + 14, 32).fill(INK);182  doc.fillColor(LIME).text("Prix", M + lw + 11, 70, { lineBreak: false });183  doc.font("JB-Reg").fontSize(7.5).fillColor(INK3)184    .text("MOTEUR D'ÉVALUATION IMMOBILIÈRE STATISTIQUE · QUÉBEC", M, 108, { characterSpacing: 1.2 });185186  doc.rect(M, 168, CW, 1.4).fill(INK);187  doc.font("SG-Bold").fontSize(30).fillColor(INK)188    .text("RAPPORT D'ÉVALUATION\nDÉTAILLÉ", M, 188, { lineGap: 4 });189  doc.font("Inter").fontSize(10.5).fillColor(INK2)190    .text("Approche par comparaison directe et modélisation hédonique de masse", M, 262);191  doc.rect(M, 288, CW, 1.4).fill(INK);192193  // bloc propriété194  doc.font("JB-Bold").fontSize(7.5).fillColor(INK3).text("PROPRIÉTÉ ÉVALUÉE", M, 318, { characterSpacing: 1.2 });195  doc.font("SG-Bold").fontSize(17).fillColor(INK)196    .text(`${u.adresse ?? ""}${s.apt ? ` app. ${s.apt}` : ""}`, M, 332);197  doc.font("SG-Med").fontSize(12).fillColor(INK2)198    .text(`${u.municipalite ?? ""} (Québec) · Matricule ${s.matricule ?? "—"}`, M, doc.y + 2);199200  // encadré conclusion201  const by = 420;202  doc.roundedRect(M, by, CW, 128, 6).lineWidth(1.6).fillAndStroke(SURFACE2, INK);203  doc.font("JB-Bold").fontSize(7.5).fillColor(GREEN_DEEP)204    .text("CONCLUSION DE LA VALEUR MARCHANDE ESTIMÉE", M + 20, by + 16, { characterSpacing: 1.2 });205  doc.font("SG-Bold").fontSize(38).fillColor(INK).text(fmt(r.estimate), M + 20, by + 32);206  doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("FOURCHETTE (P10-P90)", M + 20, by + 84, { lineBreak: false });207  doc.font("SG-Bold").fontSize(11).fillColor(INK).text(`${fmt(r.low)}  →  ${fmt(r.high)}`, M + 20, by + 96, { lineBreak: false });208  doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("DATE D'EFFET", M + 260, by + 84, { lineBreak: false });209  doc.font("SG-Bold").fontSize(11).fillColor(INK).text(generated, M + 260, by + 96, { lineBreak: false });210  doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("FIABILITÉ", M + 380, by + 84, { lineBreak: false });211  doc.font("SG-Bold").fontSize(11).fillColor(INK)212    .text(`${r.confidenceLevel} · ${r.confidencePct} %`, M + 380, by + 96, { lineBreak: false });213214  // préparé pour / par215  doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("PRÉPARÉ POUR", M, 585, { characterSpacing: 1 });216  doc.rect(M, 610, 220, 0.9).fill(INK2);217  doc.font("Inter").fontSize(7).fillColor(INK3).text("(destinataire / institution financière)", M, 615);218  doc.font("JB-Bold").fontSize(7).fillColor(INK3).text("PRÉPARÉ PAR", M + 300, 585, { characterSpacing: 1 });219  doc.font("SG-Bold").fontSize(10).fillColor(INK).text("Vrai-Prix — moteur d'évaluation statistique", M + 300, 597);220  doc.font("Inter").fontSize(8).fillColor(INK2).text("Simon-Pierre Boucher · contact@spboucher.ai", M + 300, 611);221  doc.font("Inter").fontSize(8).fillColor(INK2).text(`Dossier ${dossier} · Généré le ${generated}`, M + 300, 623);222223  // avis224  doc.roundedRect(M, 668, CW, 54, 5).lineWidth(1).stroke(INK);225  doc.font("JB-Bold").fontSize(6.5).fillColor(INK).text("AVIS IMPORTANT", M + 12, 678, { characterSpacing: 1 });226  doc.font("Inter").fontSize(7.4).fillColor(INK2).text(227    "Ce rapport est produit automatiquement par un modèle d'évaluation de masse (AVM). Il est structuré selon les usages de la " +228    "pratique de l'évaluation afin d'en faciliter la lecture, mais il ne constitue pas un rapport d'évaluation préparé par un " +229    "évaluateur agréé (OEAQ) et aucune inspection de la propriété n'a été effectuée. Voir les hypothèses et conditions limitatives, section 7.",230    M + 12, 689, { width: CW - 24, lineGap: 1.5 });231  footer(c, TOTAL);232233  /* ------------------------- PAGE 2 : SOMMAIRE EXÉCUTIF ------------------------- */234  let y = newPage(c, TOTAL);235  y = sectionTitle(c, "1.", "Sommaire exécutif", y);236  y = kvTable(c, [237    ["Adresse", `${u.adresse ?? ""}${s.apt ? ` app. ${s.apt}` : ""}, ${u.municipalite ?? ""}`],238    ["Identifiant provincial", u.id],239    ["Matricule", s.matricule ?? "—"],240    ["Usage prédominant (CUBF)", `${s.cubf ?? "—"} — ${s.cubfLibelle ?? "—"}`],241    ["Droit évalué (présumé)", "Pleine propriété, libre de toute charge"],242    ["Date d'effet de l'estimation", generated],243    ["Méthodes utilisées", "Comparaison directe (ajustée) et modèle hédonique de masse"],244    ["Valeur estimée", fmt(r.estimate)],245    ["Fourchette P10-P90", `${fmt(r.low)} → ${fmt(r.high)}`],246    ["Indice de fiabilité", `${r.confidenceLevel} (${r.confidencePct} %) — ${CONF_TXT[r.confidenceLevel]}`],247    ["Évaluation municipale (rôle 2026)", fmt(u.valeurRole)],248    ["Écart estimation / rôle", u.valeurRole ? `${((r.estimate / u.valeurRole - 1) * 100).toFixed(1)} %` : "—"],249  ], y);250  y = para(c,251    "La valeur conclue résulte de la réconciliation pondérée de deux approches indépendantes : un modèle hédonique de " +252    `masse entraîné sur environ 690 000 transactions québécoises (pondération ${(r.modelWeight * 100).toFixed(0)} %) et l'analyse de ` +253    `${r.nCompsUsed} ventes comparables récentes situées à proximité du sujet, individuellement ajustées pour les conditions de ` +254    `marché, la superficie habitable et l'âge (pondération ${((1 - r.modelWeight) * 100).toFixed(0)} %). La dispersion des comparables ` +255    `ajustés est de ±${r.compsDispersionPct ?? "—"} %. L'indice de fiabilité intègre le nombre de comparables, leur cohérence et la ` +256    "largeur de la fourchette d'incertitude du modèle.", y);257258  y = sectionTitle(c, "2.", "Mandat, portée et définition de la valeur", y + 4);259  y = para(c,260    "Mandat — Estimer la valeur marchande la plus probable de la propriété identifiée ci-dessus, à la date d'effet, aux fins " +261    "d'information et d'appui à une démarche de financement. Portée — Analyse automatisée des données publiques du rôle " +262    "d'évaluation foncière (MAMH) et des transactions publiées ; aucune inspection, aucune vérification de titres.", y);263  y = para(c,264    "Définition de la valeur marchande — Le prix le plus probable, à la date d'effet, moyennant paiement comptant ou " +265    "conditions équivalentes, pour lequel la propriété devrait se vendre sur un marché concurrentiel et ouvert, dans le cadre " +266    "d'une transaction sans lien de dépendance entre un acheteur et un vendeur prudents et informés, aucune des parties " +267    "n'étant contrainte d'agir et un délai de mise en marché raisonnable étant accordé.", y);268  y = para(c,269    "Approches écartées — L'approche du coût n'est pas appliquée (absence de données fiables sur le coût de remplacement " +270    "déprécié sans inspection). L'approche du revenu n'est pas appliquée (propriété à vocation principalement résidentielle ; " +271    "données de loyers non disponibles dans les sources publiques utilisées).", y);272273  /* --------------------- PAGE 3 : DESCRIPTION DE LA PROPRIÉTÉ --------------------- */274  y = newPage(c, TOTAL);275  y = sectionTitle(c, "3.", "Description de la propriété", y);276  doc.font("SG-Bold").fontSize(9.5).fillColor(INK).text("3.1 Bâtiment", M, y); y += 16;277  y = kvTable(c, [278    ["Année de construction", u.anneeConstruction ? `${u.anneeConstruction}${s.anneeEstimee === "E" ? " (estimée au rôle)" : " (réelle)"}` : "—"],279    ["Aire d'étages (habitable)", u.aireEtagesM2 ? `${u.aireEtagesM2} m² (${Math.round(u.aireEtagesM2 * 10.7639)} pi²)` : "—"],280    ["Nombre d'étages", s.nbEtages != null ? String(s.nbEtages) : "—"],281    ["Genre de construction", s.genreConstruction ?? "—"],282    ["Lien physique", s.lienPhysique ?? "—"],283    ["Nombre de logements", u.nbLogements != null ? String(u.nbLogements) : "—"],284    ["Locaux non résidentiels", s.nbLocauxNonResid != null ? String(s.nbLocauxNonResid) : "—"],285  ], y);286  doc.font("SG-Bold").fontSize(9.5).fillColor(INK).text("3.2 Terrain", M, y); y += 16;287  y = kvTable(c, [288    ["Superficie du terrain", u.superficieTerrainM2 ? `${u.superficieTerrainM2} m² (${Math.round(u.superficieTerrainM2 * 10.7639)} pi²)` : "—"],289    ["Mesure frontale", s.frontTerrainM ? `${s.frontTerrainM} m` : "—"],290    ["Unité de voisinage (rôle)", s.uniteVoisinage || "—"],291    ["Arrondissement", s.arrond || "—"],292  ], y);293  doc.font("SG-Bold").fontSize(9.5).fillColor(INK).text("3.3 Données du rôle d'évaluation", M, y); y += 16;294  y = kvTable(c, [295    ["Valeur du terrain (rôle 2026)", fmt(s.valeurTerrain)],296    ["Valeur du bâtiment (rôle 2026)", fmt(s.valeurBatiment)],297    ["Valeur totale (rôle 2026)", fmt(u.valeurRole)],298    ["Valeur au rôle antérieur", fmt(s.valeurAnterieure)],299    ["Conditions du marché considérées au", s.datCondMarche ?? "—"],300  ], y);301  y = para(c,302    "Les caractéristiques ci-dessus proviennent du rôle d'évaluation foncière en vigueur (source : MAMH, données ouvertes). " +303    "Elles n'ont pas fait l'objet d'une vérification sur place.", y);304305  /* --------------------- PAGE 4 : GRILLE DES COMPARABLES --------------------- */306  y = newPage(c, TOTAL);307  y = sectionTitle(c, "4.", "Approche par comparaison — grille d'ajustement", y);308  const comps = r.comps.slice(0, 4);309  const colW = (CW - 118) / comps.length;310  const rowsG: [string, (ci: number) => string][] = [311    ["Adresse", (i) => `${comps[i].street ?? ""}`],312    ["Municipalité", (i) => comps[i].city ?? "—"],313    ["Date de vente", (i) => comps[i].date],314    ["Prix de vente", (i) => fmt(comps[i].amount)],315    ["Distance du sujet", (i) => comps[i].distanceM < 1000 ? `${Math.round(comps[i].distanceM)} m` : `${(comps[i].distanceM / 1000).toFixed(1)} km`],316    ["Aire d'étages", (i) => comps[i].floorArea ? `${comps[i].floorArea} m²` : "—"],317    ["Année constr.", (i) => comps[i].yearBuilt ? String(comps[i].yearBuilt) : "—"],318    ["Ajust. conditions de marché", (i) => signed(comps[i].adjTime)],319    ["Ajust. superficie", (i) => signed(comps[i].adjArea)],320    ["Ajust. âge", (i) => signed(comps[i].adjAge)],321    ["PRIX AJUSTÉ", (i) => fmt(Math.round(comps[i].adjustedPrice))],322    ["Pondération", (i) => `${(comps[i].weight * 100).toFixed(0)} %`],323  ];324  const rh = 20;325  // en-têtes colonnes326  doc.rect(M, y, 118, rh).fill(INK);327  doc.font("JB-Bold").fontSize(6.4).fillColor("#ffffff").text("ÉLÉMENT", M + 6, y + 7, { lineBreak: false });328  comps.forEach((_, i) => {329    doc.rect(M + 118 + i * colW, y, colW, rh).fillAndStroke(i % 2 ? SURFACE2 : "#ffffff", INK);330    doc.font("JB-Bold").fontSize(6.6).fillColor(GREEN_DEEP)331      .text(`COMPARABLE ${i + 1}`, M + 118 + i * colW + 6, y + 7, { lineBreak: false });332  });333  y += rh;334  rowsG.forEach(([label, get]) => {335    const bold = label === "PRIX AJUSTÉ";336    doc.rect(M, y, 118, rh).fillAndStroke(bold ? LIME : SURFACE2, INK);337    doc.font("JB-Bold").fontSize(6).fillColor(INK)338      .text(label.toUpperCase(), M + 6, y + 7, { width: 108, height: 8, ellipsis: true, lineBreak: false });339    comps.forEach((_, ci) => {340      doc.rect(M + 118 + ci * colW, y, colW, rh).fillAndStroke(bold ? "#f6fbe4" : "#ffffff", INK);341      doc.font(bold ? "SG-Bold" : "Inter").fontSize(bold ? 8.4 : 7.4).fillColor(bold ? INK : INK2)342        .text(get(ci), M + 118 + ci * colW + 6, y + (bold ? 5.5 : 6.5), { width: colW - 12, height: 10, ellipsis: true, lineBreak: false });343    });344    y += rh;345  });346  y += 10;347  y = para(c,348    `${r.nCompsUsed} ventes comparables ont été retenues au total (les ${comps.length} plus pondérées sont détaillées ci-dessus ; la liste ` +349    "complète figure dans le rapport standard). Chaque prix de vente est ajusté : (i) aux conditions actuelles du marché au moyen " +350    "d'un indice mensuel du prix médian au mètre carré du segment, (ii) pour l'écart de superficie habitable à raison de 50 % du " +351    "prix unitaire au m² du comparable, plafonné à ±25 %, et (iii) pour l'écart d'âge à raison de 0,5 % par année, plafonné à ±10 %. " +352    `La médiane pondérée des prix ajustés s'établit à ${fmt(r.compsEstimate)}.`, y);353354  // mini-indice de marché355  if (marketIndex.length > 3) {356    doc.font("SG-Bold").fontSize(9.5).fillColor(INK).text("4.1 Indice des conditions de marché du segment", M, y);357    y += 16;358    const gw = CW, gh = 84;359    doc.roundedRect(M, y, gw, gh, 5).lineWidth(1).fillAndStroke("#ffffff", INK);360    const vals = marketIndex.map((p) => p.idx);361    const mn = Math.min(...vals), mx = Math.max(...vals), span = mx - mn || 1;362    const pts = marketIndex.map((p, i) => [363      M + 14 + (i / (marketIndex.length - 1)) * (gw - 28),364      y + gh - 18 - ((p.idx - mn) / span) * (gh - 36),365    ]);366    doc.moveTo(pts[0][0], pts[0][1]);367    pts.slice(1).forEach(([px, py]) => doc.lineTo(px, py));368    doc.lineWidth(1.8).stroke(GREEN);369    const last = pts[pts.length - 1];370    doc.circle(last[0], last[1], 3).lineWidth(1.2).fillAndStroke(LIME, INK);371    doc.font("JB-Reg").fontSize(6).fillColor(INK3)372      .text(marketIndex[0].month, M + 14, y + gh - 12, { lineBreak: false })373      .text(marketIndex[marketIndex.length - 1].month, M + gw - 60, y + gh - 12, { width: 46, align: "right" });374    doc.font("JB-Reg").fontSize(6).fillColor(INK3)375      .text(`BASE 1,00 = ${marketIndex[marketIndex.length - 1].month} · MÉDIANE $/M² LISSÉE 3 MOIS`, M + 14, y + 8, { characterSpacing: 0.5 });376  }377378  /* ------------------- PAGE 5 : HÉDONIQUE + RÉCONCILIATION ------------------- */379  y = newPage(c, TOTAL);380  y = sectionTitle(c, "5.", "Analyse hédonique de masse", y);381  y = para(c,382    "Un modèle de gradient boosting (LightGBM) est entraîné sur environ 690 000 transactions québécoises (2021-2026) appariées " +383    "au rôle d'évaluation foncière géoréférencé. Dix-huit variables décrivent chaque propriété (dimensions, âge, usage, " +384    "localisation fine, valeurs au rôle, temps). Sur un échantillon réservé de 102 943 ventes jamais vues du modèle, l'erreur " +385    "médiane est de 11,0 % et 72 % des estimations tombent à ±20 % du prix réel (ratio médian 0,995, sans biais systématique — " +386    "validation selon la norme IAAO sur études de ratios). L'incertitude propre à la propriété est quantifiée par deux modèles de " +387    "régression quantile (10e et 90e centiles).", y);388  y = kvTable(c, [389    ["Estimation du modèle hédonique", fmt(r.modelEstimate)],390    ["Intervalle P10-P90 du modèle", `${fmt(r.low)} → ${fmt(r.high)} (recentré)`],391    ["Erreur médiane du modèle (validation)", "11,0 % (MdAPE, holdout aléatoire)"],392  ], y);393394  y = sectionTitle(c, "6.", "Réconciliation et conclusion", y + 4);395  const rh2 = 20;396  const recRows: [string, string, string][] = [397    ["Approche", "Indication de valeur", "Pondération"],398    ["Modèle hédonique de masse", fmt(r.modelEstimate), `${(r.modelWeight * 100).toFixed(0)} %`],399    ["Comparaison directe (médiane pondérée)", fmt(r.compsEstimate), `${((1 - r.modelWeight) * 100).toFixed(0)} %`],400    ["VALEUR CONCLUE", fmt(r.estimate), "100 %"],401  ];402  recRows.forEach(([a, b, cc], i) => {403    const head = i === 0;404    const last = i === recRows.length - 1;405    doc.rect(M, y, CW, rh2).fillAndStroke(head ? INK : last ? LIME : i % 2 ? SURFACE2 : "#ffffff", INK);406    doc.font(head || last ? "JB-Bold" : "Inter").fontSize(head ? 6.8 : last ? 8.6 : 8)407      .fillColor(head ? "#ffffff" : INK)408      .text(head ? a.toUpperCase() : a, M + 8, y + 6, { lineBreak: false });409    doc.text(b, M + CW * 0.52, y + 6, { lineBreak: false });410    doc.text(cc, M + CW * 0.84, y + 6, { lineBreak: false });411    y += rh2;412  });413  y += 10;414  y = para(c,415    `Compte tenu de la qualité de l'appariement des données, du nombre et de la cohérence des comparables (dispersion ±${r.compsDispersionPct ?? "—"} %) ` +416    `et de la performance validée du modèle, la valeur marchande estimée de la propriété au ${generated} est conclue à ` +417    `${fmt(r.estimate)}, à l'intérieur d'une fourchette raisonnable de ${fmt(r.low)} à ${fmt(r.high)}. Indice de fiabilité : ` +418    `${r.confidenceLevel} (${r.confidencePct} %) — ${CONF_TXT[r.confidenceLevel]}.`, y);419420  doc.font("SG-Bold").fontSize(9.5).fillColor(INK).text("6.1 Évolution de la valeur estimée (2021-2026)", M, y);421  y += 16;422  const hist = u.history.filter((h) => h.value != null);423  y = kvTable(c, hist.map((h) => [String(h.year), fmt(h.value)] as [string, string]), y, CW * 0.6);424425  /* ------------------- PAGE 6 : CONDITIONS + CERTIFICATION ------------------- */426  y = newPage(c, TOTAL);427  y = sectionTitle(c, "7.", "Hypothèses et conditions limitatives", y);428  const conds = [429    "Le présent rapport est généré automatiquement par le moteur d'évaluation statistique Vrai-Prix (modèle d'évaluation de masse, AVM). Il ne constitue pas un rapport d'évaluation au sens des normes de pratique professionnelle de l'Ordre des évaluateurs agréés du Québec (OEAQ) et ne peut être présenté comme tel.",430    "Aucune inspection physique de la propriété n'a été effectuée. L'état d'entretien, la qualité des finis, les rénovations, les dépendances et tout vice apparent ou caché ne sont pas considérés.",431    "Les caractéristiques utilisées proviennent du rôle d'évaluation foncière (MAMH, données ouvertes) et de transactions publiées. Leur exactitude et leur mise à jour ne sont pas garanties.",432    "Le droit évalué est présumé être la pleine propriété, libre de toute hypothèque, servitude, charge ou restriction inhabituelle. Aucune vérification de titres n'a été réalisée.",433    "La conformité aux lois, règlements de zonage et permis est présumée. Aucune étude environnementale n'a été effectuée ; la propriété est présumée exempte de contamination.",434    "La valeur conclue vaut à la date d'effet uniquement. Les marchés immobiliers évoluent ; l'estimation ne doit pas être utilisée à une autre date.",435    "La fourchette P10-P90 et l'indice de fiabilité font partie intégrante de la conclusion et doivent être communiqués avec elle.",436    "Ce rapport est destiné au destinataire indiqué en page titre, aux fins d'information et d'appui à une démarche de financement. Toute autre utilisation ou distribution engage la seule responsabilité de l'utilisateur.",437    "Pour une décision de financement finale, une confirmation par un évaluateur agréé (OEAQ) mandaté par l'institution financière est recommandée.",438  ];439  conds.forEach((txt, i) => {440    doc.font("JB-Bold").fontSize(7).fillColor(GREEN).text(`7.${i + 1}`, M, y + 1, { lineBreak: false });441    doc.font("Inter").fontSize(7.9).fillColor(INK2)442      .text(txt, M + 26, y, { width: CW - 26, lineGap: 1.6, align: "justify" });443    y = doc.y + 6;444  });445446  y = sectionTitle(c, "8.", "Attestation", y + 2);447  y = para(c,448    "J'atteste que les données, méthodes et pondérations décrites dans ce rapport sont celles réellement employées par le moteur " +449    "Vrai-Prix pour produire la conclusion de valeur ; que la méthodologie complète, ses métriques de validation et ses limites " +450    "sont publiées à vrai-prix.com/methodologie ; et que ni Vrai-Prix ni son exploitant n'ont d'intérêt présent ou futur dans la " +451    "propriété évaluée, ni de lien de dépendance avec les parties à une éventuelle transaction.", y);452  y += 14;453  doc.rect(M, y + 26, 200, 0.9).fill(INK);454  doc.font("SG-Bold").fontSize(10).fillColor(INK).text("Vrai-Prix", M, y + 32);455  doc.font("Inter").fontSize(8).fillColor(INK2)456    .text("Simon-Pierre Boucher · contact@spboucher.ai", M, y + 46)457    .text(`Dossier ${dossier} · ${generated}`, M, y + 58);458  doc.font("JB-Reg").fontSize(6.5).fillColor(INK3)459    .text("ANNEXE DISPONIBLE : RAPPORT STANDARD (PLAN DES COMPARABLES, LISTE COMPLÈTE DES VENTES) — VRAI-PRIX.COM", M, y + 82, { characterSpacing: 0.5 });460461  doc.end();462  return done;463}464
Files main
Menu

Theme