Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/db.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 * Base de coûts `data/cost.db` (SQLite, better-sqlite3) : schéma versionné,44 * migrations forward-only, seeds idempotents (articles, assemblages,45 * localisations, sources, règles de condition). SERVEUR seulement.46 *47 * L'interface ne lit que cette base : aucun connecteur web n'est appelé dans48 * le chemin utilisateur (scripts/cost-sync.ts alimente la base en arrière-plan).49 */50import Database from "better-sqlite3";51import path from "path";52import fs from "fs";53import { ITEM_SEEDS } from "./seed/items";54import { ASSEMBLY_SEEDS, ASSEMBLY_VERSION } from "./seed/assemblies";55import { LOCATION_SEEDS } from "./seed/locations";56import { SOURCE_SEEDS } from "./seed/sources";57import { CONDITIONS, CONDITION_GROUPS, MASTERFORMAT } from "./taxonomy";5859export const COST_DB_SCHEMA_VERSION = 3;6061let db: Database.Database | null = null;6263export function costDbPath(): string {64 return process.env.COST_DB ?? path.join(process.cwd(), "data", "cost.db");65}6667/**68 * Base PARTAGÉE avec la v1 (data/cost.db est un lien symbolique, ou69 * COST_DB_SHARED=1) : la v2 y lit les coûts et y écrit seulement ce que70 * produit un visiteur (estimations enregistrées, analyses IA, usage API).71 * Le schéma et les seeds appartiennent à la v1 : jamais migrés ni réécrits ici.72 */73export function costDbShared(p: string = costDbPath()): boolean {74 if (process.env.COST_DB_SHARED === "1") return true;75 if (process.env.COST_DB_SHARED === "0") return false;76 try {77 return fs.lstatSync(p).isSymbolicLink();78 } catch {79 return false;80 }81}8283export function getCostDb(): Database.Database {84 if (db) return db;85 const p = costDbPath();86 fs.mkdirSync(path.dirname(p), { recursive: true });87 db = new Database(p);88 db.pragma("busy_timeout = 5000");89 db.pragma("foreign_keys = ON");90 if (costDbShared(p)) return db; // base de la v1 : ni migration ni seed d'ici91 db.pragma("journal_mode = WAL");92 migrate(db);93 seed(db);94 return db;95}9697/** Pour les tests : base en mémoire isolée. */98export function openCostDbAt(p: string): Database.Database {99 const d = new Database(p);100 d.pragma("journal_mode = MEMORY");101 d.pragma("foreign_keys = ON");102 migrate(d);103 seed(d);104 return d;105}106107/* ----------------------------------------------------------------- schéma */108109const SCHEMA = `110CREATE TABLE IF NOT EXISTS cost_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);111112CREATE TABLE IF NOT EXISTS cost_sources (113 id INTEGER PRIMARY KEY AUTOINCREMENT,114 key TEXT UNIQUE NOT NULL,115 name TEXT NOT NULL,116 source_type TEXT NOT NULL,117 base_url TEXT,118 jurisdiction TEXT,119 license_status TEXT NOT NULL DEFAULT 'unknown',120 license_notes TEXT,121 terms_url TEXT,122 is_active INTEGER NOT NULL DEFAULT 1,123 priority INTEGER NOT NULL DEFAULT 5,124 quality REAL NOT NULL DEFAULT 0.5,125 refresh_frequency TEXT,126 last_successful_sync TEXT,127 last_error TEXT,128 created_at TEXT NOT NULL DEFAULT (datetime('now')),129 updated_at TEXT NOT NULL DEFAULT (datetime('now'))130);131132CREATE TABLE IF NOT EXISTS cost_raw_observations (133 id INTEGER PRIMARY KEY AUTOINCREMENT,134 source_id INTEGER NOT NULL REFERENCES cost_sources(id),135 external_id TEXT,136 source_url TEXT,137 retrieved_at TEXT NOT NULL,138 effective_date TEXT,139 raw_title TEXT,140 raw_description TEXT,141 raw_unit TEXT,142 raw_price REAL,143 raw_regular_price REAL,144 raw_sale_price REAL,145 raw_currency TEXT,146 raw_location TEXT,147 raw_category TEXT,148 raw_payload_json TEXT,149 content_hash TEXT,150 parser_version TEXT,151 status TEXT NOT NULL DEFAULT 'new',152 reject_reason TEXT,153 created_at TEXT NOT NULL DEFAULT (datetime('now'))154);155CREATE INDEX IF NOT EXISTS idx_raw_obs_source_date ON cost_raw_observations(source_id, retrieved_at);156CREATE INDEX IF NOT EXISTS idx_raw_obs_hash ON cost_raw_observations(content_hash);157158CREATE TABLE IF NOT EXISTS cost_items (159 id INTEGER PRIMARY KEY AUTOINCREMENT,160 canonical_code TEXT UNIQUE NOT NULL,161 masterformat_code TEXT NOT NULL,162 division TEXT NOT NULL,163 category TEXT NOT NULL,164 subcategory TEXT,165 name_fr TEXT NOT NULL,166 name_en TEXT NOT NULL,167 description_fr TEXT,168 description_en TEXT,169 unit TEXT NOT NULL,170 material_class TEXT,171 trade TEXT,172 default_waste_pct REAL NOT NULL DEFAULT 0,173 residential_relevance INTEGER NOT NULL DEFAULT 1,174 quality_level TEXT,175 reference_price REAL,176 reference_note TEXT,177 retail_query TEXT,178 retail_pack_qty REAL,179 retail_pack_unit TEXT,180 active INTEGER NOT NULL DEFAULT 1,181 created_at TEXT NOT NULL DEFAULT (datetime('now')),182 updated_at TEXT NOT NULL DEFAULT (datetime('now'))183);184185/* URL produit par détaillant pour un article (découverte par connecteur / matching validé) */186CREATE TABLE IF NOT EXISTS cost_item_sources (187 id INTEGER PRIMARY KEY AUTOINCREMENT,188 cost_item_id INTEGER NOT NULL REFERENCES cost_items(id),189 source_id INTEGER NOT NULL REFERENCES cost_sources(id),190 product_url TEXT NOT NULL,191 product_title TEXT,192 external_id TEXT,193 pack_qty REAL,194 pack_unit TEXT,195 match_method TEXT,196 match_confidence REAL,197 approved INTEGER NOT NULL DEFAULT 0,198 active INTEGER NOT NULL DEFAULT 1,199 created_at TEXT NOT NULL DEFAULT (datetime('now')),200 UNIQUE(source_id, product_url)201);202203CREATE TABLE IF NOT EXISTS cost_item_prices (204 id INTEGER PRIMARY KEY AUTOINCREMENT,205 cost_item_id INTEGER NOT NULL REFERENCES cost_items(id),206 source_id INTEGER NOT NULL REFERENCES cost_sources(id),207 location_code TEXT,208 observation_date TEXT NOT NULL,209 price_kind TEXT NOT NULL DEFAULT 'observed',210 material_cost REAL,211 labour_cost REAL,212 equipment_cost REAL,213 total_cost REAL NOT NULL,214 low_cost REAL,215 median_cost REAL,216 high_cost REAL,217 currency TEXT NOT NULL DEFAULT 'CAD',218 source_unit TEXT,219 conversion_factor REAL NOT NULL DEFAULT 1,220 is_regular_price INTEGER NOT NULL DEFAULT 1,221 is_outlier INTEGER NOT NULL DEFAULT 0,222 outlier_reason TEXT,223 confidence_score REAL,224 source_url TEXT,225 raw_observation_id INTEGER REFERENCES cost_raw_observations(id),226 verified INTEGER NOT NULL DEFAULT 0,227 created_at TEXT NOT NULL DEFAULT (datetime('now'))228);229CREATE INDEX IF NOT EXISTS idx_item_prices_item_date ON cost_item_prices(cost_item_id, observation_date);230231CREATE TABLE IF NOT EXISTS labour_rates (232 id INTEGER PRIMARY KEY AUTOINCREMENT,233 trade_code TEXT NOT NULL,234 trade_name_fr TEXT NOT NULL,235 trade_name_en TEXT,236 sector TEXT NOT NULL,237 classification TEXT NOT NULL DEFAULT 'compagnon',238 region TEXT NOT NULL DEFAULT 'QC',239 effective_from TEXT NOT NULL,240 effective_to TEXT,241 base_wage REAL NOT NULL,242 vacation_cost REAL NOT NULL DEFAULT 0,243 benefits_cost REAL NOT NULL DEFAULT 0,244 employer_contributions REAL NOT NULL DEFAULT 0,245 other_contributions REAL NOT NULL DEFAULT 0,246 total_employer_cost REAL NOT NULL,247 source_id INTEGER REFERENCES cost_sources(id),248 source_url TEXT,249 confidence_score REAL,250 raw_observation_id INTEGER REFERENCES cost_raw_observations(id),251 created_at TEXT NOT NULL DEFAULT (datetime('now')),252 UNIQUE(trade_code, sector, classification, region, effective_from, source_id)253);254255CREATE TABLE IF NOT EXISTS cost_locations (256 id INTEGER PRIMARY KEY AUTOINCREMENT,257 code TEXT UNIQUE NOT NULL,258 municipality_code TEXT,259 municipality_name TEXT,260 name_fr TEXT NOT NULL,261 name_en TEXT NOT NULL,262 region_code TEXT,263 region_name TEXT,264 latitude REAL,265 longitude REAL,266 radius_km REAL,267 municipalities_json TEXT,268 material_factor REAL NOT NULL DEFAULT 1,269 labour_factor REAL NOT NULL DEFAULT 1,270 equipment_factor REAL NOT NULL DEFAULT 1,271 overall_factor REAL NOT NULL DEFAULT 1,272 effective_date TEXT NOT NULL,273 source_method TEXT,274 confidence_score REAL,275 created_at TEXT NOT NULL DEFAULT (datetime('now'))276);277278CREATE TABLE IF NOT EXISTS cost_assemblies (279 id INTEGER PRIMARY KEY AUTOINCREMENT,280 assembly_code TEXT UNIQUE NOT NULL,281 masterformat_code TEXT NOT NULL,282 category TEXT NOT NULL,283 name_fr TEXT NOT NULL,284 name_en TEXT NOT NULL,285 description_fr TEXT,286 description_en TEXT,287 unit TEXT NOT NULL,288 building_type TEXT,289 quality_level TEXT,290 economic_life INTEGER,291 condition_group TEXT,292 version INTEGER NOT NULL DEFAULT 1,293 active INTEGER NOT NULL DEFAULT 1,294 created_at TEXT NOT NULL DEFAULT (datetime('now')),295 updated_at TEXT NOT NULL DEFAULT (datetime('now'))296);297298CREATE TABLE IF NOT EXISTS cost_assembly_components (299 id INTEGER PRIMARY KEY AUTOINCREMENT,300 assembly_id INTEGER NOT NULL REFERENCES cost_assemblies(id) ON DELETE CASCADE,301 cost_item_id INTEGER REFERENCES cost_items(id),302 quantity_per_assembly_unit REAL NOT NULL DEFAULT 0,303 waste_factor REAL NOT NULL DEFAULT 0,304 labour_hours REAL NOT NULL DEFAULT 0,305 trade TEXT,306 equipment_cost REAL NOT NULL DEFAULT 0,307 sequence INTEGER NOT NULL DEFAULT 0,308 notes TEXT309);310CREATE INDEX IF NOT EXISTS idx_asm_comp ON cost_assembly_components(assembly_id);311312CREATE TABLE IF NOT EXISTS construction_cost_indices (313 id INTEGER PRIMARY KEY AUTOINCREMENT,314 source TEXT NOT NULL,315 index_code TEXT NOT NULL,316 geography TEXT NOT NULL,317 building_type TEXT NOT NULL,318 division TEXT NOT NULL DEFAULT 'aggregate',319 period TEXT NOT NULL,320 index_value REAL NOT NULL,321 pct_change_qoq REAL,322 pct_change_yoy REAL,323 retrieved_at TEXT NOT NULL,324 UNIQUE(index_code, period)325);326327CREATE TABLE IF NOT EXISTS cost_benchmarks (328 id INTEGER PRIMARY KEY AUTOINCREMENT,329 source TEXT NOT NULL,330 source_id INTEGER REFERENCES cost_sources(id),331 building_type TEXT NOT NULL,332 market TEXT NOT NULL,333 unit TEXT NOT NULL DEFAULT '$/pi2',334 low REAL NOT NULL,335 high REAL NOT NULL,336 midpoint REAL,337 year INTEGER NOT NULL,338 notes TEXT,339 is_demo INTEGER NOT NULL DEFAULT 0,340 created_at TEXT NOT NULL DEFAULT (datetime('now')),341 UNIQUE(source, building_type, market, year)342);343344CREATE TABLE IF NOT EXISTS component_condition_rules (345 id INTEGER PRIMARY KEY AUTOINCREMENT,346 condition_group TEXT NOT NULL,347 condition TEXT NOT NULL,348 effective_age_ratio REAL NOT NULL,349 economic_life INTEGER NOT NULL,350 notes TEXT,351 UNIQUE(condition_group, condition)352);353354CREATE TABLE IF NOT EXISTS cost_estimates (355 id TEXT PRIMARY KEY,356 property_id TEXT,357 listing_uid TEXT,358 user_session_id TEXT,359 mode TEXT NOT NULL,360 location_code TEXT,361 municipality TEXT,362 estimate_date TEXT NOT NULL,363 price_date TEXT NOT NULL,364 building_type TEXT,365 quality_level TEXT,366 area_sqft REAL,367 direct_cost REAL,368 indirect_cost REAL,369 contractor_overhead REAL,370 contractor_profit REAL,371 contingency REAL,372 replacement_cost_new REAL,373 rcn_low REAL,374 rcn_high REAL,375 physical_depreciation REAL,376 functional_obsolescence REAL,377 external_obsolescence REAL,378 depreciated_improvement_value REAL,379 land_value REAL,380 cost_approach_value REAL,381 confidence_score REAL,382 confidence_letter TEXT,383 method_version TEXT NOT NULL,384 cost_database_version TEXT NOT NULL,385 assembly_version TEXT NOT NULL,386 input_json TEXT NOT NULL,387 result_json TEXT NOT NULL,388 assumptions_json TEXT,389 created_at TEXT NOT NULL DEFAULT (datetime('now'))390);391CREATE INDEX IF NOT EXISTS idx_estimates_prop ON cost_estimates(property_id);392CREATE INDEX IF NOT EXISTS idx_estimates_listing ON cost_estimates(listing_uid);393394CREATE TABLE IF NOT EXISTS cost_estimate_lines (395 id INTEGER PRIMARY KEY AUTOINCREMENT,396 estimate_id TEXT NOT NULL REFERENCES cost_estimates(id) ON DELETE CASCADE,397 assembly_code TEXT NOT NULL,398 category TEXT NOT NULL,399 quantity REAL NOT NULL,400 unit TEXT NOT NULL,401 material_cost REAL,402 labour_cost REAL,403 equipment_cost REAL,404 direct_cost REAL,405 location_adjustment REAL,406 adjusted_cost REAL,407 source_summary TEXT,408 confidence_score REAL,409 calculation_json TEXT410);411CREATE INDEX IF NOT EXISTS idx_est_lines ON cost_estimate_lines(estimate_id);412413/* instantané des prix canoniques utilisés par une estimation (reproductibilité) */414CREATE TABLE IF NOT EXISTS cost_estimate_snapshots (415 estimate_id TEXT PRIMARY KEY REFERENCES cost_estimates(id) ON DELETE CASCADE,416 snapshot_date TEXT NOT NULL,417 prices_json TEXT NOT NULL,418 labour_json TEXT NOT NULL,419 location_json TEXT NOT NULL,420 created_at TEXT NOT NULL DEFAULT (datetime('now'))421);422423CREATE TABLE IF NOT EXISTS connector_runs (424 id INTEGER PRIMARY KEY AUTOINCREMENT,425 connector TEXT NOT NULL,426 started_at TEXT NOT NULL,427 finished_at TEXT,428 status TEXT NOT NULL DEFAULT 'running',429 pages INTEGER NOT NULL DEFAULT 0,430 observations INTEGER NOT NULL DEFAULT 0,431 accepted INTEGER NOT NULL DEFAULT 0,432 rejected INTEGER NOT NULL DEFAULT 0,433 unchanged INTEGER NOT NULL DEFAULT 0,434 errors INTEGER NOT NULL DEFAULT 0,435 duration_ms INTEGER,436 log_json TEXT437);438439/* correspondances produit détaillant → article canonique proposées (IA/déterministe) à valider */440CREATE TABLE IF NOT EXISTS product_mappings (441 id INTEGER PRIMARY KEY AUTOINCREMENT,442 source_id INTEGER NOT NULL REFERENCES cost_sources(id),443 product_url TEXT NOT NULL,444 product_title TEXT,445 proposed_item_code TEXT,446 pack_qty REAL,447 pack_unit TEXT,448 method TEXT NOT NULL,449 confidence REAL NOT NULL,450 rationale TEXT,451 status TEXT NOT NULL DEFAULT 'pending',452 reviewed_at TEXT,453 created_at TEXT NOT NULL DEFAULT (datetime('now')),454 UNIQUE(source_id, product_url)455);456457/* ---------------------------------------------- analyse IA des annonces */458CREATE TABLE IF NOT EXISTS listing_images (459 id INTEGER PRIMARY KEY AUTOINCREMENT,460 listing_uid TEXT NOT NULL,461 photo_id TEXT NOT NULL,462 source_url TEXT NOT NULL,463 position INTEGER,464 width INTEGER,465 height INTEGER,466 bytes INTEGER,467 hash TEXT,468 media_type TEXT,469 room_guess TEXT,470 quality_score REAL,471 selected_for_ai INTEGER NOT NULL DEFAULT 0,472 fetched_at TEXT NOT NULL,473 UNIQUE(listing_uid, source_url)474);475476CREATE TABLE IF NOT EXISTS listing_ai_analyses (477 id TEXT PRIMARY KEY,478 listing_uid TEXT NOT NULL,479 version INTEGER NOT NULL,480 model TEXT NOT NULL,481 prompt_version TEXT NOT NULL,482 schema_version TEXT NOT NULL,483 input_hash TEXT NOT NULL,484 status TEXT NOT NULL DEFAULT 'queued',485 stage TEXT,486 error TEXT,487 image_count INTEGER NOT NULL DEFAULT 0,488 output_json TEXT,489 compact_json TEXT,490 vector_json TEXT,491 confidence REAL,492 estimate_id TEXT,493 cost_snapshot_date TEXT,494 created_at TEXT NOT NULL DEFAULT (datetime('now')),495 completed_at TEXT496);497CREATE INDEX IF NOT EXISTS idx_ai_analyses_listing ON listing_ai_analyses(listing_uid, version);498CREATE INDEX IF NOT EXISTS idx_ai_analyses_hash ON listing_ai_analyses(listing_uid, input_hash, prompt_version, model);499500CREATE TABLE IF NOT EXISTS listing_ai_overrides (501 id INTEGER PRIMARY KEY AUTOINCREMENT,502 analysis_id TEXT NOT NULL REFERENCES listing_ai_analyses(id) ON DELETE CASCADE,503 field_path TEXT NOT NULL,504 original_value TEXT,505 new_value TEXT,506 user_id TEXT,507 created_at TEXT NOT NULL DEFAULT (datetime('now'))508);509510CREATE TABLE IF NOT EXISTS analysis_conflicts (511 id INTEGER PRIMARY KEY AUTOINCREMENT,512 analysis_id TEXT NOT NULL REFERENCES listing_ai_analyses(id) ON DELETE CASCADE,513 field TEXT NOT NULL,514 source_a TEXT NOT NULL,515 value_a TEXT,516 source_b TEXT NOT NULL,517 value_b TEXT,518 severity TEXT NOT NULL DEFAULT 'medium',519 status TEXT NOT NULL DEFAULT 'open'520);521522CREATE TABLE IF NOT EXISTS property_embeddings (523 id INTEGER PRIMARY KEY AUTOINCREMENT,524 listing_uid TEXT NOT NULL,525 analysis_id TEXT NOT NULL REFERENCES listing_ai_analyses(id) ON DELETE CASCADE,526 embedding_model TEXT NOT NULL,527 embedding_dimension INTEGER NOT NULL,528 embedding_json TEXT NOT NULL,529 canonical_text TEXT,530 created_at TEXT NOT NULL DEFAULT (datetime('now')),531 UNIQUE(analysis_id, embedding_model)532);533534CREATE TABLE IF NOT EXISTS ai_usage (535 id INTEGER PRIMARY KEY AUTOINCREMENT,536 analysis_id TEXT,537 purpose TEXT NOT NULL,538 model TEXT NOT NULL,539 input_images INTEGER NOT NULL DEFAULT 0,540 input_tokens INTEGER NOT NULL DEFAULT 0,541 output_tokens INTEGER NOT NULL DEFAULT 0,542 cache_read_tokens INTEGER NOT NULL DEFAULT 0,543 estimated_cost_usd REAL,544 latency_ms INTEGER,545 created_at TEXT NOT NULL DEFAULT (datetime('now'))546);547`;548549function migrate(d: Database.Database): void {550 d.exec(SCHEMA);551 const cur = Number((d.prepare("SELECT value FROM cost_meta WHERE key='schema_version'").get() as { value: string } | undefined)?.value ?? 0);552 // migrations incrémentales (forward-only) : ajouter ici les ALTER TABLE futurs553 if (cur < 2) {554 // v2 : colonnes de prix promotionnel déjà dans SCHEMA (création) — no-op pour bases existantes récentes555 }556 if (cur < 3) {557 // v3 : ai_usage.cache_read_tokens (ajout tolérant)558 try { d.exec("ALTER TABLE ai_usage ADD COLUMN cache_read_tokens INTEGER NOT NULL DEFAULT 0"); } catch { /* déjà présent */ }559 }560 d.prepare("INSERT INTO cost_meta(key,value) VALUES('schema_version',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(String(COST_DB_SCHEMA_VERSION));561}562563/* ------------------------------------------------------------------ seeds */564565function seed(d: Database.Database): void {566 const seedVersion = `${COST_DB_SCHEMA_VERSION}.${ASSEMBLY_VERSION}.${ITEM_SEEDS.length}.${ASSEMBLY_SEEDS.length}.${LOCATION_SEEDS.length}`;567 const done = (d.prepare("SELECT value FROM cost_meta WHERE key='seed_version'").get() as { value: string } | undefined)?.value;568 if (done === seedVersion) return;569570 const tx = d.transaction(() => {571 // sources572 const upSrc = d.prepare(`INSERT INTO cost_sources(key,name,source_type,base_url,jurisdiction,license_status,license_notes,terms_url,is_active,priority,quality,refresh_frequency)573 VALUES(@key,@name,@sourceType,@baseUrl,@jurisdiction,@licenseStatus,@licenseNotes,@termsUrl,@isActive,@priority,@quality,@refreshFrequency)574 ON CONFLICT(key) DO UPDATE SET name=excluded.name, source_type=excluded.source_type, base_url=excluded.base_url, license_status=excluded.license_status,575 license_notes=excluded.license_notes, terms_url=excluded.terms_url, priority=excluded.priority, quality=excluded.quality, refresh_frequency=excluded.refresh_frequency, updated_at=datetime('now')`);576 for (const s of SOURCE_SEEDS) upSrc.run({ ...s, isActive: s.isActive ? 1 : 0 });577578 // articles579 const upItem = d.prepare(`INSERT INTO cost_items(canonical_code,masterformat_code,division,category,name_fr,name_en,unit,material_class,trade,default_waste_pct,quality_level,reference_price,reference_note,retail_query,retail_pack_qty,retail_pack_unit)580 VALUES(@code,@mf,@division,@cat,@fr,@en,@unit,@cls,@trade,@waste,@quality,@ref,@refNote,@rq,@rpack,@rpu)581 ON CONFLICT(canonical_code) DO UPDATE SET masterformat_code=excluded.masterformat_code, division=excluded.division, category=excluded.category, name_fr=excluded.name_fr, name_en=excluded.name_en,582 unit=excluded.unit, material_class=excluded.material_class, trade=excluded.trade, default_waste_pct=excluded.default_waste_pct, quality_level=excluded.quality_level,583 reference_price=excluded.reference_price, reference_note=excluded.reference_note, retail_query=excluded.retail_query, retail_pack_qty=excluded.retail_pack_qty, retail_pack_unit=excluded.retail_pack_unit, updated_at=datetime('now')`);584 for (const it of ITEM_SEEDS) {585 upItem.run({586 code: it.code, mf: it.mf, division: MASTERFORMAT[it.mf]?.fr ?? it.mf, cat: it.cat, fr: it.fr, en: it.en, unit: it.unit,587 cls: it.cls ?? "material", trade: it.trade ?? null, waste: it.waste ?? 0, quality: it.quality ?? null,588 ref: it.ref, refNote: it.refNote ?? null, rq: it.retail?.q ?? null, rpack: it.retail?.pack ?? null, rpu: it.retail?.packUnit ?? null,589 });590 }591 const itemId = new Map<string, number>((d.prepare("SELECT id, canonical_code FROM cost_items").all() as { id: number; canonical_code: string }[]).map((r) => [r.canonical_code, r.id]));592593 // assemblages (remplacement complet des composants à chaque version de seed)594 const upAsm = d.prepare(`INSERT INTO cost_assemblies(assembly_code,masterformat_code,category,name_fr,name_en,description_fr,description_en,unit,building_type,quality_level,economic_life,condition_group,version)595 VALUES(@code,@mf,@cat,@fr,@en,@descFr,@descEn,@unit,@buildingType,@quality,@life,@group,@version)596 ON CONFLICT(assembly_code) DO UPDATE SET masterformat_code=excluded.masterformat_code, category=excluded.category, name_fr=excluded.name_fr, name_en=excluded.name_en,597 description_fr=excluded.description_fr, description_en=excluded.description_en, unit=excluded.unit, building_type=excluded.building_type, quality_level=excluded.quality_level,598 economic_life=excluded.economic_life, condition_group=excluded.condition_group, version=excluded.version, updated_at=datetime('now')`);599 const delComp = d.prepare("DELETE FROM cost_assembly_components WHERE assembly_id = ?");600 const insComp = d.prepare(`INSERT INTO cost_assembly_components(assembly_id,cost_item_id,quantity_per_assembly_unit,waste_factor,labour_hours,trade,equipment_cost,sequence,notes)601 VALUES(?,?,?,?,?,?,?,?,?)`);602 for (const a of ASSEMBLY_SEEDS) {603 upAsm.run({ code: a.code, mf: a.mf, cat: a.cat, fr: a.fr, en: a.en, descFr: a.descFr, descEn: a.descEn, unit: a.unit, buildingType: a.buildingType ?? null, quality: a.quality ?? null, life: a.life, group: a.group, version: ASSEMBLY_VERSION });604 const aid = (d.prepare("SELECT id FROM cost_assemblies WHERE assembly_code=?").get(a.code) as { id: number }).id;605 delComp.run(aid);606 for (const c of a.components) {607 const iid = c.itemCode ? itemId.get(c.itemCode) : null;608 if (c.itemCode && !iid) throw new Error(`Assemblage ${a.code} : article inconnu ${c.itemCode}`);609 insComp.run(aid, iid ?? null, c.quantity, c.wasteFactor, c.labourHours, c.trade, c.equipmentCost, c.sequence, c.notes);610 }611 }612613 // localisations614 const upLoc = d.prepare(`INSERT INTO cost_locations(code,name_fr,name_en,region_code,latitude,longitude,radius_km,municipalities_json,material_factor,labour_factor,equipment_factor,overall_factor,effective_date,source_method,confidence_score)615 VALUES(@code,@nameFr,@nameEn,@regionCode,@lat,@lng,@radiusKm,@munis,@materialFactor,@labourFactor,@equipmentFactor,@overallFactor,'2026-09-01',@method,@conf)616 ON CONFLICT(code) DO UPDATE SET name_fr=excluded.name_fr, name_en=excluded.name_en, region_code=excluded.region_code, latitude=excluded.latitude, longitude=excluded.longitude, radius_km=excluded.radius_km,617 municipalities_json=excluded.municipalities_json, material_factor=excluded.material_factor, labour_factor=excluded.labour_factor, equipment_factor=excluded.equipment_factor, overall_factor=excluded.overall_factor,618 source_method=excluded.source_method, confidence_score=excluded.confidence_score`);619 for (const l of LOCATION_SEEDS) {620 upLoc.run({ ...l, munis: JSON.stringify(l.municipalities), method: "Main-d'œuvre : conventions collectives CCQ uniformes au Québec (APCHQ) ; matériaux/équipement : surcoût de transport — hypothèse Vrai-Prix", conf: l.labourFactor === 1 ? 75 : 55 });621 }622623 // règles condition → âge effectif624 const upRule = d.prepare(`INSERT INTO component_condition_rules(condition_group,condition,effective_age_ratio,economic_life,notes) VALUES(?,?,?,?,?)625 ON CONFLICT(condition_group,condition) DO UPDATE SET effective_age_ratio=excluded.effective_age_ratio, economic_life=excluded.economic_life`);626 for (const g of CONDITION_GROUPS) for (const c of CONDITIONS) upRule.run(g.key, c.key, c.effectiveAgeRatio, g.economicLife, "Hypothèse documentée Vrai-Prix — âge effectif = ratio × vie économique de la composante");627628 d.prepare("INSERT INTO cost_meta(key,value) VALUES('seed_version',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(seedVersion);629 d.prepare("INSERT INTO cost_meta(key,value) VALUES('seeded_at',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(new Date().toISOString());630 });631 tx();632}633634/** Version de la base de coûts (pour la reproductibilité des estimations). */635export function costDatabaseVersion(d: Database.Database = getCostDb()): string {636 const seedV = (d.prepare("SELECT value FROM cost_meta WHERE key='seed_version'").get() as { value: string } | undefined)?.value ?? "0";637 const last = (d.prepare("SELECT MAX(observation_date) m, COUNT(*) n FROM cost_item_prices").get() as { m: string | null; n: number });638 const lab = (d.prepare("SELECT MAX(effective_from) m FROM labour_rates").get() as { m: string | null });639 return `${seedV}|prices:${last.n}@${last.m ?? "none"}|labour:${lab.m ?? "none"}`;640}641642export function sourceIdByKey(key: string, d: Database.Database = getCostDb()): number {643 const r = d.prepare("SELECT id FROM cost_sources WHERE key=?").get(key) as { id: number } | undefined;644 if (!r) throw new Error(`Source inconnue : ${key}`);645 return r.id;646}647648export function metaGet(key: string, d: Database.Database = getCostDb()): string | null {649 return (d.prepare("SELECT value FROM cost_meta WHERE key=?").get(key) as { value: string } | undefined)?.value ?? null;650}651export function metaSet(key: string, value: string, d: Database.Database = getCostDb()): void {652 d.prepare("INSERT INTO cost_meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(key, value);653}654