Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/ai/mapping.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 * Faits fusionnés → entrée du moteur de coût (§116-118, 124-125, 143-149, 164).44 * Le mapping est déterministe : même JSON technique + même instantané de prix45 * = même résultat. L'IA n'intervient pas ici. Module PUR.46 */47import { defaultInput } from "../estimate-defaults";48import { deriveQuantities } from "../geometry";49import { BUILDING_TYPES, CONDITION_GROUPS } from "../taxonomy";50import type { AttributeSource, CostInput, Quality } from "../types";51import type { MergedFacts } from "./merge";52import type { ModelOutput } from "./schema";5354export const AI_QTY_MIN_CONFIDENCE = 0.6;5556export interface MappingResult {57 input: CostInput;58 /** quantités d'assemblage retenues depuis l'IA (code → {qty, confidence}) */59 aiQuantities: Record<string, { quantity: number; confidence: number; evidence: string[] }>;60 notes: string[];61}6263function kitchenAssembly(q: Quality): string {64 return q === "economy" ? "KIT-ECONOMY" : q === "superior" ? "KIT-SUPERIOR" : q === "prestige" ? "KIT-PRESTIGE" : "KIT-STANDARD";65}6667export function mapToCostInput(m: MergedFacts, ai: ModelOutput, ctx: { listingUid: string; address: string | null; municipality: string | null; lat: number | null; lng: number | null; unitId: string | null; landValue: number | null; roll: CostInput["roll"]; assemblyCodes: Set<string> }): MappingResult {68 const input = defaultInput();69 const notes: string[] = [];70 input.mode = "listing";71 input.listingUid = ctx.listingUid;72 input.propertyId = ctx.unitId;73 input.address = ctx.address;74 input.municipality = ctx.municipality;75 input.lat = ctx.lat; input.lng = ctx.lng;76 const b = input.building;77 const src: Partial<Record<string, AttributeSource>> = {};78 const set = <K extends keyof typeof b>(k: K, v: (typeof b)[K], s: AttributeSource) => { b[k] = v; src[k as string] = s; };79 set("type", m.buildingType.value, m.buildingType.source);80 set("quality", m.quality.value, m.quality.source);81 set("grossFloorAreaSqft", Math.round(m.grossFloorAreaSqft.value), m.grossFloorAreaSqft.source);82 set("footprintSqft", m.footprintSqft.value, m.footprintSqft.source);83 set("stories", Math.max(1, Math.round(m.stories.value)), m.stories.source);84 set("yearBuilt", m.yearBuilt.value, m.yearBuilt.source);85 set("basement", m.basement.value, m.basement.source);86 set("basementFinishedPct", m.basementFinishedPct.value, m.basementFinishedPct.source);87 set("garage", { type: m.garage.value.type, spaces: m.garage.value.spaces, areaSqft: m.garage.value.areaSqft }, m.garage.source);88 set("structure", m.structure.value, m.structure.source);89 set("foundation", m.foundation.value, m.foundation.source);90 set("siding", m.siding.value, m.siding.source);91 set("roof", m.roof.value, m.roof.source);92 set("roofGeometry", m.roofGeometry.value, m.roofGeometry.source);93 set("roofPitch", m.roofGeometry.value === "flat" ? 0 : Math.max(2, Math.min(14, m.roofPitch.value || 6)), m.roofPitch.source);94 set("windows", m.windows.value, m.windows.source);95 set("windowCount", m.windowCount.value != null && m.windowCount.confidence >= AI_QTY_MIN_CONFIDENCE ? Math.round(m.windowCount.value) : null, m.windowCount.source);96 set("heating", m.heating.value, m.heating.source);97 set("hasAirConditioning", m.hasAirConditioning.value, m.hasAirConditioning.source);98 set("hasAirExchanger", m.hasAirExchanger.value, m.hasAirExchanger.source);99 set("kitchens", Math.max(1, Math.round(m.kitchens.value)), m.kitchens.source);100 set("kitchenQuality", m.kitchenQuality.value, m.kitchenQuality.source);101 set("bathrooms", Math.max(0, Math.round(m.bathrooms.value)), m.bathrooms.source);102 set("powderRooms", Math.max(0, Math.round(m.powderRooms.value)), m.powderRooms.source);103 set("bathroomQuality", m.bathroomQuality.value, m.bathroomQuality.source);104 set("bedrooms", m.bedrooms.value, m.bedrooms.source);105 set("flooring", m.flooring.value ?? {}, m.flooring.source);106 set("deckSqft", Math.round(m.deckSqft.value), m.deckSqft.source);107 set("driveway", m.driveway.value, m.driveway.source);108 set("drivewaySqft", m.driveway.value === "none" ? 0 : Math.round(m.drivewaySqft.value), m.drivewaySqft.source);109 set("fenceLinFt", Math.round(m.fenceLinFt.value), m.fenceLinFt.source);110 set("pool", m.pool.value, m.pool.source);111 set("units", Math.max(1, Math.round(m.units.value)), m.units.source);112 input.attributeSources = src;113114 // quantités IA fiables → surcharges d'assemblages (l'IA propose, le moteur calcule le reste)115 const aiQuantities: MappingResult["aiQuantities"] = {};116 const takeQty = (code: string, f: { value: number | null; confidence: number; evidence: string[] }, scale = 1) => {117 if (f.value != null && f.value > 0 && f.confidence >= AI_QTY_MIN_CONFIDENCE && ctx.assemblyCodes.has(code)) {118 aiQuantities[code] = { quantity: Math.round(f.value * scale * 100) / 100, confidence: f.confidence, evidence: f.evidence };119 input.quantityOverrides[code] = aiQuantities[code].quantity;120 }121 };122 takeQty(kitchenAssembly(m.kitchenQuality.value), m.kitchenLinearFt);123 takeQty("OPN-DOOR-INT-" + (m.quality.value === "superior" || m.quality.value === "prestige" ? "SOLID" : "HOLLOW"), m.interiorDoorCount);124 // assemblages suggérés par l'IA avec quantité soutenue par une preuve : acceptés seulement s'ils125 // font partie des assemblages que le moteur retient pour CE bâtiment (variantes de qualité/type déjà126 // choisies : cuisine, salles de bain, fenêtres, portes, chauffage…) ou d'une famille additive.127 const engineCodes = new Set(deriveQuantities(b, {}, "AI", input.excludedAssemblies).lines.map((l) => l.assemblyCode));128 const ADDITIVE = /^(EXT-DECK|EXT-FENCE|EXT-DRIVEWAY|EXT-POOL|EXT-STEPS|EXT-GUTTERS|OPN-SKYLIGHT|OPN-DOOR-GARAGE|ELE-EV-CHARGER|ELE-LIGHTING-EXT|MEC-HRV|MEC-HEATPUMP-WALL|MEC-CENTRAL-AC|STR-STAIRS|INT-CLOSET)/;129 for (const a of ai.assemblies) {130 if (a.quantity == null || a.quantity <= 0 || a.confidence < AI_QTY_MIN_CONFIDENCE || !ctx.assemblyCodes.has(a.assembly_code) || a.assembly_code in aiQuantities) continue;131 // ne jamais laisser l'IA surcharger la géométrie que le code dérive (murs, toit, fondations, gypse, planchers, cloisons)132 if (/^(STR-WALL|STR-FLOOR|STR-ROOF|STR-BEAM|STR-COLUMN|FND-|ROOF-|INT-DRYWALL|INT-PAINT|INT-FLOOR|INT-TRIM|ENV-INSUL|ENV-SIDING|ENV-SOFFIT|SITE-|BSM-|ELE-ROUGH|ELE-SERVICE|MEC-PLUMBING|MEC-DUCTWORK|MEC-DRAINAGE)/.test(a.assembly_code)) { notes.push(`quantité IA ignorée pour ${a.assembly_code} (dérivée par le code)`); continue; }133 if (!engineCodes.has(a.assembly_code) && !ADDITIVE.test(a.assembly_code)) { notes.push(`assemblage IA ${a.assembly_code} ignoré (variante non retenue pour ce bâtiment — évite le double compte)`); continue; }134 aiQuantities[a.assembly_code] = { quantity: a.quantity, confidence: a.confidence, evidence: a.evidence };135 input.quantityOverrides[a.assembly_code] = a.quantity;136 }137138 // dépréciation par composante : conditions IA → règles métier ; âge effectif = suggestion IA139 input.depreciation.method = "components";140 input.depreciation.componentConditions = {};141 for (const g of CONDITION_GROUPS) { const c = m.conditions[g.key]; if (c) input.depreciation.componentConditions[g.key] = c; }142 input.depreciation.economicLife = BUILDING_TYPES.find((t) => t.key === b.type)?.economicLife ?? 60;143 if (m.effectiveAge?.effective != null) { input.depreciation.effectiveAge = Math.round(m.effectiveAge.effective); input.depreciation.effectiveAgeSource = "AI"; }144 if (m.effectiveAge?.economicLife && m.effectiveAge.economicLife >= 30) input.depreciation.economicLife = Math.round(m.effectiveAge.economicLife);145146 // terrain : valeur du rôle si l'annonce est jumelée, sinon inconnue (à saisir)147 input.roll = ctx.roll;148 input.land = ctx.landValue && ctx.landValue > 0 ? { value: ctx.landValue, source: "role", rollYear: 2026, method: "Valeur du terrain au rôle d'évaluation foncière 2026 (MAMH), via le jumelage de l'annonce" } : { value: null, source: "none", rollYear: null, method: "" };149 if (!input.land.value) notes.push("terrain non jumelé : valeur du terrain à saisir");150 if (b.type === "condo") notes.push("condo : quote-part des parties communes non incluse");151 return { input, aiQuantities, notes };152}153154/** Score combiné (§172-173) : analyse bâtiment · quantités · mapping · données de coût · localisation → globale /100. */155export function combinedConfidence(ai: ModelOutput, m: MergedFacts, est: { coverage: { materialObservedShare: number; pricingCoverage: number }; confidence: { location: number } }, mappedShare: number): { building: number; quantities: number; mapping: number; costData: number; location: number; overall: number } {156 const building = Math.round(100 * ai.confidence.overall);157 const quantities = Math.round(100 * (0.5 * ai.confidence.quantities + 0.5 * Math.min(1, (m.grossFloorAreaSqft.confidence + m.stories.confidence) / 2)));158 const mapping = Math.round(100 * mappedShare);159 const costData = Math.round(100 * (0.7 * est.coverage.materialObservedShare + 0.3 * est.coverage.pricingCoverage));160 const location = Math.round((100 * est.confidence.location) / 15);161 const overall = Math.round(0.3 * building + 0.2 * quantities + 0.15 * mapping + 0.25 * costData + 0.1 * location);162 return { building, quantities, mapping, costData, location, overall };163}164