Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/connectors/imports.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 * Imports manuels (aucun scraping) :44 * - Altus Group — Canadian Cost Guide : benchmarks $/pi² saisis après45 * téléchargement légal du guide (formulaire) → cost_benchmarks ;46 * - RSMeans / Gordian : données sous licence, import CSV/XLSX→CSV autorisé47 * seulement → cost_item_prices (price_kind « reference », source rsmeans),48 * jamais redistribuées telles quelles (seul le prix canonique agrégé sert).49 */50import type Database from "better-sqlite3";51import { getCostDb, sourceIdByKey } from "../db";52import { convertPrice } from "../units";53import type { CanonicalUnit } from "../types";5455export const BENCHMARK_TYPES = ["single_family", "townhouse", "plex", "condo"] as const;56export type BenchmarkType = (typeof BENCHMARK_TYPES)[number];5758export interface BenchmarkImportRow { source: string; building_type: BenchmarkType; market: string; unit?: string; low: number; high: number; year: number; notes?: string | null }5960/** CSV simple (séparateur , ou ;) → objets ; guillemets gérés. */61export function parseCsv(text: string): Record<string, string>[] {62 const lines = text.replace(/\r/g, "").split("\n").filter((l) => l.trim());63 if (lines.length < 2) return [];64 const sep = lines[0].includes(";") && !lines[0].includes(",") ? ";" : ",";65 const split = (l: string): string[] => {66 const out: string[] = [];67 let cur = "";68 let q = false;69 for (const ch of l) {70 if (ch === '"') q = !q;71 else if (ch === sep && !q) { out.push(cur.trim()); cur = ""; }72 else cur += ch;73 }74 out.push(cur.trim());75 return out;76 };77 const head = split(lines[0]).map((h) => h.toLowerCase().replace(/\s+/g, "_"));78 return lines.slice(1).map((l) => Object.fromEntries(split(l).map((v, i) => [head[i] ?? `c${i}`, v])));79}8081export function normalizeBenchmarkRows(input: unknown): { rows: BenchmarkImportRow[]; errors: string[] } {82 const raw: Record<string, unknown>[] = typeof input === "string" ? parseCsv(input) : Array.isArray(input) ? (input as Record<string, unknown>[]) : [];83 const rows: BenchmarkImportRow[] = [];84 const errors: string[] = [];85 raw.forEach((r, i) => {86 const bt = String(r.building_type ?? "").trim() as BenchmarkType;87 const low = Number(String(r.low ?? "").replace(",", "."));88 const high = Number(String(r.high ?? "").replace(",", "."));89 const year = Number(r.year);90 if (!BENCHMARK_TYPES.includes(bt)) { errors.push(`ligne ${i + 1} : building_type invalide « ${bt} »`); return; }91 if (!(low > 0 && high >= low && high < 5000)) { errors.push(`ligne ${i + 1} : bornes invalides`); return; }92 if (!(year >= 2015 && year <= 2035)) { errors.push(`ligne ${i + 1} : année invalide`); return; }93 if (!r.source || !r.market) { errors.push(`ligne ${i + 1} : source/market requis`); return; }94 rows.push({ source: String(r.source).trim(), building_type: bt, market: String(r.market).trim(), unit: String(r.unit ?? "$/pi2"), low, high, year, notes: r.notes ? String(r.notes) : null });95 });96 return { rows, errors };97}9899export function importBenchmarks(input: unknown, d: Database.Database = getCostDb()): { imported: number; errors: string[] } {100 const { rows, errors } = normalizeBenchmarkRows(input);101 const altusId = sourceIdByKey("altus", d);102 const rsId = sourceIdByKey("rsmeans", d);103 const st = d.prepare(`INSERT INTO cost_benchmarks(source,source_id,building_type,market,unit,low,high,midpoint,year,notes,is_demo) VALUES(?,?,?,?,?,?,?,?,?,?,0)104 ON CONFLICT(source,building_type,market,year) DO UPDATE SET low=excluded.low, high=excluded.high, midpoint=excluded.midpoint, unit=excluded.unit, notes=excluded.notes, source_id=excluded.source_id`);105 const tx = d.transaction(() => { for (const r of rows) st.run(r.source, /altus/i.test(r.source) ? altusId : /rsmeans|gordian/i.test(r.source) ? rsId : null, r.building_type, r.market, r.unit, r.low, r.high, (r.low + r.high) / 2, r.year, r.notes ?? null); });106 tx();107 if (rows.length) d.prepare("UPDATE cost_sources SET last_successful_sync=datetime('now') WHERE key IN ('altus') AND EXISTS (SELECT 1 FROM cost_benchmarks WHERE source_id=cost_sources.id)").run();108 return { imported: rows.length, errors };109}110111/** Import RSMeans/Gordian (CSV : item_code, price, unit, [pack_qty], [date], [notes]) → prix de référence licenciés. */112export function importRsmeans(input: unknown, d: Database.Database = getCostDb()): { imported: number; errors: string[] } {113 const raw: Record<string, unknown>[] = typeof input === "string" ? parseCsv(input) : Array.isArray(input) ? (input as Record<string, unknown>[]) : [];114 const sid = sourceIdByKey("rsmeans", d);115 const errors: string[] = [];116 let imported = 0;117 const tx = d.transaction(() => {118 raw.forEach((r, i) => {119 const code = String(r.item_code ?? r.canonical_code ?? "").trim();120 const item = d.prepare("SELECT id, unit FROM cost_items WHERE canonical_code=?").get(code) as { id: number; unit: CanonicalUnit } | undefined;121 if (!item) { errors.push(`ligne ${i + 1} : article inconnu ${code}`); return; }122 const price = Number(String(r.price ?? "").replace(",", "."));123 if (!(price > 0)) { errors.push(`ligne ${i + 1} : prix invalide`); return; }124 const date = String(r.date ?? new Date().toISOString().slice(0, 10));125 try {126 const conv = convertPrice(price, String(r.unit ?? item.unit), item.unit, r.pack_qty ? Number(r.pack_qty) : null);127 d.prepare(`INSERT INTO cost_item_prices(cost_item_id,source_id,location_code,observation_date,price_kind,material_cost,total_cost,currency,source_unit,conversion_factor,is_regular_price,confidence_score,source_url,verified) VALUES(?,?,'QC',?,'reference',?,?,'CAD',?,?,1,70,?,1)`)128 .run(item.id, sid, date, conv.price, conv.price, conv.conversion.sourceUnit, conv.conversion.factor, r.notes ? String(r.notes) : null);129 imported++;130 } catch (e) { errors.push(`ligne ${i + 1} : ${(e as Error).message}`); }131 });132 });133 tx();134 return { imported, errors };135}136