Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/engine.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 * Moteur de la méthode du coût — calcul PUR et DÉTERMINISTE :44 * même entrée + même contexte de prix = même résultat, aucune IA.45 *46 * matériau_i = Q × qté_i × (1 + pertes_i) × prix_i × FacteurMatériau47 * main-d'œuvre = Q × heures_i × taux_métier_i × FacteurMainDœuvre48 * équipement = Q × équip_i × FacteurÉquipement49 * Direct = Σ lignes ; Indirects = Direct × Σ pct50 * FG = (Direct + Indirects) × pct ; Profit = (Direct + Indirects + FG) × pct51 * Contingence = (Direct + Indirects) × pct52 * RCN = Direct + Indirects + FG + Profit + Contingence53 * V_coût = V_terrain + RCN − (D_phys + D_fonct + D_ext)54 */55import type {56 Assembly, AssemblyUnitCost, BenchmarkCheck, CategoryTotal, Condition, ConfidenceBreakdown, CostEstimate, CostInput, CostItem,57 CostLocation, DepreciationComponentRow, DepreciationResult, EstimateLine, ItemPrice, LabourRate, Provenance, QuantityLine, UxCategory,58} from "./types";59import { BUILDING_TYPES, CONDITION_GROUPS, INDIRECT_LABELS, METHOD_VERSION, UX_CATEGORIES, categoryLabel } from "./taxonomy";6061export interface BenchmarkRow {62 source: string;63 buildingType: string; // single_family | townhouse | plex | condo | cottage64 market: string;65 unit: string;66 low: number;67 high: number;68 midpoint: number | null;69 year: number;70 notes: string | null;71}7273export interface ConditionRule {74 effectiveAgeRatio: number;75 economicLife: number;76}7778/** Contexte de prix : tout ce dont le moteur a besoin, lu une seule fois (instantané). */79export interface PricingContext {80 asOf: string;81 items: Map<string, CostItem>;82 prices: Map<string, ItemPrice>;83 labour: Map<string, LabourRate>; // par code de métier (compagnon, résidentiel léger)84 assemblies: Map<string, Assembly>;85 location: CostLocation;86 conditionRules: Map<string, Map<Condition, ConditionRule>>;87 benchmarks: BenchmarkRow[];88 /** taux horaire de repli (hypothèse) si un métier manque */89 fallbackHourlyRate: number;90}9192export const FALLBACK_HOURLY_RATE = 85; // $/h coût employeur — hypothèse si aucune grille93const Z90 = 1.2816;94const MAX_DEPRECIATION_PCT = 0.9;9596const r2 = (x: number) => Math.round(x * 100) / 100;97const r0 = (x: number) => Math.round(x);9899/* ------------------------------------------------------ coût d'assemblage */100101function priceSigmaPct(p: ItemPrice | undefined): number {102 if (!p) return 0.2;103 if (p.sourceCount >= 2 && p.price > 0) return Math.max(0.04, (p.high - p.low) / (2 * Z90 * p.price));104 switch (p.kind) {105 case "observed": case "official": return 0.08;106 case "indexed": return 0.1;107 case "derived": return 0.1;108 case "reference": return 0.15;109 default: return 0.2;110 }111}112113export function assemblyUnitCost(asm: Assembly, ctx: PricingContext): AssemblyUnitCost {114 let material = 0, labour = 0, equipment = 0, varSum = 0, observedMaterial = 0;115 let freshest: string | null = null;116 const components: AssemblyUnitCost["components"] = [];117 for (const c of asm.components) {118 const item = c.itemCode ? ctx.items.get(c.itemCode) : undefined;119 const price = c.itemCode ? ctx.prices.get(c.itemCode) : undefined;120 const unitPrice = price?.price ?? 0;121 const isEquipItem = item?.materialClass === "equipment" || item?.materialClass === "rental";122 const qty = c.quantity * (1 + c.wasteFactor);123 const matCost = item && !isEquipItem ? qty * unitPrice : 0;124 const eqItem = item && isEquipItem ? qty * unitPrice : 0;125 const trade = c.trade ?? item?.trade ?? null;126 const rate = trade ? ctx.labour.get(trade) : undefined;127 const hourly = c.labourHours > 0 ? (rate?.totalEmployerCost ?? ctx.fallbackHourlyRate) : null;128 const labCost = c.labourHours * (hourly ?? 0);129 const eqCost = c.equipmentCost + eqItem;130 material += matCost;131 labour += labCost;132 equipment += eqCost;133 if (price && (price.kind === "observed" || price.kind === "official" || price.kind === "indexed")) observedMaterial += matCost;134 if (price?.observedAt && (!freshest || price.observedAt > freshest)) freshest = price.observedAt;135 const sp = priceSigmaPct(price);136 varSum += (matCost * sp) ** 2 + (labCost * 0.15) ** 2 + (eqCost * 0.2) ** 2;137 const prov: Provenance = price138 ? { kind: price.kind, source: price.sources.map((s) => s.source).join(", ") || "—", sourceUrl: price.sources[0]?.url ?? null, observedAt: price.observedAt, confidence: price.confidence, note: price.note }139 : { kind: "assumption", source: c.itemCode ? "aucun prix" : "Vrai-Prix — hypothèse de productivité", confidence: c.itemCode ? 0 : 40, note: c.notes };140 const rateProv: Provenance | null = c.labourHours > 0141 ? rate142 ? { kind: "official", source: rate.source, sourceUrl: rate.sourceUrl, effectiveDate: rate.effectiveFrom, confidence: rate.confidence, note: `${rate.tradeNameFr} — ${rate.classification}, ${rate.sector}` }143 : { kind: "assumption", source: "Vrai-Prix — taux horaire de repli", confidence: 30, note: `Aucune grille pour le métier « ${trade ?? "?"} » : ${ctx.fallbackHourlyRate} $/h (hypothèse)` }144 : null;145 components.push({146 itemCode: c.itemCode, nameFr: item?.nameFr ?? (c.labourHours ? "Main-d'œuvre" : "Équipement"), nameEn: item?.nameEn ?? (c.labourHours ? "Labour" : "Equipment"), unit: item?.unit ?? "h",147 quantity: c.quantity, wasteFactor: c.wasteFactor, unitPrice: r2(unitPrice), materialCost: r2(matCost), labourHours: c.labourHours, trade, hourlyRate: hourly, labourCost: r2(labCost), equipmentCost: r2(eqCost),148 provenance: prov, rateProvenance: rateProv,149 });150 }151 const direct = material + labour + equipment;152 return {153 code: asm.code, unit: asm.unit, material: r2(material), labour: r2(labour), equipment: r2(equipment), direct: r2(direct),154 sigmaPct: direct > 0 ? Math.sqrt(varSum) / direct : 0.2, observedShare: material > 0 ? observedMaterial / material : 0, components, freshestObservation: freshest,155 };156}157158/* ------------------------------------------------------------- estimation */159160const QTY_UNCERTAINTY: Record<string, number> = { derived: 0.1, AI: 0.15, user: 0.03, listing: 0.05, MAMH: 0.03, cadastral: 0.02, assumed: 0.2 };161162export function computeEstimate(input: CostInput, quantities: QuantityLine[], ctx: PricingContext, meta: { id: string; createdAt: string; costDatabaseVersion: string; assemblyVersion: string }): CostEstimate {163 const loc = ctx.location;164 const warnings: string[] = [];165 const lines: EstimateLine[] = [];166 let unpriced = 0;167168 for (const q of quantities) {169 const asm = ctx.assemblies.get(q.assemblyCode);170 if (!asm) { warnings.push(`assemblage inconnu : ${q.assemblyCode}`); continue; }171 const u = assemblyUnitCost(asm, ctx);172 if (u.direct <= 0) unpriced++;173 const material = u.material * q.quantity;174 const labour = u.labour * q.quantity;175 const equipment = u.equipment * q.quantity;176 const direct = material + labour + equipment;177 const adjusted = material * loc.materialFactor + labour * loc.labourFactor + equipment * loc.equipmentFactor;178 const qUnc = QTY_UNCERTAINTY[q.source] ?? 0.1;179 const sigma = Math.sqrt((adjusted * u.sigmaPct) ** 2 + (adjusted * qUnc) ** 2);180 const conf = Math.round(100 * (0.6 * u.observedShare + 0.4 * (1 - Math.min(1, u.sigmaPct / 0.3))));181 lines.push({182 assemblyCode: asm.code, nameFr: asm.nameFr, nameEn: asm.nameEn, category: asm.category, quantity: q.quantity, unit: asm.unit, quantitySource: q.source, quantityFormula: q.formula,183 unitCost: u.direct, material: r0(material), labour: r0(labour), equipment: r0(equipment), direct: r0(direct), locationAdjustment: r0(adjusted - direct), adjusted: r0(adjusted),184 sigma: r0(sigma), observedShare: u.observedShare, confidence: conf, economicLife: asm.economicLife, conditionGroup: asm.conditionGroup, unitDetail: u,185 });186 }187 lines.sort((a, b) => (UX_CATEGORIES.find((c) => c.key === a.category)?.order ?? 99) - (UX_CATEGORIES.find((c) => c.key === b.category)?.order ?? 99) || a.nameFr.localeCompare(b.nameFr));188189 const directMaterial = r0(lines.reduce((s, l) => s + l.material * loc.materialFactor, 0));190 const directLabour = r0(lines.reduce((s, l) => s + l.labour * loc.labourFactor, 0));191 const directEquipment = r0(lines.reduce((s, l) => s + l.equipment * loc.equipmentFactor, 0));192 // le direct est la somme exacte des trois composantes (les lignes sont arrondies individuellement)193 const directCost = directMaterial + directLabour + directEquipment;194195 const categories: CategoryTotal[] = UX_CATEGORIES.filter((c) => lines.some((l) => l.category === c.key)).map((c) => {196 const ls = lines.filter((l) => l.category === c.key);197 const adjusted = ls.reduce((s, l) => s + l.adjusted, 0);198 return {199 category: c.key, labelFr: c.fr, labelEn: c.en,200 material: r0(ls.reduce((s, l) => s + l.material * loc.materialFactor, 0)), labour: r0(ls.reduce((s, l) => s + l.labour * loc.labourFactor, 0)), equipment: r0(ls.reduce((s, l) => s + l.equipment * loc.equipmentFactor, 0)),201 direct: r0(ls.reduce((s, l) => s + l.direct, 0)), adjusted: r0(adjusted), sharePct: directCost > 0 ? r2((100 * adjusted) / directCost) : 0,202 };203 });204205 const p = input.params;206 const indirect = (Object.keys(INDIRECT_LABELS) as (keyof typeof INDIRECT_LABELS)[]).map((key) => ({ key, labelFr: INDIRECT_LABELS[key].fr, labelEn: INDIRECT_LABELS[key].en, pct: p.indirect[key], amount: r0((directCost * p.indirect[key]) / 100) }));207 const indirectCost = indirect.reduce((s, i) => s + i.amount, 0);208 const contractorOverhead = r0(((directCost + indirectCost) * p.overheadPct) / 100);209 const contractorProfit = r0(((directCost + indirectCost + contractorOverhead) * p.profitPct) / 100);210 const contingency = r0(((directCost + indirectCost) * p.contingencyPct) / 100);211 const replacementCostNew = r0(directCost + indirectCost + contractorOverhead + contractorProfit + contingency);212213 // fourchette : composante aléatoire (racine des carrés des lignes) + systématique (localisation 3 %, modèle d'assemblages 5 %)214 const randomSigma = Math.sqrt(lines.reduce((s, l) => s + l.sigma ** 2, 0));215 const locUnc = loc.confidence >= 75 ? 0.02 : 0.04;216 const systematicSigma = directCost * Math.sqrt(locUnc ** 2 + 0.05 ** 2);217 const sigmaDirect = Math.sqrt(randomSigma ** 2 + systematicSigma ** 2);218 const scale = directCost > 0 ? replacementCostNew / directCost : 1;219 const sigma = sigmaDirect * scale;220 const range = { p10: r0(replacementCostNew - Z90 * sigma), p90: r0(replacementCostNew + Z90 * sigma), sigma: r0(sigma), low: r0(replacementCostNew - Z90 * sigma), high: r0(replacementCostNew + Z90 * sigma) };221222 const gfa = Math.max(1, input.building.grossFloorAreaSqft);223 const perSqft = r2(replacementCostNew / gfa);224 const perM2 = r2(replacementCostNew / (gfa * 0.092903));225226 const depreciation = computeDepreciation(input, lines, replacementCostNew, directCost, ctx);227 const landValue = input.land.value ?? 0;228 if (input.land.value == null) warnings.push("land_missing");229 const costApproachValue = r0(landValue + depreciation.depreciatedImprovementValue);230231 const benchmarks = checkBenchmarks(input, ctx, perSqft);232 const materialObservedShare = directMaterial > 0 ? lines.reduce((s, l) => s + l.material * loc.materialFactor * l.observedShare, 0) / directMaterial : 0;233 const coverage = { materialObservedShare: r2(materialObservedShare), assembliesPriced: lines.length - unpriced, assembliesTotal: lines.length, pricingCoverage: lines.length ? r2((lines.length - unpriced) / lines.length) : 0 };234 const confidence = computeConfidence(input, lines, ctx, benchmarks, coverage, directLabour, directCost);235 if (unpriced) warnings.push(`${unpriced} assemblage(s) sans prix`);236237 return {238 id: meta.id, createdAt: meta.createdAt, methodVersion: METHOD_VERSION, costDatabaseVersion: meta.costDatabaseVersion, assemblyVersion: meta.assemblyVersion, priceDate: ctx.asOf,239 input, location: loc, quantities, lines, categories,240 directCost: r0(directCost), directMaterial: r0(directMaterial), directLabour: r0(directLabour), directEquipment: r0(directEquipment),241 indirect, indirectCost: r0(indirectCost), contractorOverhead, contractorProfit, contingency, replacementCostNew, range, perSqft, perM2,242 depreciation, landValue: r0(landValue), costApproachValue, confidence, benchmarks, coverage, otherReadings: null, warnings,243 };244}245246/* ----------------------------------------------------------- dépréciation */247248export function computeDepreciation(input: CostInput, lines: EstimateLine[], rcn: number, directCost: number, ctx: PricingContext): DepreciationResult {249 const d = input.depreciation;250 const year = Number(ctx.asOf.slice(0, 4));251 const chronologicalAge = input.building.yearBuilt && input.building.yearBuilt > 1600 ? Math.max(0, year - input.building.yearBuilt) : null;252 const economicLife = d.economicLife || BUILDING_TYPES.find((t) => t.key === input.building.type)?.economicLife || 60;253 const scale = directCost > 0 ? rcn / directCost : 1;254 let physical = 0;255 let physicalPct = 0;256 let effectiveAge: number | null = d.effectiveAge ?? chronologicalAge;257 const components: DepreciationComponentRow[] = [];258259 if (d.method === "components") {260 for (const g of CONDITION_GROUPS) {261 const ls = lines.filter((l) => l.conditionGroup === g.key);262 if (!ls.length) continue;263 const groupRcn = ls.reduce((s, l) => s + l.adjusted, 0) * scale;264 const lifeW = ls.reduce((s, l) => s + (l.economicLife ?? g.economicLife) * l.adjusted, 0) / Math.max(1, ls.reduce((s, l) => s + l.adjusted, 0));265 const life = Math.max(5, Math.round(lifeW));266 const cond = d.componentConditions[g.key] ?? null;267 const rule = cond ? ctx.conditionRules.get(g.key)?.get(cond) : undefined;268 let effAge: number;269 let ruleTxt: string;270 if (cond && rule) {271 effAge = rule.effectiveAgeRatio * life;272 ruleTxt = `condition « ${cond} » → âge effectif = ${rule.effectiveAgeRatio} × vie ${life} ans`;273 } else if (d.effectiveAge != null && g.key === "structure") {274 effAge = Math.min(d.effectiveAge, life);275 ruleTxt = `âge effectif saisi (${d.effectiveAge} ans), plafonné à la vie de la composante`;276 } else {277 effAge = Math.min(chronologicalAge ?? 0, life);278 ruleTxt = chronologicalAge != null ? `âge chronologique (${chronologicalAge} ans) plafonné à la vie ${life} ans — aucune condition saisie` : "âge inconnu → 0";279 }280 const pct = Math.min(MAX_DEPRECIATION_PCT, life > 0 ? effAge / life : 0);281 const dep = groupRcn * pct;282 physical += dep;283 components.push({ conditionGroup: g.key, labelFr: g.fr, labelEn: g.en, rcn: r0(groupRcn), economicLife: life, condition: cond, effectiveAge: r2(effAge), depreciationPct: r2(pct * 100), depreciation: r0(dep), remaining: r0(groupRcn - dep), rule: ruleTxt });284 }285 physicalPct = rcn > 0 ? physical / rcn : 0;286 effectiveAge = r2(physicalPct * economicLife);287 } else {288 const ea = effectiveAge ?? 0;289 physicalPct = Math.min(MAX_DEPRECIATION_PCT, economicLife > 0 ? ea / economicLife : 0);290 physical = rcn * physicalPct;291 }292 const functionalCurable = d.functional.filter((f) => f.curable).reduce((s, f) => s + (f.costToCure || 0), 0);293 const functionalIncurable = d.functional.filter((f) => !f.curable).reduce((s, f) => s + (f.valueLoss || 0), 0);294 const functional = functionalCurable + functionalIncurable;295 const external = Math.max(0, d.externalValueLoss || 0);296 const total = Math.min(rcn, physical + functional + external);297 return {298 method: d.method, chronologicalAge, effectiveAge, economicLife, physicalPct: r2(physicalPct * 100), physical: r0(physical), components,299 functionalCurable: r0(functionalCurable), functionalIncurable: r0(functionalIncurable), functional: r0(functional), external: r0(external), total: r0(total),300 depreciatedImprovementValue: r0(Math.max(0, rcn - total)),301 };302}303304/* -------------------------------------------------------------- confiance */305306function computeConfidence(input: CostInput, lines: EstimateLine[], ctx: PricingContext, benchmarks: BenchmarkCheck[], coverage: CostEstimate["coverage"], directLabour: number, directCost: number): ConfidenceBreakdown {307 const notesFr: string[] = [];308 const notesEn: string[] = [];309 // fraîcheur : âge moyen pondéré des observations310 let wAge = 0, wSum = 0;311 for (const l of lines) for (const c of l.unitDetail.components) {312 if (c.provenance.observedAt && (c.provenance.kind === "observed" || c.provenance.kind === "official")) {313 const age = (new Date(ctx.asOf).getTime() - new Date(c.provenance.observedAt).getTime()) / 86400000;314 const w = c.materialCost * l.quantity;315 wAge += age * w; wSum += w;316 }317 }318 const freshness = wSum > 0 ? Math.round(20 * Math.max(0, 1 - wAge / wSum / 180)) : 4;319 if (wSum === 0) { notesFr.push("Aucun prix observé récent : base de référence seulement."); notesEn.push("No recent observed price: reference base only."); }320 const cov = Math.round(20 * (0.7 * coverage.materialObservedShare + 0.3 * coverage.pricingCoverage));321 if (coverage.materialObservedShare < 0.5) { notesFr.push(`${Math.round(coverage.materialObservedShare * 100)} % du coût des matériaux repose sur des prix observés ; le reste sur des prix de référence (hypothèses).`); notesEn.push(`${Math.round(coverage.materialObservedShare * 100)} % of material cost rests on observed prices; the rest on reference prices (assumptions).`); }322 const location = ctx.location.confidence >= 75 ? 15 : ctx.location.confidence >= 55 ? 11 : 8;323 // main-d'œuvre : part des $ de main-d'œuvre appuyée sur une grille officielle324 let offLab = 0;325 for (const l of lines) for (const c of l.unitDetail.components) if (c.rateProvenance?.kind === "official") offLab += c.labourCost * l.quantity * ctx.location.labourFactor;326 const labour = directLabour > 0 ? Math.round(15 * Math.min(1, offLab / directLabour)) : 8;327 if (directLabour > 0 && offLab / directLabour < 0.9) { notesFr.push("Certains métiers utilisent le taux horaire de repli (aucune grille APCHQ/CCQ)."); notesEn.push("Some trades use the fallback hourly rate (no APCHQ/CCQ grid)."); }328 const withBench = benchmarks.filter((b) => b.status !== "unavailable");329 const bench = !withBench.length ? 5 : withBench.some((b) => b.status === "within") ? 10 : 3;330 if (!withBench.length) { notesFr.push("Aucun benchmark externe disponible pour ce type/marché."); notesEn.push("No external benchmark available for this type/market."); }331 else if (!withBench.some((b) => b.status === "within")) { notesFr.push("Écart important par rapport au benchmark externe."); notesEn.push("Large deviation from the external benchmark."); }332 const keys = ["grossFloorAreaSqft", "stories", "yearBuilt", "basement", "garage", "siding", "roof", "heating", "bathrooms", "kitchenQuality"];333 const known = keys.filter((k) => { const s = input.attributeSources[k]; return s && s !== "assumed" && s !== "derived"; }).length;334 const building = Math.round(20 * (known / keys.length));335 if (known < 7) { notesFr.push(`${keys.length - known} caractéristiques du bâtiment sur ${keys.length} sont supposées par défaut.`); notesEn.push(`${keys.length - known} of ${keys.length} building attributes are default assumptions.`); }336 const total = Math.max(0, Math.min(100, freshness + cov + location + labour + bench + building));337 const letter = total >= 80 ? "A" : total >= 65 ? "B" : total >= 50 ? "C" : "D";338 void directCost;339 return { freshness, coverage: cov, location, labour, benchmarks: bench, building, total, letter, notesFr, notesEn };340}341342/* ------------------------------------------------------------- benchmarks */343344export function benchmarkTypeFor(t: CostInput["building"]["type"]): string {345 switch (t) {346 case "detached": case "chalet": return "single_family";347 case "semi_detached": case "row": return "townhouse";348 case "plex": return "plex";349 case "condo": return "condo";350 default: return "single_family";351 }352}353354export function checkBenchmarks(input: CostInput, ctx: PricingContext, perSqft: number): BenchmarkCheck[] {355 const bt = benchmarkTypeFor(input.building.type);356 const market = ctx.location.code === "QC-QUE" || ctx.location.code === "QC-LEV" ? "Québec" : ctx.location.code === "QC-GAT" ? "Ottawa-Gatineau" : "Montréal";357 const rows = ctx.benchmarks.filter((b) => b.buildingType === bt);358 const chosen = rows.filter((b) => b.market === market);359 const use = chosen.length ? chosen : rows.filter((b) => b.market === "Montréal");360 return use.map((b) => {361 const within = perSqft >= b.low && perSqft <= b.high;362 const status: BenchmarkCheck["status"] = within ? "within" : perSqft < b.low ? "below" : "above";363 const ref = within ? null : perSqft < b.low ? b.low : b.high;364 return { source: b.source, buildingType: b.buildingType, market: b.market, unit: b.unit, low: b.low, high: b.high, midpoint: b.midpoint, year: b.year, estimatePerUnit: perSqft, status, deviationPct: ref ? r2(((perSqft - ref) / ref) * 100) : 0, notes: b.notes ? `${b.notes}${b.market !== market ? " — marché de substitution (Montréal)" : ""}` : b.market !== market ? "marché de substitution (Montréal)" : null };365 });366}367368/** Libellé de catégorie (réexport pratique). */369export const catLabel = (k: UxCategory, fr: boolean) => categoryLabel(k, fr);370