SPB Git

Repository Public

validate.ts 5.2 KB 113 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/cost/connectors/validate.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 * Validation stricte des observations canoniques (sans dépendance) :44 * prix ≤ 0, devise ≠ CAD, unité inconnue, conversion incohérente, aberration45 * par rapport aux prix récents (MAD/IQR) et aux bornes métier (référence46 * interne ×0,25…×4). Les rejets sont conservés en base, jamais supprimés.47 */48import { isKnownUnit } from "../units";49import { detectOutliers } from "../pricing";50import type { CanonicalObservation, ValidationResult } from "./types";5152export interface ValidateContext {53  /** prix récents (unité canonique) par article, autres sources incluses */54  recentPrices: (itemCode: string) => number[];55  referencePrice: (itemCode: string) => number | null;56}5758const UNIT_MAX: Record<string, number> = { pi2: 400, pi_lin: 300, unit: 200000, lump: 500000, m3: 2000, kg: 500, lb: 500, L: 500, gal: 500, h: 1000, day: 5000, pi3: 500, m2: 5000 };5960export function validateObservations(obs: CanonicalObservation[], ctx: ValidateContext): ValidationResult {61  const accepted: CanonicalObservation[] = [];62  const rejected: { obs: CanonicalObservation; reason: string }[] = [];63  const priceGroups = new Map<string, number[]>();6465  for (const o of obs) {66    const reason = basicReason(o, ctx);67    if (reason) { rejected.push({ obs: o, reason }); continue; }68    accepted.push(o);69    if (o.kind === "price") priceGroups.set(o.itemCode, [...(priceGroups.get(o.itemCode) ?? []), o.totalCost]);70  }71  // aberrations statistiques : observation vs prix récents (autres sources) + celles du lot72  const final: CanonicalObservation[] = [];73  for (const o of accepted) {74    if (o.kind !== "price") { final.push(o); continue; }75    const pool = [...ctx.recentPrices(o.itemCode), ...(priceGroups.get(o.itemCode) ?? []).filter((v) => v !== o.totalCost)];76    if (pool.length >= 2) {77      const arr = [...pool, o.totalCost];78      const out = detectOutliers(arr);79      const hit = out.find((x) => x.idx === arr.length - 1);80      if (hit) { rejected.push({ obs: o, reason: `aberration : ${hit.reason}` }); continue; }81    }82    final.push(o);83  }84  return { accepted: final, rejected };85}8687function basicReason(o: CanonicalObservation, ctx: ValidateContext): string | null {88  if (o.kind === "index") {89    if (!Number.isFinite(o.value) || o.value <= 0) return "valeur d'indice invalide";90    if (!/^\d{4}-\d{2}-\d{2}$/.test(o.period)) return "période invalide";91    return null;92  }93  if (o.kind === "labour") {94    if (!(o.baseWage > 10 && o.baseWage < 200)) return `taux horaire implausible (${o.baseWage})`;95    if (!(o.totalEmployerCost >= o.baseWage && o.totalEmployerCost < o.baseWage * 2.2)) return `coût employeur incohérent (${o.totalEmployerCost} vs ${o.baseWage})`;96    if (!/^\d{4}-\d{2}-\d{2}$/.test(o.effectiveFrom)) return "date d'entrée en vigueur invalide";97    return null;98  }99  if (o.currency !== "CAD") return `devise impossible (${o.currency})`;100  if (!(o.rawPrice > 0)) return "prix ≤ 0";101  if (!isKnownUnit(o.sourceUnit)) return `unité inconnue « ${o.sourceUnit} »`;102  if (!(o.conversionFactor > 0) || !Number.isFinite(o.conversionFactor)) return "facteur de conversion invalide";103  if (!(o.totalCost > 0)) return "prix canonique ≤ 0";104  const max = UNIT_MAX[o.canonicalUnit] ?? 1e6;105  if (o.totalCost > max) return `prix par ${o.canonicalUnit} hors bornes (${o.totalCost.toFixed(2)} > ${max}) — emballage probablement mal interprété`;106  const ref = ctx.referencePrice(o.itemCode);107  if (ref != null && ref > 0) {108    const ratio = o.totalCost / ref;109    if (ratio > 4 || ratio < 0.25) return `hors bornes métier : ${ratio.toFixed(2)}× le prix de référence (${ref})`;110  }111  return null;112}113
Files main
Menu

Theme