Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/connectors/matching.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 * Correspondance produit détaillant → article canonique.44 * produit brut → normalisation déterministe → (si ambigu) classification par45 * Claude Haiku 4.5 → confiance → product_mappings → cost_item_sources46 * L'IA ne fixe JAMAIS un prix : elle choisit au plus un candidat parmi les47 * résultats de recherche et explique son choix.48 */49import Anthropic from "@anthropic-ai/sdk";50import type Database from "better-sqlite3";51import { getCostDb, sourceIdByKey } from "../db";52import type { ConnectorKey } from "./types";5354export const MATCH_AUTO_APPROVE = 0.8;55const MODEL = "claude-haiku-4-5";5657export const fold = (s: string) => s.replace(/œ/g, "oe").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[×x]/g, " x ").replace(/["'’]/g, " ").replace(/[^a-z0-9./\s]/g, " ").replace(/\s+/g, " ").trim();5859/** Jetons : dimensions (2, 6, 8, 1/2), unités (po, pi, pi², mm) et mots ≥ 3 lettres (sans mots vides). */60export function tokens(s: string): { nums: string[]; words: string[] } {61 const f = fold(s).replace(/(\d)\s*po\b/g, "$1 po").replace(/(\d)\s*pi\b/g, "$1 pi");62 const nums = [...f.matchAll(/\b\d+(?:[./]\d+)?\b/g)].map((m) => m[0]);63 const STOP = new Set(["de", "des", "du", "la", "le", "les", "et", "en", "pour", "avec", "sans", "par", "sur", "au", "aux", "un", "une", "the", "and", "of", "for", "with", "sec", "kd"]);64 const words = f.split(" ").filter((w) => /^[a-z]{3,}$/.test(w) && !STOP.has(w));65 return { nums, words };66}6768/** Score déterministe 0-1 : tous les nombres de la requête doivent apparaître ; puis recouvrement des mots. */69export function scoreCandidate(query: string, title: string): number {70 const q = tokens(query);71 const t = tokens(title);72 if (!t.words.length && !t.nums.length) return 0;73 const numOk = q.nums.every((n) => t.nums.includes(n));74 if (q.nums.length && !numOk) return Math.min(0.35, wordOverlap(q.words, t.words) * 0.5);75 const wo = wordOverlap(q.words, t.words);76 return Math.min(1, (q.nums.length ? 0.45 : 0) + wo * (q.nums.length ? 0.55 : 1));77}7879function wordOverlap(a: string[], b: string[]): number {80 if (!a.length) return 1;81 const bs = new Set(b.flatMap((w) => [w, w.replace(/s$/, ""), w.slice(0, 5)]));82 const hit = a.filter((w) => bs.has(w) || bs.has(w.replace(/s$/, "")) || bs.has(w.slice(0, 5))).length;83 return hit / a.length;84}8586export interface Candidate { url: string; title: string; description: string }87export interface MatchDecision { candidate: Candidate | null; confidence: number; method: "deterministic" | "ai" | "none"; rationale: string }8889/** Détaillant : mots qui trahissent un produit non comparable (accessoire, lot, service). */90const BAD_WORDS = /\b(ensemble de|kit de|lot de|échantillon|echantillon|service|installation|location|garantie|carte cadeau|pièce de rechange)\b/i;9192export function deterministicMatch(query: string, candidates: Candidate[]): MatchDecision {93 const scored = candidates.filter((c) => !BAD_WORDS.test(c.title)).map((c) => ({ c, s: scoreCandidate(query, c.title) })).sort((a, b) => b.s - a.s);94 if (!scored.length) return { candidate: null, confidence: 0, method: "none", rationale: "aucun candidat" };95 const best = scored[0];96 const margin = scored.length > 1 ? best.s - scored[1].s : best.s;97 if (best.s >= 0.85 && margin >= 0.1) return { candidate: best.c, confidence: Math.min(0.97, best.s), method: "deterministic", rationale: `score ${best.s.toFixed(2)}, marge ${margin.toFixed(2)}` };98 if (best.s < 0.35) return { candidate: null, confidence: best.s, method: "none", rationale: `meilleur score ${best.s.toFixed(2)} trop faible` };99 return { candidate: best.c, confidence: best.s, method: "deterministic", rationale: `ambigu : score ${best.s.toFixed(2)}, marge ${margin.toFixed(2)}` };100}101102const TOOL: Anthropic.Tool = {103 name: "choose_product",104 description: "Choisit le produit du détaillant qui correspond à l'article canonique demandé, ou aucun.",105 strict: true,106 input_schema: {107 type: "object", additionalProperties: false,108 properties: {109 index: { type: ["integer", "null"], description: "Indice (0-based) du candidat retenu, null si aucun ne correspond au même produit économique (mêmes dimensions, même matériau, même usage)" },110 confidence: { type: "number", description: "0-1" },111 pack_qty: { type: ["number", "null"], description: "Contenu de l'emballage dans l'unité canonique si le titre l'indique (ex. feuille 4x8 → 32 pi²), sinon null" },112 rationale: { type: "string" },113 },114 required: ["index", "confidence", "pack_qty", "rationale"],115 },116};117118export async function aiMatch(itemLabel: string, unit: string, query: string, candidates: Candidate[], d: Database.Database = getCostDb()): Promise<MatchDecision & { packQty: number | null }> {119 const client = new Anthropic();120 const t0 = Date.now();121 const list = candidates.map((c, i) => `${i}. ${c.title}\n ${c.description.slice(0, 160)}\n ${c.url}`).join("\n");122 const res = await client.messages.create({123 model: MODEL, max_tokens: 400,124 system: "Tu classes des produits de quincaillerie. Tu ne donnes jamais de prix. Tu choisis le candidat qui est le MÊME produit économique que l'article canonique (dimensions nominales identiques, matériau et usage équivalents ; la marque n'importe pas). En cas de doute réel, index = null.",125 tools: [TOOL], tool_choice: { type: "tool", name: "choose_product" },126 messages: [{ role: "user", content: `Article canonique : « ${itemLabel} » (unité ${unit}). Requête : « ${query} ».\nCandidats :\n${list}` }],127 });128 try {129 d.prepare("INSERT INTO ai_usage(analysis_id,purpose,model,input_images,input_tokens,output_tokens,cache_read_tokens,estimated_cost_usd,latency_ms) VALUES(NULL,'product_matching',?,0,?,?,?,?,?)")130 .run(MODEL, res.usage.input_tokens, res.usage.output_tokens, res.usage.cache_read_input_tokens ?? 0, (res.usage.input_tokens * 1 + res.usage.output_tokens * 5) / 1e6, Date.now() - t0);131 } catch { /* test */ }132 const tu = res.content.find((b): b is Anthropic.ToolUseBlock => b.type === "tool_use");133 const inp = (tu?.input ?? {}) as { index?: number | null; confidence?: number; pack_qty?: number | null; rationale?: string };134 const idx = typeof inp.index === "number" && inp.index >= 0 && inp.index < candidates.length ? inp.index : null;135 return { candidate: idx == null ? null : candidates[idx], confidence: Math.max(0, Math.min(1, Number(inp.confidence) || 0)), method: "ai", rationale: `IA : ${inp.rationale ?? ""}`.slice(0, 500), packQty: typeof inp.pack_qty === "number" && inp.pack_qty > 0 ? inp.pack_qty : null };136}137138/* ------------------------------------------------------------ persistance */139140export function upsertMapping(connector: ConnectorKey, itemCode: string, dec: MatchDecision, packQty: number | null, packUnit: string | null, d: Database.Database = getCostDb()): "approved" | "pending" | "rejected" {141 const sid = sourceIdByKey(connector, d);142 if (!dec.candidate) return "rejected";143 const status = dec.confidence >= MATCH_AUTO_APPROVE ? "auto_approved" : "pending";144 d.prepare(`INSERT INTO product_mappings(source_id,product_url,product_title,proposed_item_code,pack_qty,pack_unit,method,confidence,rationale,status)145 VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(source_id,product_url) DO UPDATE SET product_title=excluded.product_title, proposed_item_code=excluded.proposed_item_code, pack_qty=excluded.pack_qty, pack_unit=excluded.pack_unit,146 method=excluded.method, confidence=excluded.confidence, rationale=excluded.rationale, status=CASE WHEN product_mappings.status IN ('approved','rejected') THEN product_mappings.status ELSE excluded.status END`)147 .run(sid, dec.candidate.url, dec.candidate.title, itemCode, packQty, packUnit, dec.method, dec.confidence, dec.rationale, status);148 const row = d.prepare("SELECT status FROM product_mappings WHERE source_id=? AND product_url=?").get(sid, dec.candidate.url) as { status: string };149 if (row.status === "approved" || row.status === "auto_approved") {150 const iid = (d.prepare("SELECT id FROM cost_items WHERE canonical_code=?").get(itemCode) as { id: number } | undefined)?.id;151 if (iid) d.prepare(`INSERT INTO cost_item_sources(cost_item_id,source_id,product_url,product_title,pack_qty,pack_unit,match_method,match_confidence,approved,active) VALUES(?,?,?,?,?,?,?,?,1,1)152 ON CONFLICT(source_id,product_url) DO UPDATE SET cost_item_id=excluded.cost_item_id, product_title=excluded.product_title, pack_qty=COALESCE(excluded.pack_qty, cost_item_sources.pack_qty), pack_unit=COALESCE(excluded.pack_unit, cost_item_sources.pack_unit), match_confidence=excluded.match_confidence, approved=1, active=1`)153 .run(iid, sid, dec.candidate.url, dec.candidate.title, packQty, packUnit, dec.method, dec.confidence);154 return "approved";155 }156 return row.status === "rejected" ? "rejected" : "pending";157}158159/** Approuve/rejette un mapping (admin) et synchronise cost_item_sources. */160export function reviewMapping(id: number, decision: "approved" | "rejected", d: Database.Database = getCostDb()): boolean {161 const m = d.prepare("SELECT * FROM product_mappings WHERE id=?").get(id) as { id: number; source_id: number; product_url: string; product_title: string | null; proposed_item_code: string | null; pack_qty: number | null; pack_unit: string | null; method: string; confidence: number } | undefined;162 if (!m) return false;163 d.prepare("UPDATE product_mappings SET status=?, reviewed_at=datetime('now') WHERE id=?").run(decision, id);164 if (decision === "approved" && m.proposed_item_code) {165 const iid = (d.prepare("SELECT id FROM cost_items WHERE canonical_code=?").get(m.proposed_item_code) as { id: number } | undefined)?.id;166 if (iid) d.prepare(`INSERT INTO cost_item_sources(cost_item_id,source_id,product_url,product_title,pack_qty,pack_unit,match_method,match_confidence,approved,active) VALUES(?,?,?,?,?,?,?,?,1,1)167 ON CONFLICT(source_id,product_url) DO UPDATE SET cost_item_id=excluded.cost_item_id, approved=1, active=1`).run(iid, m.source_id, m.product_url, m.product_title, m.pack_qty, m.pack_unit, m.method, m.confidence);168 } else {169 d.prepare("UPDATE cost_item_sources SET active=0, approved=0 WHERE source_id=? AND product_url=?").run(m.source_id, m.product_url);170 }171 return true;172}173