Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/connectors/connectors.test.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// Auteur : Simon-Pierre Boucher — contact@spboucher.ai43// Tests des connecteurs sur FIXTURES enregistrées (jamais le Web live).44import fs from "fs";45import path from "path";46import { describe, expect, it } from "vitest";47import { dateFromUrl, discoverFromLinks, parseApchqMarkdown, rawDocFromMarkdown, sectorFromUrl, tradeCodeFor, apchqConnector } from "./apchq";48import { reconcile } from "./apchq-ai";49import { pointsToObservations, seriesList, indexCode, statcanConnector } from "./statcan";50import { detectIncident, hasRateTable } from "./ccq";51import { bmrAdapter, canacAdapter, detectPackQty, detectPromotion, patrickMorinAdapter, unitTextToSourceUnit, makeRetailConnector } from "./retail";52import { deterministicMatch, scoreCandidate } from "./matching";53import { validateObservations } from "./validate";54import { contentHash, parseMoney } from "./firecrawl";55import { normalizeBenchmarkRows, parseCsv } from "./imports";56import { openCostDbAt } from "../db";57import { ensureConnectorSchema, saveRawObservation, lastHashFor } from "./store";58import type { CanonicalPriceObservation } from "./types";5960const FX = path.join(__dirname, "__fixtures__");61const readMd = (f: string) => fs.readFileSync(path.join(FX, f), "utf8");62const readJson = (f: string) => JSON.parse(fs.readFileSync(path.join(FX, f), "utf8")) as { data: { markdown: string; metadata: Record<string, unknown>; links?: string[] } };6364const noCtx = { recentPrices: () => [] as number[], referencePrice: () => null };6566/* ------------------------------------------------------------------ APCHQ */6768describe("APCHQ", () => {69 it("lit la date et le secteur depuis l'URL (coquille « arvil » tolérée)", () => {70 expect(dateFromUrl("https://media.apchq.com/x/cout-main-d-oeuvre-residentiel-leger-26-arvil-2026-temps-simple.pdf")).toBe("2026-04-26");71 expect(dateFromUrl("https://media.apchq.com/x/cout-main-d-oeuvre-residentiel-lourd-1er-janvier-2024.pdf")).toBe("2024-01-01");72 expect(dateFromUrl("https://media.apchq.com/x/cout-main-d-oeuvre-commercial-28-decembre-2025.pdf")).toBe("2025-12-28");73 expect(sectorFromUrl("…/cout-main-d-oeuvre-commercial-26-avril-2026.pdf")).toBe("ic");74 expect(sectorFromUrl("…/cout-main-d-oeuvre-residentiel-lourd-x.pdf")).toBe("residentiel_lourd");75 });76 it("découvre les grilles temps simple léger/lourd/IC et exclut temps demi, exemples de paie, chantiers isolés", () => {77 const j = readJson("apchq-landing.json");78 const docs = discoverFromLinks(j.data.links ?? [], 100);79 expect(docs.length).toBeGreaterThanOrEqual(12);80 expect(docs.every((d) => !/temps-demi|temps-double|exemple|isoles|baie-james/i.test(d.url))).toBe(true);81 expect(docs.some((d) => d.url.includes("residentiel-leger-26-arvil-2026-temps-simple"))).toBe(true);82 expect(docs.some((d) => d.url.includes("commercial-26-avril-2026"))).toBe(true);83 expect(docs.map((d) => String(d.meta?.effectiveDate))).toEqual([...docs.map((d) => String(d.meta?.effectiveDate))].sort());84 });85 it("parse une grille propre (2025) : compagnons plausibles, total > taux, apprentis ordonnés", () => {86 const rows = parseApchqMarkdown(readJson("apchq-leger-2025-04-27.json").data.markdown);87 expect(rows.length).toBeGreaterThan(100);88 const charp = rows.filter((r) => /charpentier/i.test(r.trade));89 const comp = charp.find((r) => r.classification === "compagnon")!;90 expect(comp.baseWage).toBeCloseTo(40.16, 2);91 expect(comp.total).toBeCloseTo(62.54, 2);92 expect(comp.vacation).toBeCloseTo(comp.baseWage * 0.13, 1);93 for (const r of rows) { expect(r.total).toBeGreaterThan(r.baseWage * 1.25); expect(r.total).toBeLessThan(r.baseWage * 2.1); }94 const appr = charp.filter((r) => r.classification.startsWith("apprenti")).sort((a, b) => a.classification.localeCompare(b.classification));95 for (let i = 1; i < appr.length; i++) expect(appr[i].baseWage).toBeGreaterThan(appr[i - 1].baseWage);96 });97 it("parse une grille aux rangées fusionnées/décalées (2026) : lignes aplaties et compagnon = taux le plus élevé", () => {98 const rows = parseApchqMarkdown(readMd("apchq-residentiel-leger-2026-04-26.md"));99 const rev = rows.find((r) => /poseur de rev/i.test(r.trade) && r.classification === "compagnon")!; // rangée « valeurs puis libellé » dans une seule cellule100 expect(rev.baseWage).toBeCloseTo(41.71, 2);101 expect(rev.total).toBeCloseTo(64.87, 2);102 const briq = rows.find((r) => /briqueteur/i.test(r.trade) && r.classification === "compagnon")!; // cellule « 46,59 $ 27,96 $ » = compagnon + apprenti 1103 expect(briq.baseWage).toBeCloseTo(46.59, 2);104 expect(briq.total).toBeCloseTo(72.11, 2);105 expect(rows.find((r) => /briqueteur/i.test(r.trade) && r.classification === "apprenti-1")!.baseWage).toBeCloseTo(27.96, 2);106 expect(rows.find((r) => /manœuvre \(journalier\)/i.test(r.trade))!.total).toBeCloseTo(58.55, 2);107 });108 it("associe les libellés APCHQ aux codes de métier (œ, abréviations)", () => {109 expect(tradeCodeFor("Charpentier-menuisier").code).toBe("charpentier");110 expect(tradeCodeFor("Tuyauteur").code).toBe("plombier");111 expect(tradeCodeFor("Manœuvre (journalier)").code).toBe("manoeuvre");112 expect(tradeCodeFor("Poseur d'armature du béton".replace("'", "'")).code).toBe("ferrailleur");113 expect(tradeCodeFor("Poseur de rev. Souples").code).toBe("poseur_revetements");114 expect(tradeCodeFor("Op. de p. méc. - Cl. A").code).toBe("operateur");115 expect(tradeCodeFor("Métier imaginaire").matched).toBe(false);116 });117 it("normalise en observations de main-d'œuvre valides (secteur, dérivés, validation)", async () => {118 const raw = rawDocFromMarkdown("https://media.apchq.com/x/cout-main-d-oeuvre-residentiel-leger-27-avril-2025-temps-simple.pdf", readJson("apchq-leger-2025-04-27.json").data.markdown);119 const obs = await apchqConnector.extract(raw, { onlyItems: ["no-ai"] });120 expect(obs.length).toBeGreaterThan(100);121 const canon = await apchqConnector.normalize(obs, raw, {});122 const lab = canon.filter((c) => c.kind === "labour");123 expect(lab.some((l) => l.kind === "labour" && l.tradeCode === "poseur_systemes")).toBe(true); // spécialité dérivée du charpentier124 expect(lab.every((l) => l.kind === "labour" && l.sector === "residentiel_leger" && l.effectiveFrom === "2025-04-27")).toBe(true);125 const v = validateObservations(canon, noCtx);126 expect(v.rejected.length).toBe(0);127 });128 it("réconciliation IA : accepte les lignes dont (taux, total) existent dans le parseur ou dont la somme boucle ; rejette le reste", () => {129 const regex = parseApchqMarkdown(readJson("apchq-leger-2025-04-27.json").data.markdown);130 const ok = { trade: "Charpentier-menuisier", classification: "compagnon", base_wage: 40.16, vacation: 5.22, benefits: 7.89, total: 62.54, contributions_sum: 9.27 };131 const sumOnly = { trade: "Métier X", classification: "compagnon", base_wage: 50, vacation: 6.5, benefits: 8, total: 74.5, contributions_sum: 10 };132 const bad = { trade: "Inventé", classification: "compagnon", base_wage: 44.44, vacation: 5.78, benefits: 8, total: 70.1, contributions_sum: 3 };133 const r = reconcile([ok, sumOnly, bad], regex, 1.153);134 expect(r.rows.map((x) => x.trade)).toEqual(["Charpentier-menuisier", "Métier X"]);135 expect(r.dropped).toBe(1);136 });137});138139/* ---------------------------------------------------------------- StatCan */140141describe("StatCan", () => {142 it("construit les 40 séries attendues avec les codes lus par le catalogue", () => {143 const s = seriesList();144 expect(s.length).toBe(16 + 22);145 expect(s.map(indexCode)).toContain("statcan:18100289:10:1:1");146 expect(s.map(indexCode)).toContain("statcan:18100289:10:1:8");147 });148 it("calcule les variations trimestrielle et annuelle", () => {149 const pts = [{ refPer: "2025-01-01", value: 100 }, { refPer: "2025-04-01", value: 102 }, { refPer: "2025-07-01", value: 104 }, { refPer: "2025-10-01", value: 105 }, { refPer: "2026-01-01", value: 110 }];150 const obs = pointsToObservations({ geo: 10, type: 1, division: 1 }, pts, "2026-09-06T00:00:00Z");151 expect(obs[0].pctQoq).toBeNull();152 expect(obs[1].pctQoq).toBeCloseTo(2, 1);153 expect(obs[4].pctYoy).toBeCloseTo(10, 1);154 expect(obs[4].geography).toBe("Montréal");155 expect(validateObservations(obs, noCtx).rejected.length).toBe(0);156 });157 it("normalise une réponse WDS enregistrée", async () => {158 const wds = [{ status: "SUCCESS", object: { coordinate: "10.1.1.0.0.0.0.0.0.0", vectorDataPoint: [{ refPer: "2026-01-01", value: 112.4 }, { refPer: "2026-04-01", value: 114.8 }] } }, { status: "FAILED", object: { coordinate: "9.9.9.0.0.0.0.0.0.0", vectorDataPoint: [] } }];159 const md = JSON.stringify(wds.map((it) => ({ c: it.object.coordinate, s: it.status, p: it.object.vectorDataPoint.map((p) => [p.refPer, p.value]) })));160 const raw = { url: "wds", fetchedAt: "2026-09-06T00:00:00Z", markdown: md, metadata: {}, statusCode: 200, contentHash: contentHash(md), unchanged: false };161 const obs = await statcanConnector.extract(raw, {});162 expect(obs.length).toBe(1);163 const canon = await statcanConnector.normalize(obs, raw, {});164 expect(canon.length).toBe(2);165 expect(canon[1]).toMatchObject({ kind: "index", indexCode: "statcan:18100289:10:1:1", period: "2026-04-01", value: 114.8 });166 });167});168169/* -------------------------------------------------------------------- CCQ */170171describe("CCQ", () => {172 it("détecte l'incident et l'absence de grille (source indisponible, jamais de valeur inventée)", () => {173 const md = "Salaire et taux\n\n**Incident de sécurité informatique en cours – Les services en ligne demeurent fermés. La reprise est prévue le 8 septembre.**\n| Date | Modifications |\n| --- | --- |\n| À compter du 26 avril 2026 | Taux |";174 expect(detectIncident(md)).toMatch(/incident de sécurité/i);175 expect(hasRateTable(md)).toBe(false);176 });177});178179/* ------------------------------------------------------------- détaillants */180181describe("détaillants", () => {182 it("Canac : prix et unité depuis la fiche (métadonnée product:price:amount)", () => {183 const j = readJson("canac-2x6x8.json");184 const p = canacAdapter.parse({ markdown: j.data.markdown, metadata: j.data.metadata, statusCode: 200, links: [] });185 expect(p.price).toBeCloseTo(5.98, 2);186 expect(p.unitText?.toLowerCase()).toContain("chaque");187 expect(p.title).toMatch(/2 po x 6 po x 8 pi/);188 expect(p.currency).toBe("CAD");189 });190 it("BMR : prix depuis les métadonnées malgré les variantes « à partir de »", () => {191 const j = readJson("bmr-2x6x8.json");192 const p = bmrAdapter.parse({ markdown: j.data.markdown, metadata: j.data.metadata, statusCode: 200, links: [] });193 expect(p.price).toBeCloseTo(6.98, 2);194 });195 it("Patrick Morin : prix depuis les métadonnées", () => {196 const j = readJson("pm-2x6x8.json");197 const p = patrickMorinAdapter.parse({ markdown: j.data.markdown, metadata: j.data.metadata, statusCode: 200, links: [] });198 expect(p.price).toBeCloseTo(5.98, 2);199 });200 it("promotion : prix régulier préféré, promo non interprétée comme régulier", () => {201 expect(detectPromotion("Prix régulier : 7,49 $ Spécial 5,98 $", 5.98)).toEqual({ regular: 7.49, sale: 5.98 });202 expect(detectPromotion("Économisez 20 % — 5,98 $ / Chaque", 5.98)).toEqual({ regular: null, sale: 5.98 });203 expect(detectPromotion("Rabais de la semaine sur la peinture !\n\n\n\n\n\n\n\n\n\n" + " ".repeat(300) + "# Tuyau\n5,98 $ / Chaque", 5.98)).toEqual({ regular: 5.98, sale: null });204 expect(detectPromotion("Prix 5,98 $ / Chaque", 5.98)).toEqual({ regular: 5.98, sale: null });205 });206 it("emballage : couverture pi², rouleau 100 pi, boîte de 50 lb, paquet de 12", () => {207 expect(detectPackQty("Isolant R24 — couvre 39,8 pi²", "pi2")).toBeCloseTo(39.8, 1);208 expect(detectPackQty("Panneau de gypse 4 pi x 8 pi", "pi2")).toBe(32);209 expect(detectPackQty("Tuyau PEX 1/2 po 100 pi", "pi_lin")).toBe(100);210 expect(detectPackQty("Clous 3 1/4 po 50 lb", "lb")).toBe(50);211 expect(detectPackQty("Attaches de brique pqt/100", "unit")).toBe(100);212 expect(unitTextToSourceUnit("Chaque", "pi2", 32, "feuille")).toBe("feuille");213 expect(unitTextToSourceUnit("Chaque", "unit", null, null)).toBe("chaque");214 });215 it("page sans prix → aucune observation ; conversion par emballage → prix canonique ; unité inconnue → rejet", async () => {216 const dbPath = path.join(FX, ".test-retail.db");217 fs.rmSync(dbPath, { force: true });218 const d = openCostDbAt(dbPath);219 ensureConnectorSchema(d);220 const c = makeRetailConnector(canacAdapter);221 const j = readJson("canac-2x6x8.json");222 const noPrice = { url: "https://www.canac.ca/canac/fr/2/p/x/1", fetchedAt: "2026-09-06T10:00:00Z", markdown: "# Produit\nDisponibilité", metadata: { title: "Produit" }, statusCode: 200, contentHash: "h1", unchanged: false, meta: { itemCode: "LUM-2X6-8", packQty: null, packUnit: null } };223 expect((await c.extract(noPrice, { db: d })).length).toBe(0);224 const gyp = { url: "https://www.canac.ca/canac/fr/2/p/gypse/2", fetchedAt: "2026-09-06T10:00:00Z", markdown: "# Panneau de gypse 1/2 po 4 pi x 8 pi\n17,60 $ / Chaque", metadata: { "product:price:amount": "17,60 $", "product:price:currency": "CAD", ogTitle: "Panneau de gypse 1/2 po 4 pi x 8 pi - Canac" }, statusCode: 200, contentHash: "h2", unchanged: false, meta: { itemCode: "GYP-1/2-4X8", packQty: 32, packUnit: "feuille" } };225 const obs = await c.extract(gyp, { db: d });226 expect(obs.length).toBe(1);227 const canon = await c.normalize(obs, gyp, { db: d });228 const p = canon[0] as CanonicalPriceObservation;229 expect(p.totalCost).toBeCloseTo(0.55, 3);230 expect(p.conversionFactor).toBeCloseTo(1 / 32, 6);231 expect(p.sourceUnit).toBe("feuille");232 expect(c.validate(canon, { db: d }).rejected.length).toBe(0);233 const lum = { url: j.data.metadata.url as string, fetchedAt: "2026-09-06T10:00:00Z", markdown: j.data.markdown, metadata: j.data.metadata, statusCode: 200, contentHash: "h3", unchanged: false, meta: { itemCode: "LUM-2X6-8", packQty: null, packUnit: null } };234 const lc = await c.normalize(await c.extract(lum, { db: d }), lum, { db: d });235 expect((lc[0] as CanonicalPriceObservation).totalCost).toBeCloseTo(5.98, 2);236 // unité inconnue (aucun emballage pour un pi²) → rejet explicite237 const weird = { ...gyp, url: "https://www.canac.ca/canac/fr/2/p/gypse/3", metadata: { ...gyp.metadata, ogTitle: "Gypse" }, markdown: "# Gypse\n17,60 $ / Palette", meta: { itemCode: "GYP-1/2-4X8", packQty: null, packUnit: null } };238 const wc = await c.normalize(await c.extract(weird, { db: d }), weird, { db: d });239 const v = c.validate(wc, { db: d });240 expect(v.accepted.length + v.rejected.length).toBe(1);241 expect(v.rejected.length).toBe(1);242 d.close();243 fs.rmSync(dbPath, { force: true });244 });245 it("erreur 403 / contenu vide → aucune observation, statut d'erreur propre", async () => {246 const c = makeRetailConnector(bmrAdapter);247 const forbidden = { url: "https://www.bmr.ca/fr/x.html", fetchedAt: "2026-09-06T10:00:00Z", markdown: "Just a moment...", metadata: {}, statusCode: 403, contentHash: "h", unchanged: false, meta: { itemCode: "LUM-2X6-8" } };248 expect((await c.extract(forbidden, {})).length).toBe(0);249 const empty = { ...forbidden, statusCode: 200, markdown: "" };250 expect((await c.extract(empty, {})).length).toBe(0);251 });252});253254/* -------------------------------------------------------------- matching */255256describe("matching déterministe", () => {257 it("exige les dimensions et privilégie le recouvrement des mots", () => {258 expect(scoreCandidate("épinette de construction 2 po x 6 po x 8 pi sec", "Épinette de construction 2 po x 6 po x 8 pi sec - Canac")).toBeGreaterThan(0.85);259 expect(scoreCandidate("épinette de construction 2 po x 6 po x 8 pi sec", "Épinette de construction 2 po x 4 po x 8 pi sec")).toBeLessThan(0.4);260 const dec = deterministicMatch("panneau de gypse 1/2 po 4 x 8", [{ url: "a", title: "Panneau de gypse 1/2 po 4 pi x 8 pi", description: "" }, { url: "b", title: "Panneau de gypse 5/8 po 4 x 8", description: "" }, { url: "c", title: "Ensemble de vis à gypse", description: "" }]);261 expect(dec.candidate?.url).toBe("a");262 expect(dec.confidence).toBeGreaterThan(0.8);263 });264});265266/* ------------------------------------------------------------- validation */267268describe("validation", () => {269 const base = (over: Partial<CanonicalPriceObservation>): CanonicalPriceObservation => ({ kind: "price", itemCode: "LUM-2X6-8", sourceUrl: "u", observationDate: "2026-09-06", sourceUnit: "chaque", canonicalUnit: "unit", conversionFactor: 1, totalCost: 6, isRegularPrice: true, rawPrice: 6, rawRegularPrice: null, rawSalePrice: null, currency: "CAD", locationCode: "QC", title: "t", raw: { externalId: null, sourceUrl: "u", retrievedAt: "2026-09-06T00:00:00Z", effectiveDate: null, title: "t", description: null, unit: "chaque", price: 6, regularPrice: null, salePrice: null, currency: "CAD", location: null, category: null, payload: {} }, ...over });270 it("rejette prix ≤ 0, devise ≠ CAD, unité inconnue, hors bornes métier ; marque les aberrations sans effacer", () => {271 const ctx = { recentPrices: () => [5.9, 6.1, 6.0], referencePrice: () => 5.98 };272 const v = validateObservations([base({}), base({ rawPrice: 0, totalCost: 0 }), base({ currency: "USD" }), base({ sourceUnit: "palette" }), base({ totalCost: 40, rawPrice: 40 }), base({ totalCost: 15, rawPrice: 15 })], ctx);273 expect(v.accepted.length).toBe(1);274 expect(v.rejected.map((r) => r.reason)).toEqual(expect.arrayContaining([expect.stringMatching(/≤ 0/), expect.stringMatching(/devise/), expect.stringMatching(/unité inconnue/), expect.stringMatching(/bornes métier/), expect.stringMatching(/aberration/)]));275 });276});277278/* ---------------------------------------------------------- hash / imports */279280describe("hash et imports", () => {281 it("un document inchangé est reconnu par son hash (statut unchanged)", () => {282 const dbPath = path.join(FX, ".test-hash.db");283 fs.rmSync(dbPath, { force: true });284 const d = openCostDbAt(dbPath);285 ensureConnectorSchema(d);286 const md = "| Charpentier | 60,24 $ | 89,14 $ |";287 const raw = rawDocFromMarkdown("https://media.apchq.com/x/y.pdf", md);288 expect(lastHashFor(raw.url, d)).toBeNull();289 saveRawObservation("apchq", { externalId: "x", sourceUrl: raw.url, retrievedAt: raw.fetchedAt, effectiveDate: "2026-04-26", title: "t", description: null, unit: "h", price: 89.14, regularPrice: null, salePrice: null, currency: "CAD", location: "QC", category: "labour", payload: {} }, raw, "accepted", null, "test", d);290 expect(lastHashFor(raw.url, d)).toBe(contentHash(md));291 expect(contentHash(md + "\n")).toBe(contentHash(md)); // espaces normalisés292 expect(contentHash("| Charpentier | 61,00 $ | 90,00 $ |")).not.toBe(contentHash(md));293 d.close();294 fs.rmSync(dbPath, { force: true });295 });296 it("parseMoney et import de benchmarks (CSV)", () => {297 expect(parseMoney("5,98 $")).toBeCloseTo(5.98);298 expect(parseMoney("$1 234,50")).toBeCloseTo(1234.5);299 expect(parseMoney("abc")).toBeNull();300 const csv = "source,building_type,market,unit,low,high,year,notes\nAltus Group — Canadian Cost Guide 2026,single_family,Montréal,$/pi2,255,395,2026,custom\nAltus,castle,Montréal,$/pi2,1,2,2026,\n";301 expect(parseCsv(csv).length).toBe(2);302 const r = normalizeBenchmarkRows(csv);303 expect(r.rows.length).toBe(1);304 expect(r.errors.length).toBe(1);305 });306});307