Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/connectors/apchq.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 * Connecteur APCHQ — grilles publiques « Coût horaire de la main-d'œuvre »44 * (PDF, media.apchq.com) : taux horaire conventionné (CCQ), indemnité de45 * vacances (13 %), avantages sociaux, cotisations (AE, RQAP, RRQ, FSS, CNESST),46 * prélèvements (CCQ, AECQ, fonds), TOTAL = coût employeur complet.47 *48 * Firecrawl rend le PDF en tableau markdown ; la mise en page fusionne parfois49 * deux lignes (compagnon + apprenti 1, ou apprenti 2 + apprenti 3) dans une50 * même rangée : le parseur lit les montants cellule par cellule et reconstitue51 * un enregistrement par valeur de « Taux horaire ». Les champs exacts sont le52 * taux horaire et le total ; la ventilation intermédiaire est lue quand la53 * cellule est nette, sinon reconstituée (vacances = 13 % réglementaire,54 * cotisations employeur = total − autres postes) et la confiance est réduite.55 */56import { TRADES } from "../taxonomy";57import { contentHash, parseMoney, scrape } from "./firecrawl";58import { lastHashFor } from "./store";59import { downloadPdf, extractApchqWithClaude } from "./apchq-ai";60import type { CanonicalObservation, ConnectorConfig, CostConnector, RawDocument, RawObservation, RunOptions, SourceDocument, ValidationResult } from "./types";61import { validateObservations } from "./validate";62import { recentPricesFor, referencePriceFor } from "./store";6364export const APCHQ_PARSER_VERSION = "apchq-1.0";65export const APCHQ_LANDING = "https://www.apchq.com/nos-services/relations-du-travail/paie/couts-horaires-et-paie/";6667export const APCHQ_CONFIG: ConnectorConfig = {68 key: "apchq", name: "APCHQ — Coûts horaires de la main-d'œuvre", domain: "apchq.com", maxPages: 40,69 allowedPaths: [/^https:\/\/media\.apchq\.com\/.+\.pdf$/i, /^https:\/\/www\.apchq\.com\/nos-services\/relations-du-travail\/paie\//],70 excludedPaths: [/temps-(demi|et-demi|double)/i, /exemple-de-paie/i, /avantages-(sociaux|imposable)/i, /residentiel-r-2/i, /chantiers?-isoles/i, /baie-james/i, /special-paie/i, /ic_special/i, /ic-speciale/i],71 refreshDays: 7, timeoutMs: 150_000, retries: 2, rateLimitMs: 1500, concurrency: 2,72};7374const MONTHS: [RegExp, string][] = [75 [/^jan/, "01"], [/^f[eé]v/, "02"], [/^mar/, "03"], [/^a[vr]r?[iv]?/, "04"], [/^mai/, "05"], [/^juin/, "06"], [/^juil/, "07"], [/^ao[uû]/, "08"], [/^sep/, "09"], [/^oct/, "10"], [/^nov/, "11"], [/^d[eé]c/, "12"],76];7778/** Date d'entrée en vigueur depuis le nom du PDF (« 26-arvil-2026 », « 1er-janvier-2024 »). */79export function dateFromUrl(url: string): string | null {80 const m = url.toLowerCase().match(/(\d{1,2})(?:er)?-([a-zéû]+)-(\d{4})/);81 if (!m) return null;82 const month = MONTHS.find(([re]) => re.test(m[2]))?.[1];83 if (!month) return null;84 return `${m[3]}-${month}-${m[1].padStart(2, "0")}`;85}8687export function sectorFromUrl(url: string): "residentiel_leger" | "residentiel_lourd" | "ic" | null {88 const u = url.toLowerCase();89 if (/residentiel-leger/.test(u)) return "residentiel_leger";90 if (/residentiel-lourd/.test(u)) return "residentiel_lourd";91 if (/commercial/.test(u)) return "ic";92 return null;93}9495const fold = (s: string) => s.replace(/œ/g, "oe").replace(/Œ/g, "oe").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();9697/** Libellés APCHQ (abrégés dans les PDF) → codes de métier internes. */98const ALIASES: Record<string, string> = {99 "charpentier menuisier": "charpentier",100 "briqueteur macon": "briqueteur",101 carreleur: "carreleur",102 "cimentier applicateur": "cimentier",103 "coffreur a beton": "coffreur",104 couvreur: "couvreur",105 electricien: "electricien",106 tuyauteur: "plombier",107 plombier: "plombier",108 ferblantier: "ferblantier",109 frigoriste: "frigoriste",110 peintre: "peintre",111 platrier: "platrier",112 "tir joints peint platr": "tireur_joints",113 "poseur de systemes interieurs": "poseur_systemes",114 "poseur de rev souples": "poseur_revetements",115 "poseur de revetements souples": "poseur_revetements",116 calorifugeur: "calorifugeur",117 "poseur d armature du beton": "ferrailleur",118 ferrailleur: "ferrailleur",119 "monteur mecanicien vitrier": "vitrier",120 "manoeuvre journalier": "manoeuvre",121 manoeuvre: "manoeuvre",122 "manoeuvre specialise": "manoeuvre_specialise",123 "op de p mec cl a": "operateur",124 "ope de p mec cl b": "operateur_b",125 "op d equip l classe a": "operateur_equipement_lourd",126 "op d equip l classe b": "operateur_equipement_lourd_b",127 "parqueteur sableur": "parqueteur",128 "grutier classe a": "grutier",129 "mecanicien de chantier": "mecanicien_chantier",130 "monteur assembleur": "monteur_assembleur",131 "poseur de fondation profonde": "poseur_fondation",132 "install de sys de securite": "installateur_securite",133 "mec protection incendie": "mecanicien_protection_incendie",134 soudeur: "soudeur",135 boutefeu: "boutefeu",136 foreur: "foreur",137};138139/** Spécialités de la CCQ rattachées à un métier : le poseur de systèmes intérieurs est une spécialité du charpentier-menuisier. */140const DERIVED: { from: string; to: string; label: string }[] = [141 { from: "charpentier", to: "poseur_systemes", label: "Charpentier-menuisier — spécialité poseur de systèmes intérieurs" },142 { from: "couvreur", to: "poseur_bardeaux", label: "Couvreur — pose de bardeaux" },143];144145export function tradeCodeFor(label: string): { code: string; matched: boolean } {146 const f = fold(label);147 if (ALIASES[f]) return { code: ALIASES[f], matched: true };148 for (const t of TRADES) if (t.apchq.some((a) => fold(a) === f)) return { code: t.code, matched: true };149 for (const [k, v] of Object.entries(ALIASES)) if (f.startsWith(k) || k.startsWith(f)) return { code: v, matched: true };150 return { code: f.replace(/ /g, "_").slice(0, 40) || "inconnu", matched: false };151}152153/* ---------------------------------------------------------------- parseur */154155export interface ApchqRow {156 trade: string; // libellé APCHQ157 classification: string; // compagnon | apprenti-1…158 baseWage: number;159 vacation: number;160 benefits: number;161 otherFixed: number;162 employer: number;163 total: number;164 exactBreakdown: boolean;165}166167const FIXED_CANDIDATES = [0.26, 0.6, 0.65, 0.03, 0.02, 0.2, 0.043];168const MONEY_RE = /-?\d[\d\s]*(?:[.,]\d+)?\s*\$/g;169const APPR_RE = /apprenti[- ]p[eé]riode\s*(\d)/gi;170171function cellValues(cell: string): number[] {172 return [...cell.matchAll(MONEY_RE)].map((m) => parseMoney(m[0])).filter((v): v is number => v != null);173}174175function cellText(cell: string): string {176 return cell.replace(MONEY_RE, " ").replace(/'|'|’/g, "'").replace(/\s+/g, " ").trim();177}178179/** Parse le markdown d'une grille APCHQ en enregistrements (compagnon + apprentis). */180export function parseApchqMarkdown(md: string): ApchqRow[] {181 const rows: ApchqRow[] = [];182 let currentTrade: string | null = null;183 for (const line of md.split("\n")) {184 if (!line.startsWith("|")) continue;185 const cells = line.trim().replace(/^\|/, "").replace(/\|$/, "").split("|");186 const text = cells.map(cellText).filter(Boolean).join(" ").trim();187 if (!text || /^-+$/.test(text) || /après avoir|valeur unité|métiers et spécialités|occupations|^total$|horaire/i.test(text)) continue;188 let valueCells = cells.map(cellValues).filter((v) => v.length > 0);189 const apprs = [...text.matchAll(APPR_RE)].map((m) => Number(m[1]));190 const nameOnly = text.replace(APPR_RE, " ").replace(/\s+/g, " ").trim();191 const looksLikeName = nameOnly.length >= 3 && nameOnly.length <= 60 && !/%|\$/.test(nameOnly);192 if (!valueCells.length) {193 if (looksLikeName && !apprs.length) currentTrade = nameOnly;194 continue;195 }196 if (looksLikeName) currentTrade = nameOnly;197 if (!currentTrade) continue;198 // rangée aplatie : toutes les valeurs dans une seule cellule → un seul enregistrement199 if (valueCells.length === 1 && valueCells[0].length >= 12) valueCells = valueCells[0].map((v) => [v]);200 const first = valueCells[0];201 const last = valueCells[valueCells.length - 1];202 const k = Math.max(1, first.length);203 const classes: string[] = apprs.length ? apprs.map((n) => `apprenti-${n}`) : ["compagnon"];204 while (classes.length < k) {205 const prev = classes[classes.length - 1];206 classes.push(`apprenti-${prev === "compagnon" ? 1 : Number(prev.split("-")[1]) + 1}`);207 }208 const allValues = valueCells.flat();209 const otherFixed = FIXED_CANDIDATES.filter((c) => allValues.some((v) => Math.abs(v - c) < 0.0005)).reduce((s, v) => s + v, 0);210 for (let i = 0; i < k; i++) {211 const base = first[i];212 const total = last.length > i ? last[i] : last.length === 1 && i === 0 ? last[0] : null;213 if (base == null || total == null) continue;214 if (!(base > 10 && base < 200) || !(total > base * 1.25 && total < base * 2.1)) continue;215 const pick = (idx: number, lo: number, hi: number): number | null => {216 const c = valueCells[idx];217 if (!c) return null;218 const v = c.length > i ? c[i] : c.length === 1 ? c[0] : null;219 return v != null && v >= lo && v <= hi ? v : null;220 };221 const vac = pick(1, base * 0.1, base * 0.16);222 const ben = pick(2, 3, 14);223 const vacation = vac ?? Math.round(base * 0.13 * 100) / 100;224 const benefits = ben ?? 0;225 const employer = Math.max(0, Math.round((total - base - vacation - benefits - otherFixed) * 100) / 100);226 rows.push({ trade: currentTrade, classification: classes[i], baseWage: base, vacation, benefits, otherFixed: Math.round(otherFixed * 1000) / 1000, employer, total, exactBreakdown: vac != null && ben != null });227 }228 }229 return reclassify(rows);230}231232/**233 * La mise en page du PDF décale parfois les libellés : on rétablit la234 * classification à partir des salaires. Le compagnon est le taux le plus élevé235 * du métier ; chaque apprenti reçoit la période dont le ratio conventionnel236 * (≈ 50 / 60 / 70 / 85 % du compagnon) est le plus proche, dans un régime à237 * 3, 4 ou 5 périodes selon le métier.238 */239function reclassify(rows: ApchqRow[]): ApchqRow[] {240 const groups = new Map<string, ApchqRow[]>();241 for (const r of rows) groups.set(fold(r.trade), [...(groups.get(fold(r.trade)) ?? []), r]);242 const out: ApchqRow[] = [];243 for (const g of groups.values()) {244 const uniq = [...new Map(g.map((r) => [r.baseWage.toFixed(2), r])).values()].sort((a, b) => b.baseWage - a.baseWage);245 const comp = uniq[0];246 out.push({ ...comp, classification: "compagnon" });247 const appr = uniq.slice(1).sort((a, b) => a.baseWage - b.baseWage);248 if (!appr.length) continue;249 const parsedMax = Math.max(...g.map((r) => Number(r.classification.split("-")[1]) || 0));250 const periods = Math.max(appr.length, Math.min(5, parsedMax || 0), 3);251 const scheme = periods >= 5 ? [0.5, 0.6, 0.7, 0.85, 0.85] : periods === 4 ? [0.5, 0.6, 0.7, 0.85] : [0.6, 0.7, 0.85];252 const used = new Set<number>();253 for (const r of appr) {254 const ratio = r.baseWage / comp.baseWage;255 let best = 1;256 let bestD = Infinity;257 scheme.forEach((x, idx) => { const d = Math.abs(x - ratio); if (d < bestD && !used.has(idx + 1)) { bestD = d; best = idx + 1; } });258 used.add(best);259 out.push({ ...r, classification: `apprenti-${best}` });260 }261 }262 return out;263}264265/* --------------------------------------------------------------- connecteur */266267export const apchqConnector: CostConnector = {268 config: APCHQ_CONFIG,269270 async discover(opts) {271 const page = await scrape(APCHQ_LANDING, { links: true, timeoutMs: APCHQ_CONFIG.timeoutMs, retries: APCHQ_CONFIG.retries, rateLimitMs: APCHQ_CONFIG.rateLimitMs });272 return discoverFromLinks([...page.links, ...page.markdown.matchAll(/https:\/\/media\.apchq\.com\/[^\s)]+\.pdf/g).map((m) => m[0])], opts.maxPages ?? APCHQ_CONFIG.maxPages);273 },274275 async fetch(doc, opts) {276 const r = await scrape(doc.url, { timeoutMs: APCHQ_CONFIG.timeoutMs, retries: APCHQ_CONFIG.retries, rateLimitMs: APCHQ_CONFIG.rateLimitMs, concurrency: APCHQ_CONFIG.concurrency });277 const hash = contentHash(r.markdown);278 return { url: doc.url, fetchedAt: new Date().toISOString(), markdown: r.markdown, metadata: r.metadata, statusCode: r.statusCode, contentHash: hash, unchanged: !opts.force && lastHashFor(doc.url, opts.db) === hash, meta: doc.meta };279 },280281 async extract(raw, opts) {282 const effective = dateFromUrl(raw.url);283 const sector = sectorFromUrl(raw.url);284 if (!effective || !sector) return [];285 let rows = parseApchqMarkdown(raw.markdown);286 // lecture assistée (Claude Haiku) pour rétablir les libellés décalés par la conversion PDF → markdown ;287 // chaque ligne IA est vérifiée contre les couples (taux, total) du parseur déterministe.288 if (process.env.ANTHROPIC_API_KEY && !opts.onlyItems?.includes("no-ai")) {289 try {290 const pdf = await downloadPdf(raw.url, 60_000);291 const ai = await extractApchqWithClaude(pdf, rows, { url: raw.url, sector, effectiveDate: effective }, opts.db);292 if (ai.rows.length >= Math.min(20, rows.length * 0.6)) {293 opts.log?.({ connector: "apchq", url: raw.url, status: "ok", duration: ai.usage.latencyMs, observations: ai.rows.length, validationErrors: ai.dropped, timestamp: new Date().toISOString(), message: `lecture IA : ${ai.rows.length} lignes vérifiées, ${ai.dropped} rejetées (regex : ${rows.length})` });294 rows = ai.rows;295 } else {296 opts.log?.({ connector: "apchq", url: raw.url, status: "skipped", duration: ai.usage.latencyMs, observations: ai.rows.length, validationErrors: ai.dropped, timestamp: new Date().toISOString(), message: `lecture IA insuffisante (${ai.rows.length} lignes) — parseur déterministe conservé` });297 }298 } catch (e) {299 opts.log?.({ connector: "apchq", url: raw.url, status: "skipped", duration: 0, observations: 0, validationErrors: 0, timestamp: new Date().toISOString(), message: `lecture IA indisponible : ${(e as Error).message} — parseur déterministe conservé` });300 }301 }302 return rows.map((r) => ({303 externalId: `${sector}|${effective}|${fold(r.trade)}|${r.classification}`, sourceUrl: raw.url, retrievedAt: raw.fetchedAt, effectiveDate: effective,304 title: `${r.trade} — ${r.classification} (${sector})`, description: null, unit: "h", price: r.total, regularPrice: null, salePrice: null, currency: "CAD", location: "QC", category: "labour",305 payload: { ...r, sector },306 }));307 },308309 async normalize(obs) {310 const out: CanonicalObservation[] = [];311 for (const o of obs) {312 const p = o.payload as unknown as ApchqRow & { sector: string };313 const { code, matched } = tradeCodeFor(p.trade);314 const base = {315 kind: "labour" as const, sector: p.sector, classification: p.classification, region: "QC", effectiveFrom: o.effectiveDate ?? "", baseWage: p.baseWage, vacationCost: p.vacation, benefitsCost: p.benefits,316 employerContributions: p.employer, otherContributions: p.otherFixed, totalEmployerCost: p.total, sourceUrl: o.sourceUrl, confidence: (p.exactBreakdown ? 95 : 88) - (matched ? 0 : 10), raw: o,317 };318 out.push({ ...base, tradeCode: code, tradeNameFr: p.trade });319 for (const d of DERIVED) if (d.from === code) out.push({ ...base, tradeCode: d.to, tradeNameFr: d.label, confidence: base.confidence - 5 });320 }321 return out;322 },323324 validate(obs, opts): ValidationResult {325 return validateObservations(obs, { recentPrices: (c) => recentPricesFor(c, 120, opts.db), referencePrice: (c) => referencePriceFor(c, opts.db) });326 },327};328329/** Filtre les liens de la page APCHQ : grilles « coût main-d'œuvre », temps simple, léger/lourd/IC. */330export function discoverFromLinks(links: string[], maxPages: number): SourceDocument[] {331 const seen = new Set<string>();332 const docs: SourceDocument[] = [];333 for (const l of links) {334 const url = l.split("#")[0].trim();335 if (!/media\.apchq\.com\/.+cout-main-d-oeuvre.+\.pdf$/i.test(url)) continue;336 if (APCHQ_CONFIG.excludedPaths.some((re) => re.test(url))) continue;337 const d = dateFromUrl(url);338 const s = sectorFromUrl(url);339 if (!d || !s || seen.has(url)) continue;340 seen.add(url);341 docs.push({ url, title: `APCHQ ${s} ${d}`, meta: { effectiveDate: d, sector: s } });342 }343 return docs.sort((a, b) => String(a.meta?.effectiveDate).localeCompare(String(b.meta?.effectiveDate))).slice(0, maxPages);344}345346/** Pour les tests : construit un RawDocument depuis un markdown de fixture. */347export function rawDocFromMarkdown(url: string, markdown: string, meta?: RawDocument["meta"]): RawDocument {348 return { url, fetchedAt: new Date().toISOString(), markdown, metadata: {}, statusCode: 200, contentHash: contentHash(markdown), unchanged: false, meta };349}350351export type { RawObservation, RunOptions };352