SPB Git

Repository Public

report-cost.ts 44.5 KB 659 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/report-cost.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/vrai-prix11 * Created          : 2026-09-0812 * Last Modified    : 2026-09-0813 *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 « Méthode du coût »  — vectoriel (pdfkit), même44 * branding que report.ts : bandeau encre, logo Vrai-Prix, cartes, filets,45 * format Lettre. Chaque nombre du rapport vient du moteur (CostEstimate) ;46 * la nature de chaque prix est marquée : ● observé/officiel · ◐ calculé ·47 * ○ indexé · ◇ référence interne (hypothèse).48 */49import PDFDocument from "pdfkit";50import path from "path";51import type { CostEstimate, PriceKind } from "./cost/types";52import { INDIRECT_LABELS, QUALITIES, BUILDING_TYPES, tradeLabel } from "./cost/taxonomy";53import { UNIT_LABELS } from "./cost/units";5455const INK = "#141814";56const INK2 = "#4d5551";57const INK3 = "#8b928c";58const PAPER = "#f5f3ee";59const SURFACE2 = "#faf9f5";60const GREEN = "#9e2a25"; // bordeaux Vrai-Prix (--green)61const GREEN_DEEP = "#771f1b";62const LIME = "#ff5148"; // rouge vif Vrai-Prix (--accent-bright)63const LIME_SOFT = "#ffe3e0";64const AMBER_SOFT = "#fdf3e2";65const DANGER = "#b3423a";66const DANGER_SOFT = "#fbe9e7";67const LINE = "#dedcd4";6869const W = 612;70const H = 792;71const M = 44;72const BOTTOM = H - 62; // limite basse du contenu (au-dessus du pied de page)7374const F = (f: string) => path.join(process.cwd(), "assets", "fonts", f);7576const fmt = (v: number | null | undefined) =>77  v == null || !Number.isFinite(v) ? "—" : new Intl.NumberFormat("fr-CA", { style: "currency", currency: "CAD", maximumFractionDigits: 0 }).format(v);78const fmt2 = (v: number | null | undefined) =>79  v == null || !Number.isFinite(v) ? "—" : new Intl.NumberFormat("fr-CA", { style: "currency", currency: "CAD", minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(v);80const num = (v: number | null | undefined, d = 0) =>81  v == null || !Number.isFinite(v) ? "—" : v.toLocaleString("fr-CA", { maximumFractionDigits: d, minimumFractionDigits: 0 });82const pct = (v: number | null | undefined, d = 1) => (v == null || !Number.isFinite(v) ? "—" : `${v.toLocaleString("fr-CA", { maximumFractionDigits: d })} %`);83const neg = (v: number) => (v > 0 ? `−${fmt(v)}` : fmt(0));8485const KIND_ICON: Record<PriceKind, string> = { observed: "●", official: "●", derived: "◐", indexed: "○", reference: "◇", assumption: "◇" };86const KIND_TXT: Record<PriceKind, string> = { observed: "observé", official: "officiel", derived: "calculé", indexed: "indexé", reference: "référence (hypothèse)", assumption: "hypothèse" };87const SRC_TXT: Record<string, string> = { MAMH: "rôle MAMH", user: "saisi", AI: "inféré par IA", derived: "dérivé", assumed: "supposé", listing: "annonce", cadastral: "cadastre" };88const CONF_BG: Record<string, string> = { A: LIME, B: LIME_SOFT, C: AMBER_SOFT, D: DANGER_SOFT };89const CONF_TXT: Record<string, string> = { A: "Très fiable", B: "Fiable", C: "Indicative", D: "Peu fiable" };9091type Doc = InstanceType<typeof PDFDocument>;9293/* ------------------------------------------------------------- primitives */9495/** Mot-symbole Vrai-Prix (identique à report.ts) : « Vrai » papier + « Prix » sur pastille rouge inclinée. */96function logo(doc: Doc, x: number, y: number, scale = 1) {97  doc.save();98  doc.font("SG-Bold").fontSize(24 * scale);99  doc.fillColor(PAPER).text("Vrai", x, y, { lineBreak: false });100  const w = doc.widthOfString("Vrai");101  const bx = x + w + 4 * scale;102  doc.save();103  doc.rotate(-3, { origin: [bx, y + 12 * scale] });104  const bw = doc.widthOfString("Prix") + 12 * scale;105  doc.roundedRect(bx, y - 3 * scale, bw, 30 * scale, 5 * scale).fill(LIME);106  doc.fillColor(INK).text("Prix", bx + 6 * scale, y, { lineBreak: false });107  doc.restore();108  doc.restore();109}110111function kicker(doc: Doc, txt: string, x: number, y: number, color = GREEN) {112  doc.rect(x, y + 3.5, 20, 2).fill(color);113  doc.font("JB-Bold").fontSize(8).fillColor(color).text(txt.toUpperCase(), x + 26, y, { characterSpacing: 1.4, lineBreak: false, width: W - 2 * M - 26, height: 12, ellipsis: true });114}115116function pageBg(doc: Doc) {117  doc.rect(0, 0, W, H).fill(PAPER);118}119120function pageFooter(doc: Doc, page: number, total: number, generated: string) {121  doc.rect(M, H - 46, W - 2 * M, 1.2).fill(INK);122  doc.font("JB-Reg").fontSize(6.5).fillColor(INK3).text(123    "VRAI-PRIX.COM · MÉTHODE DU COÛT — ESTIMATION STATISTIQUE À TITRE INDICATIF, NI SOUMISSION NI ÉVALUATION CERTIFIÉE (OEAQ)",124    M, H - 39, { width: W - 2 * M - 60, characterSpacing: 0.3, lineBreak: false, height: 9, ellipsis: true }125  );126  doc.font("JB-Reg").fontSize(6.5).fillColor(INK3).text("SIMON-PIERRE BOUCHER · CONTACT@SPBOUCHER.AI", M, H - 30, { width: W - 2 * M - 60, characterSpacing: 0.4, lineBreak: false });127  doc.font("JB-Bold").fontSize(7.5).fillColor(INK).text(`${page} / ${total}`, W - M - 40, H - 39, { width: 40, align: "right" });128  doc.font("JB-Reg").fontSize(6.5).fillColor(INK3).text(generated, W - M - 160, H - 30, { width: 160, align: "right" });129}130131function card(doc: Doc, x: number, y: number, w: number, h: number, opts?: { shadow?: boolean; fill?: string }) {132  if (opts?.shadow !== false) doc.roundedRect(x + 3.5, y + 3.5, w, h, 8).fill("#e3e1d9");133  doc.roundedRect(x, y, w, h, 8).lineWidth(1.3).fillAndStroke(opts?.fill ?? "#ffffff", INK);134}135136function kvCell(doc: Doc, x: number, y: number, w: number, h: number, k: string, v: string) {137  doc.lineWidth(0.8);138  doc.roundedRect(x, y, w, h, 4).fillAndStroke(SURFACE2, LINE);139  doc.font("JB-Bold").fontSize(5.8).fillColor(INK3).text(k.toUpperCase(), x + 7, y + 6, { width: w - 14, characterSpacing: 0.7, height: 8, ellipsis: true, lineBreak: false });140  doc.font("SG-Bold").fontSize(7.4).fillColor(INK).text(v, x + 7, y + 15.5, { width: w - 14, height: h - 18, ellipsis: true, lineGap: -0.5 });141  doc.lineWidth(1.3);142}143144/* -------------------------------------------------------- mise en page */145146class Layout {147  y = 34;148  constructor(readonly doc: Doc) {}149  newPage() {150    this.doc.addPage({ size: "LETTER", margin: 0 });151    pageBg(this.doc);152    this.doc.rect(0, 0, W, 8).fill(INK);153    this.doc.rect(0, 8, W, 2.5).fill(LIME);154    this.y = 34;155  }156  /** garantit `h` points disponibles, sinon nouvelle page */157  ensure(h: number) {158    if (this.y + h > BOTTOM) this.newPage();159  }160  section(title: string) {161    this.ensure(60);162    kicker(this.doc, title, M, this.y);163    this.y += 18;164  }165  para(txt: string, opts: { size?: number; color?: string; font?: string; gap?: number } = {}) {166    const d = this.doc;167    d.font(opts.font ?? "Inter").fontSize(opts.size ?? 8);168    const h = d.heightOfString(txt, { width: W - 2 * M, lineGap: 1.4 });169    this.ensure(h + 4);170    d.fillColor(opts.color ?? INK2).text(txt, M, this.y, { width: W - 2 * M, lineGap: 1.4 });171    this.y += h + (opts.gap ?? 6);172  }173  bullet(txt: string) {174    const d = this.doc;175    d.font("Inter").fontSize(7.8);176    const h = d.heightOfString(txt, { width: W - 2 * M - 14, lineGap: 1.2 });177    this.ensure(h + 3);178    d.rect(M + 2, this.y + 3.5, 4, 4).fill(GREEN);179    d.fillColor(INK2).text(txt, M + 14, this.y, { width: W - 2 * M - 14, lineGap: 1.2 });180    this.y += h + 3;181  }182  /** tableau avec en-tête répété à chaque saut de page */183  table(cols: { h: string; w: number; align?: "left" | "right"; mono?: boolean }[], rows: string[][], opts: { rowH?: number; total?: string[]; highlight?: (i: number) => boolean } = {}) {184    const d = this.doc;185    const rowH = opts.rowH ?? 14;186    const x0 = M;187    const totalW = cols.reduce((s, c) => s + c.w, 0);188    const scale = (W - 2 * M) / totalW;189    const ws = cols.map((c) => c.w * scale);190    const header = () => {191      this.ensure(rowH + 4);192      d.rect(x0, this.y, W - 2 * M, rowH).fill(INK);193      let x = x0;194      cols.forEach((c, i) => {195        d.font("JB-Bold").fontSize(6.2).fillColor(PAPER).text(c.h.toUpperCase(), x + 5, this.y + 4.2, { width: ws[i] - 10, align: c.align ?? "left", lineBreak: false, height: rowH, ellipsis: true, characterSpacing: 0.4 });196        x += ws[i];197      });198      this.y += rowH;199    };200    header();201    rows.forEach((row, ri) => {202      if (this.y + rowH > BOTTOM) { this.newPage(); header(); }203      const hl = opts.highlight?.(ri);204      if (hl) d.rect(x0, this.y, W - 2 * M, rowH).fill(LIME_SOFT);205      else if (ri % 2 === 1) d.rect(x0, this.y, W - 2 * M, rowH).fill(SURFACE2);206      let x = x0;207      cols.forEach((c, i) => {208        d.font(hl ? "SG-Bold" : c.mono ? "JB-Reg" : "Inter").fontSize(c.mono ? 6.6 : 7.2).fillColor(INK)209          .text(row[i] ?? "", x + 5, this.y + 3.6, { width: ws[i] - 10, align: c.align ?? "left", lineBreak: false, height: rowH, ellipsis: true });210        x += ws[i];211      });212      d.moveTo(x0, this.y + rowH).lineTo(W - M, this.y + rowH).lineWidth(0.4).stroke(LINE);213      this.y += rowH;214    });215    if (opts.total) {216      if (this.y + rowH + 2 > BOTTOM) { this.newPage(); header(); }217      d.rect(x0, this.y, W - 2 * M, rowH + 2).fill(INK);218      let x = x0;219      cols.forEach((c, i) => {220        d.font("SG-Bold").fontSize(7.4).fillColor(PAPER).text(opts.total![i] ?? "", x + 5, this.y + 4.2, { width: ws[i] - 10, align: c.align ?? "left", lineBreak: false, height: rowH, ellipsis: true });221        x += ws[i];222      });223      this.y += rowH + 2;224    }225    this.y += 8;226  }227  gap(h = 8) { this.y += h; }228}229230/* -------------------------------------------------------------- libellés */231232const BASEMENT: Record<string, string> = { none: "aucun (dalle)", crawl: "vide sanitaire", unfinished: "non fini", partial: "partiellement fini", finished: "fini", walkout: "fini, sortie de plain-pied" };233const FOUND: Record<string, string> = { poured_concrete: "béton coulé", concrete_block: "blocs de béton", slab_on_grade: "dalle sur sol", piers: "pieux", stone: "pierre" };234const ROOF: Record<string, string> = { asphalt_shingle: "bardeau d'asphalte", metal: "tôle", membrane: "membrane", cedar: "cèdre", slate_tile: "ardoise/tuile" };235const GEOM: Record<string, string> = { gable: "à deux versants", hip: "à quatre versants", flat: "plat", mansard: "mansardé", complex: "complexe" };236const WIN: Record<string, string> = { pvc: "PVC", hybrid: "hybride", aluminum: "aluminium", wood: "bois" };237const HEAT: Record<string, string> = { electric_baseboard: "plinthes électriques", heat_pump: "thermopompe centrale", furnace_electric: "fournaise électrique", furnace_gas: "fournaise au gaz", furnace_oil: "fournaise à l'huile", hydronic: "eau chaude", geothermal: "géothermie", wood: "bois" };238const GARAGE: Record<string, string> = { none: "aucun", attached: "attenant", detached: "détaché", integrated: "intégré", carport: "abri d'auto" };239const SIDING: Record<string, string> = { vinyl: "vinyle", brick: "brique", fiber_cement: "fibrociment", wood: "bois", stone: "pierre", stucco: "stuc", aluminum: "aluminium", steel: "acier" };240const MODE: Record<string, string> = { property: "propriété du rôle (MAMH)", construction: "construction hypothétique", listing: "annonce à vendre (analyse IA)" };241const qLabel = (q: string) => QUALITIES.find((x) => x.key === q)?.fr ?? q;242const unitLabel = (u: string) => UNIT_LABELS[u as keyof typeof UNIT_LABELS]?.fr ?? u;243const shortUrl = (u: string | null | undefined) => {244  if (!u) return "";245  try { const x = new URL(u); return (x.host.replace(/^www\./, "") + x.pathname).slice(0, 60); } catch { return u.slice(0, 60); }246};247248/* ============================================================ rapport */249250export async function buildCostReport(est: CostEstimate): Promise<Buffer> {251  const b = est.input.building;252  const generated = new Date().toISOString().slice(0, 16).replace("T", " ");253  const doc = new PDFDocument({ size: "LETTER", margin: 0, bufferPages: true, info: { Title: `Vrai-Prix — Méthode du coût — ${est.input.address ?? "bâtiment"}`, Author: "Vrai-Prix — Simon-Pierre Boucher (contact@spboucher.ai)" } });254  doc.registerFont("SG-Bold", F("SpaceGrotesk-Bold.ttf"));255  doc.registerFont("SG-Med", F("SpaceGrotesk-Medium.ttf"));256  doc.registerFont("JB-Reg", F("JetBrainsMono-Regular.ttf"));257  doc.registerFont("JB-Bold", F("JetBrainsMono-Bold.ttf"));258  doc.registerFont("Inter", F("Inter-Regular.ttf"));259  const chunks: Buffer[] = [];260  doc.on("data", (c: Buffer) => chunks.push(c));261  const done = new Promise<Buffer>((res) => doc.on("end", () => res(Buffer.concat(chunks))));262  const L = new Layout(doc);263  const src = est.input.attributeSources;264  const prov = (k: string) => SRC_TXT[src[k] ?? ""] ?? (src[k] ?? "supposé");265266  /* ================================ PAGE 1 — couverture ================================ */267  pageBg(doc);268  doc.rect(0, 0, W, 96).fill(INK);269  logo(doc, M, 30);270  doc.font("JB-Reg").fontSize(7).fillColor(LIME).text("ESTIMATION IMMOBILIÈRE TRANSPARENTE · RAPPORT — MÉTHODE DU COÛT", M, 66, { characterSpacing: 1.2, lineBreak: false });271  doc.font("JB-Reg").fontSize(6).fillColor("#9aa39c").text("COÛT DE REMPLACEMENT À NEUF · DÉPRÉCIATION · TERRAIN — TROISIÈME LECTURE DE LA VALEUR", M, 78, { characterSpacing: 1, lineBreak: false });272  doc.font("JB-Reg").fontSize(7).fillColor("#9aa39c")273    .text(`ESTIMATION ${est.id.slice(0, 8).toUpperCase()}`, W - M - 220, 34, { width: 220, align: "right" })274    .text(`GÉNÉRÉ LE ${generated}`, W - M - 220, 46, { width: 220, align: "right" })275    .text(`PRIX AU ${est.priceDate} · MÉTHODE v${est.methodVersion}`, W - M - 220, 58, { width: 220, align: "right" });276  doc.rect(0, 96, W, 3).fill(LIME);277278  let y = 122;279  kicker(doc, "Indication de valeur par la méthode du coût", M, y);280  y += 16;281  const titre = [est.input.address, est.input.municipality].filter(Boolean).join(" · ") || `${BUILDING_TYPES.find((t) => t.key === b.type)?.fr ?? b.type} — ${num(b.grossFloorAreaSqft)} pi²`;282  doc.font("SG-Bold").fontSize(15).fillColor(INK).text(titre.toUpperCase(), M, y, { width: W - 2 * M });283  y = doc.y + 6;284  doc.font("SG-Bold").fontSize(46).fillColor(INK).text(fmt(est.costApproachValue), M, y);285  y = doc.y + 10;286287  const cols = [288    ["COÛT DE REMPLACEMENT À NEUF", fmt(est.replacementCostNew)],289    ["DÉPRÉCIATION TOTALE", neg(est.depreciation.total)],290    ["VALEUR DU TERRAIN", fmt(est.landValue)],291    ["FOURCHETTE RCN P10-P90", `${fmt(est.range.p10)} → ${fmt(est.range.p90)}`],292  ] as const;293  let cx0 = M;294  for (const [k, v] of cols) {295    doc.font("JB-Bold").fontSize(6.3).fillColor(INK3).text(k, cx0, y, { characterSpacing: 0.6, lineBreak: false });296    const lw = doc.widthOfString(k) + 6;297    doc.font("SG-Bold").fontSize(12).fillColor(INK).text(v, cx0, y + 11, { lineBreak: false });298    cx0 += Math.max(doc.widthOfString(v), lw) + 26;299  }300  const c = est.confidence;301  const confTxt = `CONFIANCE ${c.letter} · ${c.total} / 100 — ${CONF_TXT[c.letter].toUpperCase()}`;302  doc.font("JB-Bold").fontSize(7.5);303  const cw = doc.widthOfString(confTxt) + 20;304  doc.roundedRect(M, y + 34, cw, 18, 4).lineWidth(1).fillAndStroke(CONF_BG[c.letter], INK);305  doc.fillColor(c.letter === "D" ? DANGER : INK).text(confTxt, M + 10, y + 39.5, { lineBreak: false });306  y += 72;307308  // équation309  card(doc, M, y, W - 2 * M, 58, { fill: INK, shadow: false });310  doc.font("JB-Bold").fontSize(7).fillColor(LIME).text("LA FORMULE — JAMAIS MASQUÉE", M + 16, y + 11, { characterSpacing: 1.4 });311  doc.font("JB-Reg").fontSize(8.2).fillColor("#e8e6df").text(312    `V_coût = V_terrain + RCN − D   →   ${fmt(est.costApproachValue)} = ${fmt(est.landValue)} + ${fmt(est.replacementCostNew)} − ${fmt(est.depreciation.total)}`,313    M + 16, y + 26, { width: W - 2 * M - 32, lineBreak: false, height: 12, ellipsis: true });314  doc.font("JB-Reg").fontSize(7).fillColor("#9fb4bd").text(315    `RCN = Direct ${fmt(est.directCost)} + Indirects ${fmt(est.indirectCost)} + Frais gén. ${fmt(est.contractorOverhead)} + Profit ${fmt(est.contractorProfit)} + Contingence ${fmt(est.contingency)}`,316    M + 16, y + 41, { width: W - 2 * M - 32, lineBreak: false, height: 10, ellipsis: true });317  y += 78;318319  // fiche du bâtiment (3 cartes)320  kicker(doc, "1 · Propriété et bâtiment — chaque caractéristique avec sa provenance", M, y);321  y += 16;322  const sidingTxt = Object.entries(b.siding).filter(([, v]) => (v ?? 0) > 0).map(([k, v]) => `${SIDING[k] ?? k} ${Math.round((v ?? 0) * 100)} %`).join(", ") || "—";323  const groups: [string, [string, string][]][] = [324    ["IDENTIFICATION", [325      ["Mode", MODE[est.input.mode] ?? est.input.mode],326      ["Id / annonce", est.input.propertyId ?? est.input.listingUid ?? "—"],327      ["Municipalité", est.input.municipality ?? "—"],328      ["Type", `${BUILDING_TYPES.find((t) => t.key === b.type)?.fr ?? b.type} (${prov("type")})`],329      ["Qualité", `${qLabel(b.quality)} (${prov("quality")})`],330      ["Logements", String(b.units)],331      ["Année constr.", `${b.yearBuilt ?? "—"} (${prov("yearBuilt")})`],332      ["Localisation", est.location.nameFr],333    ]],334    ["GÉOMÉTRIE", [335      ["Aire d'étages", `${num(b.grossFloorAreaSqft)} pi² (${prov("grossFloorAreaSqft")})`],336      ["Étages", `${b.stories} (${prov("stories")})`],337      ["Sous-sol", `${BASEMENT[b.basement] ?? b.basement} (${prov("basement")})`],338      ["Fondation", `${FOUND[b.foundation] ?? b.foundation} (${prov("foundation")})`],339      ["Garage", `${GARAGE[b.garage.type]}${b.garage.spaces ? ` ${b.garage.spaces} pl.` : ""} (${prov("garage")})`],340      ["Toit", `${ROOF[b.roof] ?? b.roof}, ${GEOM[b.roofGeometry] ?? b.roofGeometry} ${b.roofPitch}/12 (${prov("roof")})`],341      ["Fenêtres", `${WIN[b.windows] ?? b.windows}${b.windowCount != null ? ` × ${b.windowCount}` : ""} (${prov("windows")})`],342      ["Revêtement", `${sidingTxt} (${prov("siding")})`],343    ]],344    ["INTÉRIEUR ET MÉCANIQUE", [345      ["Chauffage", `${HEAT[b.heating] ?? b.heating} (${prov("heating")})`],346      ["Clim. / VRC", `${b.hasAirConditioning ? "clim." : "—"} / ${b.hasAirExchanger ? "VRC" : "—"}`],347      ["Cuisines", `${b.kitchens} · ${qLabel(b.kitchenQuality)} (${prov("kitchenQuality")})`],348      ["Salles de bain", `${b.bathrooms} + ${b.powderRooms} s. d'eau · ${qLabel(b.bathroomQuality)} (${prov("bathrooms")})`],349      ["Terrasse", b.deckSqft ? `${num(b.deckSqft)} pi²` : "—"],350      ["Entrée", b.drivewaySqft ? `${num(b.drivewaySqft)} pi² (${b.driveway})` : "—"],351      ["Piscine", b.pool === "none" ? "—" : b.pool === "inground" ? "creusée" : "hors terre"],352      ["Aménagement", b.landscapingSqft ? `${num(b.landscapingSqft)} pi²` : "—"],353    ]],354  ];355  const gW = (W - 2 * M - 2 * 14) / 3;356  const cellH = 38;357  const gH = 4 * (cellH + 6) + 34;358  groups.forEach(([title, rows], gi) => {359    const gx = M + gi * (gW + 14);360    card(doc, gx, y, gW, gH);361    doc.font("JB-Bold").fontSize(7).fillColor(GREEN_DEEP).text(title, gx + 12, y + 11, { characterSpacing: 1.2, lineBreak: false });362    doc.moveTo(gx + 12, y + 24).lineTo(gx + gW - 12, y + 24).dash(2, { space: 3 }).lineWidth(0.8).stroke(LINE).undash();363    const cw2 = (gW - 24 - 6) / 2;364    rows.forEach(([k, v], i) => {365      const col = i % 2, row = Math.floor(i / 2);366      kvCell(doc, gx + 12 + col * (cw2 + 6), y + 32 + row * (cellH + 6), cw2, cellH, k, v);367    });368  });369  y += gH + 14;370  doc.font("JB-Reg").fontSize(6.3).fillColor(INK3).text(371    "PROVENANCE : rôle MAMH = registre officiel · saisi = utilisateur · inféré par IA = analyse multimodale · dérivé = formule · supposé = hypothèse par défaut. Légende des prix : ● observé/officiel · ◐ calculé · ○ indexé · ◇ référence interne (hypothèse).",372    M, y, { width: W - 2 * M, characterSpacing: 0.2, lineGap: 1 });373374  /* ================================ PAGE 2 — hypothèses & localisation ================================ */375  L.newPage();376  L.section("2 · Hypothèses — chaque pourcentage est visible, modifiable et expliqué");377  const p = est.input.params;378  L.table(379    [{ h: "Poste", w: 40 }, { h: "Taux", w: 10, align: "right", mono: true }, { h: "Base de calcul", w: 30 }, { h: "Explication (hypothèse documentée)", w: 60 }],380    [381      ...est.indirect.map((i) => [i.labelFr, pct(i.pct, 1), "coût direct", INDIRECT_LABELS[i.key].noteFr]),382      ["Frais généraux entrepreneur", pct(p.overheadPct, 1), "direct + indirects", "Frais fixes de l'entreprise (bureau, gestion) — distincts du profit."],383      ["Profit entrepreneur", pct(p.profitPct, 1), "direct + indirects + FG", "Rémunération du risque de l'entrepreneur général."],384      ["Contingence", pct(p.contingencyPct, 1), "direct + indirects", "Réserve pour imprévus de chantier — ni profit ni frais indirects."],385    ],386    { rowH: 15 }387  );388  L.para(`Coût de REMPLACEMENT (et non de reproduction) : le bâtiment est reconstruit avec les composantes modernes équivalentes (murs 2 × 6 R24, comble R50, poutrelles ajourées), quel que soit son année de construction. Constantes de prise de quantités : hauteur d'étage 9 pi, rapport de forme 1,5, 0,011 fenêtre de 10 pi² par pi² de plancher, 0,09 pi lin de cloison par pi², murs de sous-sol 8 pi, garage 10 pi. Dépréciation : méthode « ${est.depreciation.method === "components" ? "composante par composante (vie économique et condition de chaque groupe)" : "âge-vie simple (âge effectif ÷ vie économique)"} », vie économique ${est.depreciation.economicLife} ans, dépréciation physique plafonnée à 90 %.`);389  L.para(`Base de coûts version ${est.costDatabaseVersion} · assemblages v${est.assemblyVersion} · géométrie/quantités dérivées automatiquement sauf surcharges (${Object.keys(est.input.quantityOverrides).length}). Une estimation créée aujourd'hui peut être reconstruite plus tard avec les prix de sa date (instantané conservé).`, { size: 7.2, color: INK3 });390391  L.section("8 · Localisation — facteurs distincts matériaux / main-d'œuvre / équipement");392  const loc = est.location;393  L.table(394    [{ h: "Région", w: 40 }, { h: "Matériaux", w: 15, align: "right", mono: true }, { h: "Main-d'œuvre", w: 15, align: "right", mono: true }, { h: "Équipement", w: 15, align: "right", mono: true }, { h: "Global", w: 15, align: "right", mono: true }, { h: "Confiance", w: 15, align: "right", mono: true }],395    [[`${loc.nameFr} (${loc.code})`, loc.materialFactor.toFixed(3), loc.labourFactor.toFixed(3), loc.equipmentFactor.toFixed(3), loc.overallFactor.toFixed(3), `${loc.confidence}/100`]]396  );397  L.para(`Méthode : ${loc.sourceMethod}. Ajustement de localisation appliqué au coût direct : ${fmt(est.lines.reduce((s, l) => s + l.locationAdjustment, 0))} (matériaux × ${loc.materialFactor}, main-d'œuvre × ${loc.labourFactor}, équipement × ${loc.equipmentFactor}). Les conventions collectives de la construction (Loi R-20) fixent des taux uniformes pour tout le Québec : le facteur main-d'œuvre est 1,00 sauf régions éloignées.`);398399  /* ================================ 4 · direct par catégorie ================================ */400  L.section("4 · Coût direct par catégorie — matériaux, main-d'œuvre, équipement");401  const maxAdj = Math.max(1, ...est.categories.map((k) => k.adjusted));402  L.table(403    [{ h: "Catégorie", w: 34 }, { h: "Matériaux", w: 16, align: "right", mono: true }, { h: "Main-d'œuvre", w: 16, align: "right", mono: true }, { h: "Équip.", w: 12, align: "right", mono: true }, { h: "Direct localisé", w: 16, align: "right", mono: true }, { h: "Part", w: 10, align: "right", mono: true }],404    est.categories.map((k) => [k.labelFr, fmt(k.material), fmt(k.labour), fmt(k.equipment), fmt(k.adjusted), pct(k.sharePct, 1)]),405    { total: ["COÛTS DIRECTS", fmt(est.directMaterial), fmt(est.directLabour), fmt(est.directEquipment), fmt(est.directCost), "100 %"] }406  );407  // barres408  L.ensure(est.categories.length * 11 + 14);409  est.categories.forEach((k) => {410    const trackX = M + 150, trackW = W - 2 * M - 150 - 70;411    doc.font("JB-Reg").fontSize(6.4).fillColor(INK).text(k.labelFr, M, L.y + 1, { width: 145, lineBreak: false, height: 9, ellipsis: true });412    doc.rect(trackX, L.y, trackW, 8).fill(SURFACE2);413    const wM = (k.material / maxAdj) * trackW, wL = (k.labour / maxAdj) * trackW, wE = (k.equipment / maxAdj) * trackW;414    doc.rect(trackX, L.y, wM, 8).fill(INK);415    doc.rect(trackX + wM, L.y, wL, 8).fill(GREEN);416    doc.rect(trackX + wM + wL, L.y, wE, 8).fill(LIME);417    doc.font("JB-Bold").fontSize(6.4).fillColor(INK).text(fmt(k.adjusted), W - M - 66, L.y + 1, { width: 66, align: "right", lineBreak: false });418    L.y += 11;419  });420  doc.font("JB-Reg").fontSize(6.2).fillColor(INK3).text("■ MATÉRIAUX (encre) · ■ MAIN-D'ŒUVRE (bordeaux) · ■ ÉQUIPEMENT (rouge)", M, L.y + 2, { characterSpacing: 0.3 });421  L.y += 16;422423  /* ================================ 5 · indirects + 9 · RCN ================================ */424  L.section("5 · Indirects, frais généraux, profit, contingence → 9 · RCN");425  L.table(426    [{ h: "Poste", w: 55 }, { h: "Taux", w: 15, align: "right", mono: true }, { h: "Montant", w: 30, align: "right", mono: true }],427    [428      ["Coûts directs localisés", "", fmt(est.directCost)],429      ...est.indirect.map((i) => [`Indirect — ${i.labelFr}`, pct(i.pct, 1), fmt(i.amount)]),430      ["Sous-total coûts indirects", pct(est.indirect.reduce((s, i) => s + i.pct, 0), 1), fmt(est.indirectCost)],431      ["Frais généraux entrepreneur", pct(p.overheadPct, 1), fmt(est.contractorOverhead)],432      ["Profit entrepreneur", pct(p.profitPct, 1), fmt(est.contractorProfit)],433      ["Contingence", pct(p.contingencyPct, 1), fmt(est.contingency)],434    ],435    { total: ["COÛT DE REMPLACEMENT À NEUF (RCN)", "", fmt(est.replacementCostNew)], highlight: (i) => i === 0 || i === est.indirect.length + 1 }436  );437  L.ensure(70);438  const tW3 = (W - 2 * M - 28) / 3;439  [["RCN TOTAL", fmt(est.replacementCostNew)], ["RCN PAR PI² D'AIRE D'ÉTAGES", `${fmt2(est.perSqft)} / pi²`], ["RCN PAR M²", `${fmt2(est.perM2)} / m²`]].forEach(([k, v], i) => {440    const x = M + i * (tW3 + 14);441    card(doc, x, L.y, tW3, 52);442    doc.font("JB-Bold").fontSize(6.3).fillColor(INK3).text(k, x + 12, L.y + 10, { characterSpacing: 0.6, lineBreak: false, width: tW3 - 24, height: 9, ellipsis: true });443    doc.font("SG-Bold").fontSize(17).fillColor(INK).text(v, x + 12, L.y + 24, { lineBreak: false, width: tW3 - 24, height: 22, ellipsis: true });444  });445  L.y += 74;446447  /* ================================ 13 · fourchette ================================ */448  L.section("13 · Fourchette de coût — P10 · central · P90");449  L.ensure(60);450  {451    const r = est.range;452    const lo = r.p10 * 0.96, hi = r.p90 * 1.04;453    const tx = M, tw = W - 2 * M;454    const X = (v: number) => tx + ((v - lo) / (hi - lo)) * tw;455    doc.rect(tx, L.y + 14, tw, 10).fill(SURFACE2);456    doc.rect(X(r.p10), L.y + 14, X(r.p90) - X(r.p10), 10).fill(LIME_SOFT);457    doc.rect(X(r.p10), L.y + 10, 1.5, 18).fill(GREEN);458    doc.rect(X(r.p90), L.y + 10, 1.5, 18).fill(GREEN);459    doc.rect(X(est.replacementCostNew) - 1.5, L.y + 6, 3, 26).fill(INK);460    doc.font("JB-Bold").fontSize(6.5).fillColor(GREEN_DEEP).text(`P10 ${fmt(r.p10)}`, X(r.p10) - 40, L.y + 32, { width: 80, align: "center", lineBreak: false });461    doc.text(`P90 ${fmt(r.p90)}`, X(r.p90) - 40, L.y + 32, { width: 80, align: "center", lineBreak: false });462    doc.fillColor(INK).text(`RCN ${fmt(est.replacementCostNew)}`, X(est.replacementCostNew) - 50, L.y - 2, { width: 100, align: "center", lineBreak: false });463    L.y += 46;464  }465  L.para(`Écart-type combiné ${fmt(est.range.sigma)} : dispersion des prix de chaque article (observés multi-sources, ou ±8 % observé / ±15 % référence / ±20 % hypothèse), incertitude des heures (±15 %), de l'équipement (±20 %) et des quantités (dérivées ±10 %, saisies ±3 %, IA ±15 %), combinées en racine des carrés, plus une composante systématique (localisation, modèle d'assemblages 5 %). P10/P90 = RCN ∓ 1,28 σ.`);466467  /* ================================ 10 · dépréciation ================================ */468  L.newPage();469  L.section("10 · Dépréciation — physique, fonctionnelle, externe");470  const d = est.depreciation;471  L.table(472    [{ h: "Élément", w: 60 }, { h: "Valeur", w: 40, align: "right", mono: true }],473    [474      ["Âge chronologique", d.chronologicalAge != null ? `${d.chronologicalAge} ans` : "—"],475      ["Âge effectif retenu", d.effectiveAge != null ? `${num(d.effectiveAge, 1)} ans (${SRC_TXT[est.input.depreciation.effectiveAgeSource] ?? est.input.depreciation.effectiveAgeSource})` : "—"],476      ["Vie économique", `${d.economicLife} ans`],477      ["Méthode", d.method === "components" ? "composante par composante" : "âge-vie simple"],478      ["Détérioration physique", `${pct(d.physicalPct, 1)} → ${fmt(d.physical)}`],479    ]480  );481  if (d.method === "components" && d.components.length) {482    L.table(483      [{ h: "Composante", w: 28 }, { h: "RCN", w: 13, align: "right", mono: true }, { h: "Vie", w: 8, align: "right", mono: true }, { h: "Condition", w: 11 }, { h: "Âge eff.", w: 11, align: "right", mono: true }, { h: "Dépr. %", w: 10, align: "right", mono: true }, { h: "Dépréciation", w: 14, align: "right", mono: true }, { h: "Restant", w: 14, align: "right", mono: true }],484      d.components.map((k) => [k.labelFr, fmt(k.rcn), `${k.economicLife} a`, k.condition ?? "— (âge)", num(k.effectiveAge, 1), pct(k.depreciationPct, 0), fmt(k.depreciation), fmt(k.remaining)]),485      { total: ["TOTAL PHYSIQUE", fmt(d.components.reduce((s, k) => s + k.rcn, 0)), "", "", "", pct(d.physicalPct, 1), fmt(d.physical), fmt(d.components.reduce((s, k) => s + k.remaining, 0))] }486    );487    L.para("Règle : âge effectif de la composante = ratio de condition × vie économique (règles documentées modifiables : neuf 0 · excellent 0,10 · rénové 0,12 · très bon 0,20 · bon 0,35 · moyen 0,55 · sous la moyenne 0,70 · mauvais 0,85) ; sans condition saisie, l'âge chronologique plafonné à la vie est utilisé.", { size: 7.2, color: INK3 });488  }489  const fo = est.input.depreciation.functional;490  L.table(491    [{ h: "Désuétude", w: 34 }, { h: "Type", w: 16 }, { h: "Détail", w: 30 }, { h: "Montant", w: 20, align: "right", mono: true }],492    [493      ...fo.map((f) => [`Fonctionnelle — ${f.type || "—"}`, f.curable ? "curable" : "incurable", f.curable ? `coût de correction ${fmt(f.costToCure)}` : `perte de valeur ${fmt(f.valueLoss)}`, neg(f.curable ? f.costToCure : f.valueLoss)]),494      ["Désuétude fonctionnelle (total)", "", `${fo.length} déficience(s)`, neg(d.functional)],495      ["Désuétude externe", "", est.input.depreciation.externalNote || "aucune preuve saisie → 0 $", neg(d.external)],496    ],497    { total: ["DÉPRÉCIATION TOTALE", "", `${pct(est.replacementCostNew ? (d.total / est.replacementCostNew) * 100 : 0, 1)} du RCN`, neg(d.total)] }498  );499500  /* ================================ 11 · terrain + 12 · valeur ================================ */501  L.section("11 · Valeur du terrain");502  const land = est.input.land;503  const LANDSRC: Record<string, string> = { role: `Rôle d'évaluation foncière ${land.rollYear ?? 2026} (MAMH)`, user: "Valeur saisie par l'utilisateur", market: "Valeur marchande (ventes de terrains)", residual: "Technique du résiduel", none: "Aucune valeur — 0 $ (à compléter)" };504  L.table([{ h: "Valeur du terrain utilisée", w: 30, align: "right", mono: true }, { h: "Source", w: 35 }, { h: "Méthode", w: 35 }], [[fmt(est.landValue), LANDSRC[land.source] ?? land.source, land.method || "—"]]);505  L.para("⚠ La valeur du terrain au rôle n'est pas nécessairement la valeur marchande actuelle du terrain : le rôle est établi 18 à 24 mois avant son entrée en vigueur. Vous pouvez la conserver, la remplacer ou la documenter par une autre méthode.", { color: DANGER, size: 7.4 });506507  L.section("12 · Indication de valeur par la méthode du coût");508  L.table(509    [{ h: "Poste", w: 60 }, { h: "Montant", w: 40, align: "right", mono: true }],510    [511      ...est.categories.map((k) => [k.labelFr, fmt(k.adjusted)]),512      ["Coûts directs", fmt(est.directCost)],513      ["Coûts indirects", fmt(est.indirectCost)],514      ["Frais généraux", fmt(est.contractorOverhead)],515      ["Profit", fmt(est.contractorProfit)],516      ["Contingence", fmt(est.contingency)],517      ["COÛT DE REMPLACEMENT À NEUF", fmt(est.replacementCostNew)],518      ["Détérioration physique", neg(d.physical)],519      ["Désuétude fonctionnelle", neg(d.functional)],520      ["Désuétude externe", neg(d.external)],521      ["Valeur dépréciée du bâtiment", fmt(d.depreciatedImprovementValue)],522      ["Valeur du terrain", fmt(est.landValue)],523    ],524    { total: ["INDICATION PAR LE COÛT", fmt(est.costApproachValue)], highlight: (i) => [est.categories.length, est.categories.length + 5, est.categories.length + 9].includes(i) }525  );526527  /* ================================ 14 · confiance + benchmarks ================================ */528  L.section("14 · Indice de confiance — décomposition");529  L.table(530    [{ h: "Critère", w: 50 }, { h: "Score", w: 20, align: "right", mono: true }, { h: "Maximum", w: 30, align: "right", mono: true }],531    [["Fraîcheur des prix", String(c.freshness), "20"], ["Couverture (prix observés vs référence)", String(c.coverage), "20"], ["Localisation", String(c.location), "15"], ["Main-d'œuvre (grilles officielles)", String(c.labour), "15"], ["Benchmarks externes", String(c.benchmarks), "10"], ["Complétude du bâtiment", String(c.building), "20"]],532    { total: [`TOTAL — ${c.letter} · ${CONF_TXT[c.letter]}`, String(c.total), "100"] }533  );534  c.notesFr.forEach((n) => L.bullet(n));535  L.bullet(`Couverture des prix : ${pct(est.coverage.materialObservedShare * 100, 0)} du coût des matériaux repose sur des prix observés/officiels ; ${est.coverage.assembliesPriced}/${est.coverage.assembliesTotal} assemblages chiffrés.`);536  L.gap(4);537  L.section("Validation externe — benchmarks");538  if (est.benchmarks.length) {539    L.table(540      [{ h: "Source", w: 26 }, { h: "Type / marché", w: 26 }, { h: "Plage", w: 20, align: "right", mono: true }, { h: "Vrai-Prix", w: 14, align: "right", mono: true }, { h: "État", w: 14 }],541      est.benchmarks.map((k) => [`${k.source} ${k.year}`, `${k.buildingType} · ${k.market}`, `${fmt(k.low)}–${fmt(k.high)} ${k.unit}`, fmt2(k.estimatePerUnit), k.status === "within" ? "dans la plage" : k.status === "below" ? `⚠ sous la plage (${pct(k.deviationPct, 0)})` : k.status === "above" ? `⚠ au-dessus (${pct(k.deviationPct, 0)})` : "non disponible"])542    );543    L.para("Le benchmark ne modifie jamais l'estimation : un écart important est signalé, pas corrigé.", { size: 7.2, color: INK3 });544  } else {545    L.para("Donnée non disponible — aucun benchmark externe importé pour ce type de bâtiment et ce marché (le guide Altus requiert un import manuel après téléchargement légal).", { color: INK3 });546  }547  if (est.otherReadings) {548    const o = est.otherReadings;549    L.section("Trois lectures de la valeur — à comparer, jamais à moyenner");550    L.table(551      [{ h: "Lecture", w: 50 }, { h: "Valeur", w: 25, align: "right", mono: true }, { h: "vs coût", w: 25, align: "right", mono: true }],552      [553        ["Modèle hédonique (LightGBM)", fmt(o.hedonic), o.hedonic ? pct(((o.hedonic - est.costApproachValue) / est.costApproachValue) * 100, 1) : "—"],554        ["Comparables ajustés", fmt(o.comparables), o.comparables ? pct(((o.comparables - est.costApproachValue) / est.costApproachValue) * 100, 1) : "—"],555        ["Mesure Vrai-Prix (hybride 65/35)", fmt(o.hybrid), o.hybrid ? pct(((o.hybrid - est.costApproachValue) / est.costApproachValue) * 100, 1) : "—"],556        ["Méthode du coût (ce rapport)", fmt(est.costApproachValue), "—"],557        ...(o.askingPrice ? [["Prix demandé", fmt(o.askingPrice), pct(((o.askingPrice - est.costApproachValue) / est.costApproachValue) * 100, 1)]] : []),558        ["Rôle 2026 — valeur totale", fmt(o.rollValue), o.rollValue ? pct(((o.rollValue - est.costApproachValue) / est.costApproachValue) * 100, 1) : "—"],559        ["Rôle 2026 — bâtiment / terrain", `${fmt(o.rollBuilding)} / ${fmt(o.rollLand)}`, ""],560      ]561    );562    L.para(`RCN vs valeur du bâtiment au rôle : ${fmt(est.replacementCostNew)} vs ${fmt(o.rollBuilding)} ; valeur dépréciée vs rôle bâtiment : ${fmt(d.depreciatedImprovementValue)} vs ${fmt(o.rollBuilding)}. Le but est de comparer les approches, pas de faire une moyenne naïve.`, { size: 7.2, color: INK3 });563  }564565  /* ================================ 3 + 6 · assemblages ================================ */566  L.newPage();567  L.section("3 · Assemblages retenus (6 · quantités, coûts unitaires, totaux)");568  L.para(`${est.lines.length} assemblages quantifiés par le moteur de géométrie (formule affichée) ou surchargés (${Object.keys(est.input.quantityOverrides).length}). Coût unitaire = matériaux (qté × pertes × prix) + main-d'œuvre (heures × taux employeur) + équipement, avant facteur régional. Prov. = nature dominante des prix des composants.`, { size: 7.2, color: INK3 });569  const kindOf = (l: CostEstimate["lines"][number]): string => {570    const kinds = l.unitDetail.components.filter((k) => k.itemCode).map((k) => k.provenance.kind);571    if (!kinds.length) return "◐";572    if (kinds.every((k) => k === "observed" || k === "official")) return "●";573    if (kinds.some((k) => k === "observed" || k === "official")) return "◐";574    if (kinds.some((k) => k === "indexed")) return "○";575    return "◇";576  };577  L.table(578    [{ h: "Assemblage", w: 30 }, { h: "Quantité", w: 11, align: "right", mono: true }, { h: "Formule", w: 27 }, { h: "Unitaire", w: 10, align: "right", mono: true }, { h: "M / MO / É", w: 14, align: "right", mono: true }, { h: "Total loc.", w: 11, align: "right", mono: true }, { h: "P", w: 3 }],579    est.lines.map((l) => [l.nameFr, `${num(l.quantity, l.quantity < 10 ? 1 : 0)} ${unitLabel(l.unit)}`, l.quantityFormula.replace(/\s+/g, " "), fmt2(l.unitCost), `${num(l.material / 1000, 1)}k/${num(l.labour / 1000, 1)}k/${num(l.equipment / 1000, 1)}k`, fmt(l.adjusted), kindOf(l)]),580    { rowH: 13, total: ["COÛTS DIRECTS LOCALISÉS", "", "", "", `${num(est.directMaterial / 1000, 0)}k/${num(est.directLabour / 1000, 0)}k/${num(est.directEquipment / 1000, 0)}k`, fmt(est.directCost), ""] }581  );582  // descriptions des assemblages583  L.section("Description des assemblages");584  const seen = new Set<string>();585  for (const l of est.lines) {586    if (seen.has(l.assemblyCode)) continue;587    seen.add(l.assemblyCode);588    const a = est.lines.find((x) => x.assemblyCode === l.assemblyCode)!;589    const desc = a.unitDetail.components.filter((k) => k.itemCode).map((k) => `${k.nameFr} ${num(k.quantity, 3)} ${unitLabel(k.unit)}`).join(" · ");590    L.para(`${l.nameFr} [${l.assemblyCode}, par ${unitLabel(l.unit)}] — ${desc || "main-d'œuvre/équipement seulement"}.`, { size: 6.8, color: INK2, gap: 3 });591  }592593  /* ================================ 7 · main-d'œuvre ================================ */594  L.newPage();595  L.section("7 · Main-d'œuvre — heures et coût par métier (taux employeur complet)");596  const trades = new Map<string, { h: number; cost: number; rate: number | null; src: string; date: string; kind: string }>();597  for (const l of est.lines) for (const k of l.unitDetail.components) {598    if (!k.labourHours) continue;599    const t = k.trade ?? "—";600    const cur = trades.get(t) ?? { h: 0, cost: 0, rate: k.hourlyRate, src: k.rateProvenance?.source ?? "—", date: k.rateProvenance?.effectiveDate ?? "—", kind: k.rateProvenance?.kind === "official" ? "● officiel" : "◇ repli (hypothèse)" };601    cur.h += k.labourHours * l.quantity;602    cur.cost += k.labourCost * l.quantity * loc.labourFactor;603    trades.set(t, cur);604  }605  const trows = [...trades.entries()].sort((a, b) => b[1].cost - a[1].cost);606  L.table(607    [{ h: "Métier", w: 22 }, { h: "Heures", w: 9, align: "right", mono: true }, { h: "Taux employeur", w: 13, align: "right", mono: true }, { h: "Coût localisé", w: 13, align: "right", mono: true }, { h: "Source", w: 33 }, { h: "En vigueur", w: 10, mono: true }],608    trows.map(([t, v]) => [tradeLabel(t, true), num(v.h, 0), v.rate != null ? `${fmt2(v.rate)}/h` : "—", fmt(v.cost), `${v.kind} — ${v.src}`, v.date]),609    { total: ["TOTAL MAIN-D'ŒUVRE", num(trows.reduce((s, [, v]) => s + v.h, 0), 0), "", fmt(est.directLabour), "", ""] }610  );611  L.para("Le taux employeur complet inclut le salaire horaire conventionné (CCQ), l'indemnité de congés (13 %), les avantages sociaux, les cotisations (AE, RQAP, RRQ, FSS, CNESST, prélèvement CCQ, AECQ, fonds de formation) — jamais le salaire horaire nu. Les heures par unité d'assemblage sont des hypothèses de productivité résidentielle documentées.", { size: 7.2, color: INK3 });612613  /* ================================ 15 · sources ================================ */614  L.section("15 · Sources — chaque prix important est retraçable");615  const srcMap = new Map<string, { kind: string; date: string; url: string; n: number }>();616  for (const l of est.lines) for (const k of l.unitDetail.components) {617    if (!k.itemCode) continue;618    for (const nm of k.provenance.source.split(", ")) {619      const key = nm.trim();620      const cur = srcMap.get(key) ?? { kind: `${KIND_ICON[k.provenance.kind]} ${KIND_TXT[k.provenance.kind]}`, date: k.provenance.observedAt ?? k.provenance.effectiveDate ?? "—", url: shortUrl(k.provenance.sourceUrl), n: 0 };621      cur.n++;622      srcMap.set(key, cur);623    }624    if (k.rateProvenance) {625      const key = k.rateProvenance.source;626      const cur = srcMap.get(key) ?? { kind: `${KIND_ICON[k.rateProvenance.kind]} ${KIND_TXT[k.rateProvenance.kind]}`, date: k.rateProvenance.effectiveDate ?? "—", url: shortUrl(k.rateProvenance.sourceUrl), n: 0 };627      cur.n++;628      srcMap.set(key, cur);629    }630  }631  L.table(632    [{ h: "Source", w: 34 }, { h: "Nature", w: 20 }, { h: "Date", w: 12, mono: true }, { h: "Composants", w: 10, align: "right", mono: true }, { h: "URL", w: 24, mono: true }],633    [...srcMap.entries()].sort((a, b) => b[1].n - a[1].n).map(([k, v]) => [k, v.kind, v.date, String(v.n), v.url]),634    { rowH: 13 }635  );636  L.para(`Localisation : ${loc.nameFr} — ${loc.sourceMethod}. Indices : Statistique Canada 18-10-0289-01 (actualisation des observations anciennes). Prix de référence internes (◇) : hypothèses documentées pour les articles sans observation détaillant — ils réduisent la couverture et l'indice de confiance.`, { size: 7.2, color: INK3 });637638  /* ================================ 16 · limites ================================ */639  L.section("16 · Limites");640  [641    "Estimation indicative : les coûts présentés sont des estimations statistiques et ne constituent ni une soumission d'entrepreneur ni une évaluation professionnelle certifiée (OEAQ).",642    "Les quantités sont dérivées de formules géométriques génériques (rapport de forme, hauteurs, ratios d'ouvertures) et non d'un relevé des plans ; les surcharges saisies priment.",643    "Les caractéristiques « supposées » (revêtement, toiture, chauffage, qualité…) sont des valeurs par défaut à confirmer ; leur part abaisse le score « complétude du bâtiment ».",644    "Les prix de référence internes (◇) ne sont pas observés ; les prix détaillants observés (●) reflètent le prix affiché au détail, non les escomptes d'entrepreneur.",645    "La dépréciation dépend fortement de l'âge effectif et des conditions saisies ; la désuétude externe n'est jamais calculée sans preuve.",646    "Le facteur de localisation matériaux/équipement des régions éloignées est une hypothèse ; la main-d'œuvre suit les conventions collectives provinciales (CCQ).",647    ...(est.warnings.filter((w) => !w.startsWith("localisation")).map((w) => `Avertissement du moteur : ${w}.`)),648  ].forEach((t) => L.bullet(t));649650  /* ---- pieds de page avec total ---- */651  const range = doc.bufferedPageRange();652  for (let i = range.start; i < range.start + range.count; i++) {653    doc.switchToPage(i);654    pageFooter(doc, i + 1, range.count, generated);655  }656  doc.end();657  return done;658}659
Files main
Menu

Theme