Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/catalog.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 * Accès à la base de coûts (serveur) : articles + prix canoniques, assemblages,44 * taux de main-d'œuvre, localisations, indices, benchmarks → PricingContext.45 * Toute lecture est un INSTANTANÉ à une date (`asOf`) : reproductible.46 */47import type Database from "better-sqlite3";48import { getCostDb } from "./db";49import { canonicalPrice, indexFactor, type PriceObservation } from "./pricing";50import { FALLBACK_HOURLY_RATE, assemblyUnitCost, type BenchmarkRow, type ConditionRule, type PricingContext } from "./engine";51import type { Assembly, CanonicalUnit, Condition, CostItem, CostLocation, CostOverview, IndexSeries, ItemPrice, LabourRate, PriceKind, Quality, UxCategory } from "./types";52import { TRADES } from "./taxonomy";5354type Row = Record<string, unknown>;55const s = (v: unknown) => (v == null ? null : String(v));56const n = (v: unknown) => (v == null ? null : Number(v));5758export const today = (): string => new Date().toISOString().slice(0, 10);5960/* ---------------------------------------------------------------- articles */6162function rowToItem(r: Row): CostItem {63 return {64 id: Number(r.id), code: String(r.canonical_code), masterformat: String(r.masterformat_code), division: String(r.division), category: r.category as UxCategory, subcategory: s(r.subcategory),65 nameFr: String(r.name_fr), nameEn: String(r.name_en), descriptionFr: s(r.description_fr), descriptionEn: s(r.description_en), unit: r.unit as CanonicalUnit, materialClass: s(r.material_class),66 trade: s(r.trade), defaultWastePct: Number(r.default_waste_pct), qualityLevel: (r.quality_level as Quality) ?? null, referencePrice: n(r.reference_price), referenceNote: s(r.reference_note), active: Number(r.active) === 1,67 };68}6970export function loadItems(d: Database.Database = getCostDb()): Map<string, CostItem> {71 const rows = d.prepare("SELECT * FROM cost_items WHERE active=1").all() as Row[];72 return new Map(rows.map((r) => [String(r.canonical_code), rowToItem(r)]));73}7475export function getItem(code: string, d: Database.Database = getCostDb()): CostItem | null {76 const r = d.prepare("SELECT * FROM cost_items WHERE canonical_code=?").get(code) as Row | undefined;77 return r ? rowToItem(r) : null;78}7980export function searchItems(q: string, limit = 20, d: Database.Database = getCostDb()): CostItem[] {81 const like = `%${q.trim().normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase()}%`;82 const rows = d.prepare(`SELECT * FROM cost_items WHERE active=1 AND (lower(name_fr) LIKE ? OR lower(name_en) LIKE ? OR lower(canonical_code) LIKE ? OR lower(category) LIKE ?) ORDER BY name_fr LIMIT ?`)83 .all(like, like, like, like, limit) as Row[];84 // repli sans accents : SQLite lower() ignore les accents des noms → seconde passe JS85 if (rows.length) return rows.map(rowToItem);86 const all = loadItems(d);87 const fold = (x: string) => x.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();88 const needle = fold(q);89 return [...all.values()].filter((i) => fold(i.nameFr).includes(needle) || fold(i.nameEn).includes(needle) || fold(i.code).includes(needle)).slice(0, limit);90}9192/* ------------------------------------------------------------------- prix */9394interface PriceRow { code: string; unit: string; source: string; quality: number; total_cost: number; observation_date: string; source_url: string | null; source_unit: string | null; conversion_factor: number; is_regular_price: number; price_kind: string; location_code: string | null; is_outlier: number }9596/** Série d'indice résidentiel utilisée pour l'actualisation (Montréal, bâtiments résidentiels, agrégat). */97export function residentialIndexSeries(d: Database.Database = getCostDb(), code = "statcan:18100289:10:1:1"): { period: string; value: number }[] {98 return d.prepare("SELECT period, index_value AS value FROM construction_cost_indices WHERE index_code=? ORDER BY period").all(code) as { period: string; value: number }[];99}100101/**102 * Prix canonique de chaque article à la date `asOf` : observations des 120103 * derniers jours → médiane robuste ; sinon dernière observation actualisée par104 * l'indice StatCan (kind « indexed », ≤ 3 ans) ; sinon prix de référence105 * interne (kind « reference », hypothèse).106 */107export function loadPrices(asOf: string, locationCode: string | null, d: Database.Database = getCostDb(), items = loadItems(d)): Map<string, ItemPrice> {108 const rows = d.prepare(`SELECT i.canonical_code code, i.unit, s.name source, s.quality, p.total_cost, p.observation_date, p.source_url, p.source_unit, p.conversion_factor, p.is_regular_price, p.price_kind, p.location_code, p.is_outlier109 FROM cost_item_prices p JOIN cost_items i ON i.id=p.cost_item_id JOIN cost_sources s ON s.id=p.source_id110 WHERE p.observation_date <= ? AND s.is_active=1 AND p.is_outlier=0 AND p.price_kind IN ('observed','official','indexed','derived') ORDER BY p.observation_date DESC`).all(asOf) as PriceRow[];111 const byItem = new Map<string, PriceObservation[]>();112 for (const r of rows) {113 const arr = byItem.get(r.code) ?? [];114 arr.push({ source: r.source, sourceQuality: r.quality, price: r.total_cost, observedAt: r.observation_date, url: r.source_url, sourceUnit: r.source_unit ?? r.unit, conversionFactor: r.conversion_factor, regular: r.is_regular_price === 1, kind: r.price_kind as PriceKind, locationMatch: !r.location_code || r.location_code === "QC" || r.location_code === locationCode });115 byItem.set(r.code, arr);116 }117 const series = residentialIndexSeries(d);118 const out = new Map<string, ItemPrice>();119 for (const item of items.values()) {120 const obs = byItem.get(item.code) ?? [];121 const cp = canonicalPrice(obs, asOf, 120);122 if (cp) {123 out.set(item.code, {124 itemCode: item.code, unit: item.unit, price: cp.price, low: cp.low, high: cp.high, kind: cp.kind, sourceCount: cp.sourceCount, observedAt: cp.observedAt,125 sources: cp.used.map((o) => ({ source: o.source, price: o.price, url: o.url, observedAt: o.observedAt, sourceUnit: o.sourceUnit, conversionFactor: o.conversionFactor, regular: o.regular })),126 confidence: cp.confidence, indexed: null, note: cp.outliers.length ? `${cp.outliers.length} observation(s) aberrante(s) écartée(s) : ${cp.outliers.map((o) => `${o.obs.source} ${o.obs.price.toFixed(2)} $ (${o.reason})`).join(" ; ")}` : null,127 });128 continue;129 }130 // observation ancienne → actualisation par indice131 const old = obs.filter((o) => o.observedAt <= asOf).sort((a, b) => (a.observedAt < b.observedAt ? 1 : -1))[0];132 if (old && series.length >= 2) {133 const f = indexFactor(series, old.observedAt, asOf);134 const ageDays = (new Date(asOf).getTime() - new Date(old.observedAt).getTime()) / 86400000;135 if (f && ageDays <= 3 * 365) {136 const price = old.price * f.factor;137 out.set(item.code, {138 itemCode: item.code, unit: item.unit, price, low: price * 0.9, high: price * 1.1, kind: "indexed", sourceCount: 1, observedAt: old.observedAt,139 sources: [{ source: old.source, price: old.price, url: old.url, observedAt: old.observedAt, sourceUnit: old.sourceUnit, conversionFactor: old.conversionFactor, regular: old.regular }],140 confidence: Math.round(45 * Math.max(0.3, 1 - ageDays / 1095)), indexed: { fromDate: old.observedAt, toDate: asOf, factor: f.factor, index: "StatCan 18-10-0289 — bâtiments résidentiels, Montréal" },141 note: `Prix du ${old.observedAt} actualisé au ${asOf} par l'indice StatCan (× ${f.factor.toFixed(3)}).`,142 });143 continue;144 }145 }146 if (item.referencePrice != null) {147 out.set(item.code, {148 itemCode: item.code, unit: item.unit, price: item.referencePrice, low: item.referencePrice * 0.85, high: item.referencePrice * 1.15, kind: "reference", sourceCount: 0, observedAt: null,149 sources: [{ source: "Vrai-Prix — prix de référence (hypothèse)", price: item.referencePrice, url: null, observedAt: "2026-09-01", sourceUnit: item.unit, conversionFactor: 1, regular: true }],150 confidence: 35, indexed: null, note: item.referenceNote ?? "Prix de référence interne : aucune observation détaillant pour cet article — hypothèse documentée, non observée.",151 });152 }153 }154 return out;155}156157/** Historique des prix (toutes observations) d'un article. */158export function priceHistory(code: string, d: Database.Database = getCostDb()): { date: string; price: number; source: string; url: string | null; regular: boolean; kind: string; outlier: boolean; sourceUnit: string | null; conversionFactor: number }[] {159 return (d.prepare(`SELECT p.observation_date date, p.total_cost price, s.name source, p.source_url url, p.is_regular_price regular, p.price_kind kind, p.is_outlier outlier, p.source_unit su, p.conversion_factor cf160 FROM cost_item_prices p JOIN cost_items i ON i.id=p.cost_item_id JOIN cost_sources s ON s.id=p.source_id WHERE i.canonical_code=? ORDER BY p.observation_date`).all(code) as Row[])161 .map((r) => ({ date: String(r.date), price: Number(r.price), source: String(r.source), url: s(r.url), regular: Number(r.regular) === 1, kind: String(r.kind), outlier: Number(r.outlier) === 1, sourceUnit: s(r.su), conversionFactor: Number(r.cf) }));162}163164/* ----------------------------------------------------------- main-d'œuvre */165166export function loadLabour(asOf: string, d: Database.Database = getCostDb(), sector = "residentiel_leger", region = "QC"): Map<string, LabourRate> {167 const rows = d.prepare(`SELECT l.*, s.name source_name FROM labour_rates l LEFT JOIN cost_sources s ON s.id=l.source_id168 WHERE l.effective_from <= ? AND l.classification='compagnon' AND l.sector=? AND l.region=? ORDER BY l.effective_from DESC, COALESCE(s.priority, 9) ASC`).all(asOf, sector, region) as Row[];169 const out = new Map<string, LabourRate>();170 for (const r of rows) {171 const code = String(r.trade_code);172 if (out.has(code)) continue;173 out.set(code, {174 tradeCode: code, tradeNameFr: String(r.trade_name_fr), tradeNameEn: s(r.trade_name_en) ?? String(r.trade_name_fr), sector: String(r.sector), classification: String(r.classification), region: String(r.region),175 effectiveFrom: String(r.effective_from), effectiveTo: s(r.effective_to), baseWage: Number(r.base_wage), vacationCost: Number(r.vacation_cost), benefitsCost: Number(r.benefits_cost), employerContributions: Number(r.employer_contributions),176 otherContributions: Number(r.other_contributions), totalEmployerCost: Number(r.total_employer_cost), source: s(r.source_name) ?? "—", sourceUrl: s(r.source_url), confidence: Number(r.confidence_score ?? 80),177 });178 }179 // alias : poseur de bardeaux → couvreur180 if (!out.has("poseur_bardeaux") && out.has("couvreur")) out.set("poseur_bardeaux", { ...out.get("couvreur")!, tradeCode: "poseur_bardeaux" });181 return out;182}183184/** Toutes les grilles (historique) d'un métier. */185export function labourHistory(tradeCode: string, d: Database.Database = getCostDb()): LabourRate[] {186 const rows = d.prepare(`SELECT l.*, s.name source_name FROM labour_rates l LEFT JOIN cost_sources s ON s.id=l.source_id WHERE l.trade_code=? ORDER BY l.effective_from`).all(tradeCode) as Row[];187 return rows.map((r) => ({188 tradeCode: String(r.trade_code), tradeNameFr: String(r.trade_name_fr), tradeNameEn: s(r.trade_name_en) ?? String(r.trade_name_fr), sector: String(r.sector), classification: String(r.classification), region: String(r.region),189 effectiveFrom: String(r.effective_from), effectiveTo: s(r.effective_to), baseWage: Number(r.base_wage), vacationCost: Number(r.vacation_cost), benefitsCost: Number(r.benefits_cost), employerContributions: Number(r.employer_contributions),190 otherContributions: Number(r.other_contributions), totalEmployerCost: Number(r.total_employer_cost), source: s(r.source_name) ?? "—", sourceUrl: s(r.source_url), confidence: Number(r.confidence_score ?? 80),191 }));192}193194export function allLabourRates(asOf: string, d: Database.Database = getCostDb()): LabourRate[] {195 const out: LabourRate[] = [];196 for (const sector of ["residentiel_leger", "residentiel_lourd", "ic"]) {197 const rows = d.prepare(`SELECT l.*, s.name source_name FROM labour_rates l LEFT JOIN cost_sources s ON s.id=l.source_id WHERE l.effective_from <= ? AND l.sector=? AND l.region='QC' ORDER BY l.effective_from DESC`).all(asOf, sector) as Row[];198 const seen = new Set<string>();199 for (const r of rows) {200 const k = `${r.trade_code}|${r.classification}`;201 if (seen.has(k)) continue;202 seen.add(k);203 out.push({204 tradeCode: String(r.trade_code), tradeNameFr: String(r.trade_name_fr), tradeNameEn: s(r.trade_name_en) ?? String(r.trade_name_fr), sector: String(r.sector), classification: String(r.classification), region: String(r.region),205 effectiveFrom: String(r.effective_from), effectiveTo: s(r.effective_to), baseWage: Number(r.base_wage), vacationCost: Number(r.vacation_cost), benefitsCost: Number(r.benefits_cost), employerContributions: Number(r.employer_contributions),206 otherContributions: Number(r.other_contributions), totalEmployerCost: Number(r.total_employer_cost), source: s(r.source_name) ?? "—", sourceUrl: s(r.source_url), confidence: Number(r.confidence_score ?? 80),207 });208 }209 }210 return out;211}212213/* ------------------------------------------------------------ assemblages */214215export function loadAssemblies(d: Database.Database = getCostDb()): Map<string, Assembly> {216 const asms = d.prepare("SELECT * FROM cost_assemblies WHERE active=1").all() as Row[];217 const comps = d.prepare(`SELECT c.*, i.canonical_code FROM cost_assembly_components c LEFT JOIN cost_items i ON i.id=c.cost_item_id ORDER BY c.assembly_id, c.sequence`).all() as Row[];218 const byAsm = new Map<number, Assembly["components"]>();219 for (const c of comps) {220 const arr = byAsm.get(Number(c.assembly_id)) ?? [];221 arr.push({ itemCode: s(c.canonical_code) ?? "", quantity: Number(c.quantity_per_assembly_unit), wasteFactor: Number(c.waste_factor), labourHours: Number(c.labour_hours), trade: s(c.trade), equipmentCost: Number(c.equipment_cost), sequence: Number(c.sequence), notes: s(c.notes) });222 byAsm.set(Number(c.assembly_id), arr);223 }224 return new Map(asms.map((a) => [String(a.assembly_code), {225 code: String(a.assembly_code), masterformat: String(a.masterformat_code), category: a.category as UxCategory, nameFr: String(a.name_fr), nameEn: String(a.name_en), descriptionFr: s(a.description_fr) ?? "", descriptionEn: s(a.description_en) ?? "",226 unit: a.unit as CanonicalUnit, buildingType: s(a.building_type), quality: (a.quality_level as Quality) ?? null, version: Number(a.version), economicLife: n(a.economic_life), conditionGroup: s(a.condition_group), components: byAsm.get(Number(a.id)) ?? [], active: true,227 } satisfies Assembly]));228}229230/* ----------------------------------------------------------- localisation */231232function rowToLocation(r: Row): CostLocation {233 return { code: String(r.code), nameFr: String(r.name_fr), nameEn: String(r.name_en), regionCode: s(r.region_code) ?? "", materialFactor: Number(r.material_factor), labourFactor: Number(r.labour_factor), equipmentFactor: Number(r.equipment_factor), overallFactor: Number(r.overall_factor), effectiveDate: String(r.effective_date), sourceMethod: s(r.source_method) ?? "", confidence: Number(r.confidence_score ?? 50) };234}235236export function loadLocations(d: Database.Database = getCostDb()): CostLocation[] {237 return (d.prepare("SELECT * FROM cost_locations ORDER BY code").all() as Row[]).map(rowToLocation);238}239240const fold = (x: string) => x.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();241242/** Localisation d'une propriété : code forcé → municipalité → centre le plus proche (rayon) → rural. */243export function resolveLocation(opts: { code?: string | null; municipality?: string | null; lat?: number | null; lng?: number | null }, d: Database.Database = getCostDb()): { location: CostLocation; method: string } {244 const rows = d.prepare("SELECT * FROM cost_locations").all() as Row[];245 if (opts.code) {246 const r = rows.find((x) => x.code === opts.code);247 if (r) return { location: rowToLocation(r), method: "code imposé" };248 }249 if (opts.municipality) {250 const m = fold(opts.municipality);251 for (const r of rows) {252 const munis = JSON.parse(String(r.municipalities_json ?? "[]")) as string[];253 if (munis.some((x) => fold(x) === m)) return { location: rowToLocation(r), method: `municipalité « ${opts.municipality} »` };254 }255 }256 if (opts.lat != null && opts.lng != null) {257 let best: { r: Row; km: number } | null = null;258 for (const r of rows) {259 if (!r.latitude || !r.radius_km || Number(r.radius_km) <= 0) continue;260 const km = haversineKm(opts.lat, opts.lng, Number(r.latitude), Number(r.longitude));261 if (km <= Number(r.radius_km) && (!best || km < best.km)) best = { r, km };262 }263 if (best) return { location: rowToLocation(best.r), method: `centre le plus proche (${best.km.toFixed(0)} km de ${best.r.name_fr})` };264 }265 const rural = rows.find((x) => x.code === "QC-RUR") ?? rows[0];266 return { location: rowToLocation(rural), method: "défaut rural (aucune correspondance)" };267}268269function haversineKm(lat1: number, lng1: number, lat2: number, lng2: number): number {270 const R = 6371, dLat = ((lat2 - lat1) * Math.PI) / 180, dLng = ((lng2 - lng1) * Math.PI) / 180;271 const a = Math.sin(dLat / 2) ** 2 + Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) / 180) * Math.sin(dLng / 2) ** 2;272 return 2 * R * Math.asin(Math.sqrt(a));273}274275/* ------------------------------------------------- règles, benchmarks, indices */276277export function loadConditionRules(d: Database.Database = getCostDb()): Map<string, Map<Condition, ConditionRule>> {278 const rows = d.prepare("SELECT * FROM component_condition_rules").all() as Row[];279 const out = new Map<string, Map<Condition, ConditionRule>>();280 for (const r of rows) {281 const g = String(r.condition_group);282 if (!out.has(g)) out.set(g, new Map());283 out.get(g)!.set(r.condition as Condition, { effectiveAgeRatio: Number(r.effective_age_ratio), economicLife: Number(r.economic_life) });284 }285 return out;286}287288export function loadBenchmarks(d: Database.Database = getCostDb()): BenchmarkRow[] {289 return (d.prepare("SELECT * FROM cost_benchmarks WHERE is_demo=0 ORDER BY year DESC").all() as Row[]).map((r) => ({ source: String(r.source), buildingType: String(r.building_type), market: String(r.market), unit: String(r.unit), low: Number(r.low), high: Number(r.high), midpoint: n(r.midpoint), year: Number(r.year), notes: s(r.notes) }));290}291292export function loadIndexSeries(d: Database.Database = getCostDb()): IndexSeries[] {293 const rows = d.prepare("SELECT * FROM construction_cost_indices ORDER BY index_code, period").all() as Row[];294 const map = new Map<string, IndexSeries>();295 for (const r of rows) {296 const code = String(r.index_code);297 if (!map.has(code)) map.set(code, { code, source: String(r.source), geography: String(r.geography), buildingType: String(r.building_type), division: String(r.division), points: [], retrievedAt: s(r.retrieved_at) });298 map.get(code)!.points.push({ period: String(r.period), value: Number(r.index_value), pctYoy: n(r.pct_change_yoy) });299 }300 return [...map.values()];301}302303/* ---------------------------------------------------------------- contexte */304305export function buildContext(opts: { asOf?: string | null; locationCode?: string | null; municipality?: string | null; lat?: number | null; lng?: number | null }, d: Database.Database = getCostDb()): PricingContext & { locationMethod: string } {306 const asOf = opts.asOf ?? today();307 const items = loadItems(d);308 const { location, method } = resolveLocation({ code: opts.locationCode, municipality: opts.municipality, lat: opts.lat, lng: opts.lng }, d);309 return {310 asOf, items, prices: loadPrices(asOf, location.code, d, items), labour: loadLabour(asOf, d), assemblies: loadAssemblies(d), location,311 conditionRules: loadConditionRules(d), benchmarks: loadBenchmarks(d), fallbackHourlyRate: FALLBACK_HOURLY_RATE, locationMethod: method,312 };313}314315/* ------------------------------------------------------------- tableau de bord */316317const WATCHED_MATERIALS = ["LUM-2X4-8", "LUM-2X6-8", "OSB-7/16-4X8", "GYP-1/2-4X8", "INS-BATT-R24-2X6", "CONC-BAG-30KG", "SHINGLE-ARCH", "SIDING-VINYL", "PLY-1/2-4X8", "POLY-6MIL", "FLOOR-VINYL-PLANK", "TILE-CERAMIC-12X24"];318const POPULAR_ASSEMBLIES = ["STR-WALL-2X6-EXT", "ENV-INSUL-WALL-R24", "ENV-SIDING-VINYL", "ENV-SIDING-BRICK", "ROOF-ASPHALT-ARCH", "FND-WALL-POURED-8IN", "INT-DRYWALL-1/2-FINISHED", "STR-FLOOR-IJOIST", "OPN-WINDOW-PVC-STD", "KIT-STANDARD", "BATH-STANDARD", "INT-FLOOR-HARDWOOD"];319320export function buildOverview(d: Database.Database = getCostDb()): CostOverview {321 const asOf = today();322 const ctx = buildContext({ asOf, locationCode: "QC-MTL" }, d);323 const indices = loadIndexSeries(d);324 const resi = indices.find((i) => i.code === "statcan:18100289:10:1:1") ?? indices.find((i) => i.buildingType.includes("résidentiel")) ?? null;325 const wood = indices.find((i) => i.code === "statcan:18100289:10:1:8") ?? null;326 const last = (sr: IndexSeries | null) => (sr && sr.points.length ? sr.points[sr.points.length - 1] : null);327 const rp = last(resi);328 const wp = last(wood);329 const carp = ctx.labour.get("charpentier") ?? null;330 let labourYoy: number | null = null;331 if (carp) {332 const hist = labourHistory("charpentier", d).filter((h) => h.sector === carp.sector && h.classification === "compagnon");333 const prev = [...hist].reverse().find((h) => h.effectiveFrom <= shiftDays(carp.effectiveFrom, -300));334 if (prev && prev.totalEmployerCost > 0) labourYoy = Math.round(((carp.totalEmployerCost / prev.totalEmployerCost) - 1) * 1000) / 10;335 }336 const obsCount = (d.prepare("SELECT COUNT(*) n FROM cost_item_prices WHERE price_kind IN ('observed','official')").get() as { n: number }).n;337 const itemsObserved = (d.prepare("SELECT COUNT(DISTINCT cost_item_id) n FROM cost_item_prices WHERE price_kind IN ('observed','official') AND observation_date >= date('now','-120 days')").get() as { n: number }).n;338 const lastSync = (d.prepare("SELECT MAX(last_successful_sync) m FROM cost_sources").get() as { m: string | null }).m;339 const materials = WATCHED_MATERIALS.filter((c) => ctx.items.has(c)).map((code) => {340 const it = ctx.items.get(code)!;341 const p = ctx.prices.get(code) ?? null;342 const hist = priceHistory(code, d).filter((h) => !h.outlier && h.kind !== "reference");343 // médiane par date344 const byDate = new Map<string, number[]>();345 for (const h of hist) byDate.set(h.date, [...(byDate.get(h.date) ?? []), h.price]);346 const history = [...byDate.entries()].map(([date, ps]) => ({ date, price: Math.round(100 * ps.sort((a, b) => a - b)[Math.floor(ps.length / 2)]) / 100 })).sort((a, b) => a.date.localeCompare(b.date));347 return { itemCode: code, nameFr: it.nameFr, nameEn: it.nameEn, unit: it.unit, price: p ? Math.round(p.price * 100) / 100 : null, kind: p?.kind ?? null, sourceCount: p?.sourceCount ?? 0, observedAt: p?.observedAt ?? null, history };348 });349 const popularAssemblies = POPULAR_ASSEMBLIES.filter((c) => ctx.assemblies.has(c)).map((code) => {350 const a = ctx.assemblies.get(code)!;351 const u = assemblyUnitCost(a, ctx);352 return { code, nameFr: a.nameFr, nameEn: a.nameEn, unit: a.unit, direct: u.direct, material: u.material, labour: u.labour, equipment: u.equipment, observedShare: Math.round(u.observedShare * 100) / 100 };353 });354 const sources = (d.prepare(`SELECT s.*, (SELECT COUNT(*) FROM cost_item_prices p WHERE p.source_id=s.id) + (SELECT COUNT(*) FROM labour_rates l WHERE l.source_id=s.id) obs FROM cost_sources s ORDER BY s.priority, s.name`).all() as Row[])355 .map((r) => ({ name: String(r.name), type: String(r.source_type), license: String(r.license_status), lastSync: s(r.last_successful_sync), active: Number(r.is_active) === 1, observations: Number(r.obs), url: s(r.base_url) }));356 return {357 generatedAt: new Date().toISOString(), indices,358 kpis: {359 residentialIndex: rp ? { value: rp.value, period: rp.period, pctYoy: rp.pctYoy, geography: resi!.geography } : null,360 materialsProxy: wp ? { value: wp.value, period: wp.period, pctYoy: wp.pctYoy, label: wood!.division } : null,361 labour: carp ? { trade: carp.tradeNameFr, totalEmployerCost: carp.totalEmployerCost, effectiveFrom: carp.effectiveFrom, pctYoy: labourYoy, source: carp.source } : null,362 observations: obsCount, itemsObserved, itemsTotal: ctx.items.size, lastSync,363 },364 materials, popularAssemblies, locations: loadLocations(d), sources,365 };366}367368function shiftDays(iso: string, days: number): string {369 const d = new Date(iso);370 d.setDate(d.getDate() + days);371 return d.toISOString().slice(0, 10);372}373374/** Libellés des métiers pour l'UI (réexport). */375export const TRADE_LIST = TRADES;376