Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/estimate.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 * Service d'estimation par la méthode du coût (serveur) :44 * - préremplissage depuis une propriété du rôle (MAMH) ;45 * - entrée par défaut (mode construction) ;46 * - exécution (contexte de prix → quantités → moteur) + sauvegarde47 * reproductible (estimation, lignes, instantané des prix) ;48 * - relecture.49 */50import { randomUUID } from "crypto";51import { getUnit, type UnitRow } from "../db";52import { estimateByUnitId } from "../estimator";53import { costDatabaseVersion, getCostDb } from "./db";54import { buildContext, today } from "./catalog";55import { computeEstimate } from "./engine";56import { deriveQuantities } from "./geometry";57import { ASSEMBLY_VERSION } from "./seed/assemblies";58import { BUILDING_TYPES } from "./taxonomy";59import { sqftFromM2 } from "./units";60import type { AttributeSource, BuildingSpec, BuildingType, CostEstimate, CostInput, Quality } from "./types";61import { defaultInput } from "./estimate-defaults";6263export { defaultBuilding, defaultInput } from "./estimate-defaults";6465/* ------------------------------------------------- préremplissage MAMH */6667function buildingTypeFromUnit(u: UnitRow): BuildingType {68 switch (u.type_prop) {69 case "plex": return "plex";70 case "condo_ou_multi": return (u.nb_logements ?? 1) > 1 && (u.aire_etages_m2 ?? 0) > 400 ? "plex" : "condo";71 case "chalet": return "chalet";72 case "maison_mobile": return "mobile";73 case "unifamilial": {74 const lien = (u.lien_physique ?? "").toLowerCase();75 if (lien.includes("jumel")) return "semi_detached";76 if (lien.includes("rang")) return "row";77 if (lien.includes("intégré") || lien.includes("integre")) return "row";78 return "detached";79 }80 default: return "other";81 }82}8384export interface PropertyPrefill {85 input: CostInput;86 unit: { id: string; adresse: string | null; municipalite: string | null; typeProp: string; genre: string | null; lien: string | null; cubf: number | null; cubfLibelle: string | null; nbLogements: number | null; aireM2: number | null; terrainM2: number | null };87 missing: string[]; // champs à saisir manuellement88}8990/** Préremplit une entrée de coût depuis une unité d'évaluation (source MAMH). */91export function prefillFromProperty(id: string): PropertyPrefill | null {92 const u = getUnit(id);93 if (!u) return null;94 const input = defaultInput();95 const src: Partial<Record<string, AttributeSource>> = {};96 const missing: string[] = [];97 input.mode = "property";98 input.propertyId = u.id_provinc;99 input.address = [u.adresse, u.apt ? `app. ${u.apt}` : null].filter(Boolean).join(", ") || null;100 input.municipality = u.municipalite;101 input.lat = u.lat;102 input.lng = u.lng;103 const b = input.building;104 b.type = buildingTypeFromUnit(u);105 src.type = "MAMH";106 if (u.aire_etages_m2 && u.aire_etages_m2 > 15) { b.grossFloorAreaSqft = Math.round(sqftFromM2(u.aire_etages_m2)); src.grossFloorAreaSqft = "MAMH"; } else { missing.push("grossFloorAreaSqft"); src.grossFloorAreaSqft = "assumed"; }107 if (u.nb_etages && u.nb_etages > 0) { b.stories = Math.max(1, Math.round(u.nb_etages)); src.stories = "MAMH"; } else {108 const g = (u.genre_construction ?? "").toLowerCase();109 b.stories = g.includes("plain-pied") || g.includes("unimodulaire") ? 1 : g.includes("étages entiers") ? 2 : g.includes("mansard") ? 1.5 : g.includes("décal") ? 1.5 : 1;110 src.stories = g ? "derived" : "assumed";111 if (!g) missing.push("stories");112 }113 if (b.stories === 1.5) b.stories = 2; // étage mansardé / niveaux décalés : 2 niveaux de structure114 if (u.annee_construction && u.annee_construction > 1600) { b.yearBuilt = u.annee_construction; src.yearBuilt = u.annee_estimee === "E" ? "derived" : "MAMH"; } else missing.push("yearBuilt");115 b.units = Math.max(1, u.nb_logements ?? 1);116 src.units = u.nb_logements ? "MAMH" : "assumed";117 // hypothèses par défaut (à confirmer par l'utilisateur) — marquées « assumed »118 for (const k of ["basement", "garage", "siding", "roof", "heating", "bathrooms", "kitchenQuality", "quality", "windows", "foundation"]) { src[k] = "assumed"; missing.push(k); }119 if (b.type === "plex") { b.kitchens = b.units; b.bathrooms = b.units; b.quality = "standard"; }120 if (b.type === "mobile") { b.foundation = "piers"; b.basement = "none"; b.stories = 1; }121 if (b.type === "condo") { b.basement = "none"; }122 if (b.grossFloorAreaSqft > 2600 && b.type === "detached") { b.bathrooms = 2; b.powderRooms = 1; }123 if (b.type === "chalet") { b.quality = "standard"; }124 // terrain et rôle125 input.roll = { landValue: u.valeur_terrain, buildingValue: u.valeur_batiment, totalValue: u.valeur_role, year: 2026 };126 if (u.valeur_terrain && u.valeur_terrain > 0) input.land = { value: u.valeur_terrain, source: "role", rollYear: 2026, method: "Valeur du terrain au rôle d'évaluation foncière 2026 (MAMH)" };127 else { input.land = { value: null, source: "none", rollYear: null, method: "" }; missing.push("landValue"); }128 input.depreciation.economicLife = BUILDING_TYPES.find((t) => t.key === b.type)?.economicLife ?? 60;129 input.attributeSources = src;130 return {131 input,132 unit: { id: u.id_provinc, adresse: u.adresse, municipalite: u.municipalite, typeProp: u.type_prop, genre: u.genre_construction, lien: u.lien_physique, cubf: u.cubf, cubfLibelle: u.cubf_libelle, nbLogements: u.nb_logements, aireM2: u.aire_etages_m2, terrainM2: u.superficie_terrain_m2 },133 missing,134 };135}136137/* --------------------------------------------------------------- exécution */138139export interface RunOptions {140 save?: boolean;141 sessionId?: string | null;142 otherReadings?: CostEstimate["otherReadings"];143}144145export function runEstimate(input: CostInput, opts: RunOptions = {}): CostEstimate {146 const d = getCostDb();147 const asOf = input.priceDate ?? today();148 const ctx = buildContext({ asOf, locationCode: input.locationCode, municipality: input.municipality, lat: input.lat, lng: input.lng }, d);149 const derived = deriveQuantities(input.building, input.quantityOverrides, input.mode === "listing" ? "AI" : "user", input.excludedAssemblies);150 const id = randomUUID();151 const est = computeEstimate(input, derived.lines, ctx, { id, createdAt: new Date().toISOString(), costDatabaseVersion: costDatabaseVersion(d), assemblyVersion: String(ASSEMBLY_VERSION) });152 est.warnings.push(...derived.warnings, `localisation : ${ctx.locationMethod}`);153 est.otherReadings = opts.otherReadings ?? (input.propertyId ? otherReadingsForProperty(input.propertyId) : null);154 if (opts.save !== false) saveEstimate(est, ctx, opts.sessionId ?? null);155 return est;156}157158/** Les autres lectures de la valeur pour une propriété du rôle (hédonique, comparables, hybride, rôle). */159export function otherReadingsForProperty(id: string): CostEstimate["otherReadings"] {160 try {161 const e = estimateByUnitId(id);162 if (!e?.unit) return null;163 return { hedonic: e.result.modelEstimate ?? null, comparables: e.result.compsEstimate ?? null, hybrid: e.result.estimate ?? null, askingPrice: null, rollValue: e.unit.valeurRole, rollBuilding: e.unit.specs.valeurBatiment, rollLand: e.unit.specs.valeurTerrain };164 } catch {165 return null;166 }167}168169function saveEstimate(est: CostEstimate, ctx: ReturnType<typeof buildContext>, sessionId: string | null): void {170 const d = getCostDb();171 const tx = d.transaction(() => {172 d.prepare(`INSERT INTO cost_estimates(id,property_id,listing_uid,user_session_id,mode,location_code,municipality,estimate_date,price_date,building_type,quality_level,area_sqft,direct_cost,indirect_cost,contractor_overhead,contractor_profit,contingency,replacement_cost_new,rcn_low,rcn_high,physical_depreciation,functional_obsolescence,external_obsolescence,depreciated_improvement_value,land_value,cost_approach_value,confidence_score,confidence_letter,method_version,cost_database_version,assembly_version,input_json,result_json,assumptions_json)173 VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).run(174 est.id, est.input.propertyId, est.input.listingUid, sessionId, est.input.mode, est.location.code, est.input.municipality, est.createdAt, est.priceDate, est.input.building.type, est.input.building.quality, est.input.building.grossFloorAreaSqft,175 est.directCost, est.indirectCost, est.contractorOverhead, est.contractorProfit, est.contingency, est.replacementCostNew, est.range.p10, est.range.p90, est.depreciation.physical, est.depreciation.functional, est.depreciation.external,176 est.depreciation.depreciatedImprovementValue, est.landValue, est.costApproachValue, est.confidence.total, est.confidence.letter, est.methodVersion, est.costDatabaseVersion, est.assemblyVersion,177 JSON.stringify(est.input), JSON.stringify(stripForStorage(est)), JSON.stringify({ params: est.input.params, depreciation: est.input.depreciation, land: est.input.land, attributeSources: est.input.attributeSources, warnings: est.warnings }),178 );179 const ins = d.prepare(`INSERT INTO cost_estimate_lines(estimate_id,assembly_code,category,quantity,unit,material_cost,labour_cost,equipment_cost,direct_cost,location_adjustment,adjusted_cost,source_summary,confidence_score,calculation_json) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)`);180 for (const l of est.lines) {181 ins.run(est.id, l.assemblyCode, l.category, l.quantity, l.unit, l.material, l.labour, l.equipment, l.direct, l.locationAdjustment, l.adjusted,182 [...new Set(l.unitDetail.components.map((c) => c.provenance.source))].join(" · "), l.confidence, JSON.stringify({ formula: l.quantityFormula, quantitySource: l.quantitySource, unitCost: l.unitCost, sigma: l.sigma, components: l.unitDetail.components }));183 }184 const used = new Set(est.lines.flatMap((l) => l.unitDetail.components.map((c) => c.itemCode).filter(Boolean)));185 const prices = Object.fromEntries([...ctx.prices.entries()].filter(([k]) => used.has(k)));186 d.prepare("INSERT INTO cost_estimate_snapshots(estimate_id,snapshot_date,prices_json,labour_json,location_json) VALUES(?,?,?,?,?)")187 .run(est.id, est.priceDate, JSON.stringify(prices), JSON.stringify(Object.fromEntries(ctx.labour)), JSON.stringify(ctx.location));188 });189 tx();190}191192/** Le résultat complet est stocké tel quel (JSON) — sans doublons volumineux. */193function stripForStorage(est: CostEstimate): CostEstimate {194 return est;195}196197export function getEstimate(id: string): CostEstimate | null {198 const r = getCostDb().prepare("SELECT result_json FROM cost_estimates WHERE id=?").get(id) as { result_json: string } | undefined;199 if (!r) return null;200 return JSON.parse(r.result_json) as CostEstimate;201}202203export function recentEstimatesForProperty(propertyId: string, limit = 5): { id: string; createdAt: string; rcn: number; value: number; letter: string }[] {204 return (getCostDb().prepare("SELECT id, created_at, replacement_cost_new rcn, cost_approach_value value, confidence_letter letter FROM cost_estimates WHERE property_id=? ORDER BY created_at DESC LIMIT ?").all(propertyId, limit) as Record<string, unknown>[])205 .map((r) => ({ id: String(r.id), createdAt: String(r.created_at), rcn: Number(r.rcn), value: Number(r.value), letter: String(r.letter) }));206}207208/** Normalise/valide une entrée reçue du client (bornes, valeurs par défaut). */209export function sanitizeInput(raw: unknown): CostInput {210 const base = defaultInput();211 if (!raw || typeof raw !== "object") return base;212 const r = raw as Partial<CostInput>;213 const b: BuildingSpec = { ...base.building, ...(r.building ?? {}) };214 b.grossFloorAreaSqft = clamp(Number(b.grossFloorAreaSqft) || 1800, 200, 30000);215 b.footprintSqft = b.footprintSqft != null ? clamp(Number(b.footprintSqft), 100, 20000) : null;216 b.stories = clamp(Number(b.stories) || 1, 1, 6);217 b.units = clamp(Number(b.units) || 1, 1, 12);218 b.kitchens = clamp(Number(b.kitchens) || 1, 0, 12);219 b.bathrooms = clamp(Number(b.bathrooms) || 0, 0, 12);220 b.powderRooms = clamp(Number(b.powderRooms) || 0, 0, 6);221 b.roofPitch = clamp(Number(b.roofPitch) || 6, 0, 18);222 b.deckSqft = clamp(Number(b.deckSqft) || 0, 0, 3000);223 b.drivewaySqft = clamp(Number(b.drivewaySqft) || 0, 0, 10000);224 b.fenceLinFt = clamp(Number(b.fenceLinFt) || 0, 0, 2000);225 b.landscapingSqft = clamp(Number(b.landscapingSqft) || 0, 0, 40000);226 b.basementFinishedPct = clamp(Number(b.basementFinishedPct) || 0, 0, 1);227 b.garage = { type: b.garage?.type ?? "none", spaces: clamp(Number(b.garage?.spaces) || 0, 0, 4), areaSqft: b.garage?.areaSqft != null ? clamp(Number(b.garage.areaSqft), 100, 2000) : null };228 b.yearBuilt = b.yearBuilt != null && Number(b.yearBuilt) > 1600 ? Math.round(Number(b.yearBuilt)) : null;229 b.windowCount = b.windowCount != null ? clamp(Math.round(Number(b.windowCount)), 0, 200) : null;230 b.siding = Object.fromEntries(Object.entries(b.siding ?? {}).filter(([, v]) => typeof v === "number" && v > 0));231 b.flooring = Object.fromEntries(Object.entries(b.flooring ?? {}).filter(([, v]) => typeof v === "number" && v > 0));232 const q = (x: unknown): Quality => (["economy", "standard", "superior", "prestige"].includes(String(x)) ? (x as Quality) : "standard");233 b.quality = q(b.quality); b.kitchenQuality = q(b.kitchenQuality); b.bathroomQuality = q(b.bathroomQuality);234 const params = { indirect: { ...base.params.indirect, ...(r.params?.indirect ?? {}) }, overheadPct: clamp(Number(r.params?.overheadPct ?? base.params.overheadPct), 0, 40), profitPct: clamp(Number(r.params?.profitPct ?? base.params.profitPct), 0, 40), contingencyPct: clamp(Number(r.params?.contingencyPct ?? base.params.contingencyPct), 0, 40) };235 for (const k of Object.keys(params.indirect) as (keyof typeof params.indirect)[]) params.indirect[k] = clamp(Number(params.indirect[k]) || 0, 0, 30);236 const dep = { ...base.depreciation, ...(r.depreciation ?? {}) };237 dep.economicLife = clamp(Number(dep.economicLife) || 60, 10, 150);238 dep.effectiveAge = dep.effectiveAge != null && dep.effectiveAge !== ("" as unknown) ? clamp(Number(dep.effectiveAge), 0, 200) : null;239 dep.functional = Array.isArray(dep.functional) ? dep.functional.slice(0, 20).map((f) => ({ id: String(f.id ?? randomUUID()), type: String(f.type ?? ""), curable: !!f.curable, costToCure: clamp(Number(f.costToCure) || 0, 0, 5e6), valueLoss: clamp(Number(f.valueLoss) || 0, 0, 5e6), notes: String(f.notes ?? "").slice(0, 500) })) : [];240 dep.externalValueLoss = clamp(Number(dep.externalValueLoss) || 0, 0, 5e6);241 dep.componentConditions = dep.componentConditions ?? {};242 const land = { ...base.land, ...(r.land ?? {}) };243 land.value = land.value != null && land.value !== ("" as unknown) ? clamp(Number(land.value), 0, 5e7) : null;244 const overrides: Record<string, number> = {};245 for (const [k, v] of Object.entries(r.quantityOverrides ?? {})) if (typeof v === "number" && v >= 0 && /^[A-Z0-9/.-]+$/.test(k)) overrides[k] = clamp(v, 0, 1e6);246 return {247 ...base, ...r, building: b, params, depreciation: dep, land, quantityOverrides: overrides,248 excludedAssemblies: Array.isArray(r.excludedAssemblies) ? r.excludedAssemblies.filter((x) => typeof x === "string").slice(0, 100) : [],249 attributeSources: r.attributeSources ?? {}, priceDate: r.priceDate && /^\d{4}-\d{2}-\d{2}$/.test(r.priceDate) ? r.priceDate : null,250 mode: r.mode === "property" || r.mode === "listing" ? r.mode : "construction",251 propertyId: r.propertyId ? String(r.propertyId).slice(0, 40) : null, listingUid: r.listingUid ? String(r.listingUid).slice(0, 80) : null,252 municipality: r.municipality ? String(r.municipality).slice(0, 120) : null, address: r.address ? String(r.address).slice(0, 200) : null,253 lat: typeof r.lat === "number" ? r.lat : null, lng: typeof r.lng === "number" ? r.lng : null, locationCode: r.locationCode ? String(r.locationCode).slice(0, 20) : null,254 roll: r.roll ?? null,255 };256}257258const clamp = (v: number, lo: number, hi: number) => (Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : lo);259