Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : scripts/cost-sync.ts9 * Module : scripts10 * 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 * Planificateur de la base de coûts (méthode du coût) :44 * npx tsx scripts/cost-sync.ts # tous les connecteurs dus (fréquence nominale)45 * npx tsx scripts/cost-sync.ts apchq statcan # connecteurs choisis (même si non dus)46 * npx tsx scripts/cost-sync.ts canac --force # ignore le cache de hash / la fréquence47 * npx tsx scripts/cost-sync.ts --items LUM-2X6-8,GYP-1/2-4X8 canac48 * npx tsx scripts/cost-sync.ts --max 20 bmr49 * Fréquences nominales : détaillants 1 j · APCHQ 7 j (+ hash) · CCQ 7 j · StatCan 30 j.50 * Charge .env.local sans dépendance. Conçu pour PM2 (cron_restart) sur le nœud.51 */52import fs from "fs";53import path from "path";5455function loadEnv(): void {56 for (const f of [".env.local", ".env"]) {57 const p = path.join(process.cwd(), f);58 if (!fs.existsSync(p)) continue;59 for (const line of fs.readFileSync(p, "utf8").split("\n")) {60 const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);61 if (!m || line.trim().startsWith("#")) continue;62 if (process.env[m[1]] == null) process.env[m[1]] = m[2].replace(/^["']|["']$/g, "");63 }64 }65}66loadEnv();6768async function main(): Promise<void> {69 const { RUNNABLE_KEYS, isRunnable } = await import("../src/lib/cost/connectors/registry");70 const { isDue, runConnector } = await import("../src/lib/cost/connectors/run");71 const { getCostDb } = await import("../src/lib/cost/db");7273 const args = process.argv.slice(2);74 const force = args.includes("--force");75 const itemsArg = args.find((a) => a.startsWith("--items"));76 const items = itemsArg ? (itemsArg.includes("=") ? itemsArg.split("=")[1] : args[args.indexOf(itemsArg) + 1]).split(",").map((s) => s.trim()).filter(Boolean) : undefined;77 const maxArg = args.find((a) => a.startsWith("--max"));78 const maxPages = maxArg ? Number(maxArg.includes("=") ? maxArg.split("=")[1] : args[args.indexOf(maxArg) + 1]) : undefined;79 const verbose = args.includes("--verbose") || args.includes("-v");80 const requested = args.filter((a) => !a.startsWith("-") && isRunnable(a) && a !== (items ? items.join(",") : "") && a !== String(maxPages));81 const d = getCostDb();82 const keys = requested.length ? requested : RUNNABLE_KEYS.filter((k) => force || isDue(k, d));83 if (!keys.length) { console.log("[cost-sync] rien à faire (aucun connecteur dû)."); return; }84 console.log(`[cost-sync] ${new Date().toISOString()} — connecteurs : ${keys.join(", ")}${force ? " (--force)" : ""}${items ? ` — articles : ${items.join(",")}` : ""}`);85 let failed = 0;86 for (const key of keys) {87 if (!isRunnable(key)) continue;88 const t0 = Date.now();89 const stats = await runConnector(key, {90 force, onlyItems: items, maxPages, db: d,91 log: (e) => { if (verbose || e.status === "error" || e.status === "unavailable") console.log(` [${key}] ${e.status.padEnd(11)} ${e.url ?? ""} ${e.message ?? ""}`.trimEnd()); },92 });93 if (stats.status === "error") failed++;94 console.log(`[cost-sync] ${key.padEnd(13)} ${stats.status.padEnd(11)} pages ${stats.pages} · obs ${stats.observations} · acceptées ${stats.accepted} · rejetées ${stats.rejected} · inchangées ${stats.unchanged} · erreurs ${stats.errors} · ${Math.round((Date.now() - t0) / 1000)} s${stats.message ? ` — ${stats.message}` : ""}`);95 }96 const s = d.prepare("SELECT (SELECT COUNT(*) FROM cost_item_prices WHERE price_kind IN ('observed','official')) prices, (SELECT COUNT(DISTINCT cost_item_id) FROM cost_item_prices WHERE observation_date >= date('now','-120 days')) items, (SELECT COUNT(*) FROM labour_rates) labour, (SELECT COUNT(*) FROM construction_cost_indices) idx").get() as { prices: number; items: number; labour: number; idx: number };97 console.log(`[cost-sync] base : ${s.prices} observations de prix · ${s.items} articles avec prix récent · ${s.labour} grilles de main-d'œuvre · ${s.idx} points d'indice`);98 if (failed) process.exitCode = 1;99}100101main().catch((e) => { console.error("[cost-sync] échec :", e); process.exit(1); });102