Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/units.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 * Moteur de conversion d'unités de la base de coûts. Module PUR.44 * Règle : on conserve TOUJOURS l'unité d'origine (source_unit), l'unité45 * canonique (canonical_unit) et le facteur de conversion appliqué.46 */47import type { CanonicalUnit } from "./types";4849export const SQFT_PER_M2 = 10.7639;50export const M2_PER_SQFT = 0.092903;51export const FT_PER_M = 3.28084;52export const M3_PER_FT3 = 0.0283168;53export const LB_PER_KG = 2.20462;54export const L_PER_GAL_US = 3.78541;55export const L_PER_GAL_IMP = 4.54609;5657/** Libellés FR/EN des unités canoniques. */58export const UNIT_LABELS: Record<CanonicalUnit, { fr: string; en: string }> = {59 unit: { fr: "unité", en: "each" },60 pi2: { fr: "pi²", en: "sq ft" },61 pi_lin: { fr: "pi lin.", en: "lin ft" },62 pi3: { fr: "pi³", en: "cu ft" },63 m2: { fr: "m²", en: "m²" },64 m3: { fr: "m³", en: "m³" },65 kg: { fr: "kg", en: "kg" },66 lb: { fr: "lb", en: "lb" },67 L: { fr: "L", en: "L" },68 gal: { fr: "gal", en: "gal" },69 h: { fr: "heure", en: "hour" },70 day: { fr: "jour", en: "day" },71 lump: { fr: "forfait", en: "lump sum" },72};7374/** Unités source reconnues (normalisées en minuscules, sans accents). */75export type SourceUnit =76 | CanonicalUnit77 | "chaque"78 | "each"79 | "ea"80 | "paquet"81 | "pack"82 | "boite"83 | "box"84 | "sac"85 | "bag"86 | "rouleau"87 | "roll"88 | "feuille"89 | "sheet"90 | "seau"91 | "pail"92 | "planche"93 | "board"94 | "longueur"95 | "length"96 | "ballot"97 | "bundle"98 | "verge3"99 | "cu_yd"100 | "tonne"101 | "kit";102103export interface UnitConversion {104 sourceUnit: string;105 canonicalUnit: CanonicalUnit;106 /** prix canonique = prix source × factor (ex. feuille 32 pi² → factor 1/32) */107 factor: number;108 method: string;109}110111export function normalizeUnitToken(raw: string): string {112 return raw113 .normalize("NFD")114 .replace(/[̀-ͯ]/g, "")115 .toLowerCase()116 .replace(/[^a-z0-9/]/g, "")117 .trim();118}119120/** Unités « emballage » qui nécessitent une quantité par emballage propre à l'article. */121const PACK_UNITS = new Set(["paquet", "pack", "boite", "box", "sac", "bag", "rouleau", "roll", "feuille", "sheet", "seau", "pail", "planche", "board", "longueur", "length", "ballot", "bundle", "kit", "pqt", "bte"]);122123const DIRECT: Record<string, CanonicalUnit> = {124 unit: "unit", chaque: "unit", each: "unit", ea: "unit", ch: "unit", un: "unit", unite: "unit",125 pi2: "pi2", pi: "pi_lin", sqft: "pi2", "pi²": "pi2", pieds2: "pi2", piedcarre: "pi2", ft2: "pi2",126 pilin: "pi_lin", lf: "pi_lin", linft: "pi_lin", pl: "pi_lin", ft: "pi_lin",127 pi3: "pi3", ft3: "pi3", m2: "m2", m3: "m3", kg: "kg", lb: "lb", lbs: "lb", l: "L", litre: "L", liter: "L",128 gal: "gal", gallon: "gal", h: "h", heure: "h", hour: "h", hr: "h", day: "day", jour: "day", lump: "lump", forfait: "lump",129};130131/**132 * Convertit un prix exprimé dans une unité source vers l'unité canonique de133 * l'article. `packQty` = contenu d'un emballage exprimé dans l'unité canonique134 * (ex. feuille de gypse 4×8 → 32 pi² ; paquet d'isolant R24 → 78,3 pi²).135 */136export function convertPrice(137 price: number,138 sourceUnitRaw: string,139 canonical: CanonicalUnit,140 packQty?: number | null141): { price: number; conversion: UnitConversion } {142 const tok = normalizeUnitToken(sourceUnitRaw);143 const direct = DIRECT[tok];144 if (direct === canonical) {145 return { price, conversion: { sourceUnit: sourceUnitRaw, canonicalUnit: canonical, factor: 1, method: "identité" } };146 }147 // conversions métriques ↔ impériales simples148 const pair = `${direct ?? tok}->${canonical}`;149 const SIMPLE: Record<string, [number, string]> = {150 "m2->pi2": [1 / SQFT_PER_M2, "1 m² = 10,764 pi²"],151 "pi2->m2": [SQFT_PER_M2, "1 m² = 10,764 pi²"],152 "m3->pi3": [M3_PER_FT3, "1 pi³ = 0,0283 m³"],153 "pi3->m3": [1 / M3_PER_FT3, "1 pi³ = 0,0283 m³"],154 "verge3->m3": [1 / 0.764555, "1 vg³ = 0,7646 m³"],155 "cu_yd->m3": [1 / 0.764555, "1 vg³ = 0,7646 m³"],156 "kg->lb": [1 / LB_PER_KG, "1 kg = 2,2046 lb"],157 "lb->kg": [LB_PER_KG, "1 kg = 2,2046 lb"],158 "gal->L": [1 / L_PER_GAL_US, "1 gal US = 3,785 L"],159 "L->gal": [L_PER_GAL_US, "1 gal US = 3,785 L"],160 "m->pi_lin": [1 / FT_PER_M, "1 m = 3,2808 pi"],161 "pi_lin->m": [FT_PER_M, "1 m = 3,2808 pi"],162 };163 const s = SIMPLE[pair];164 if (s) return { price: price * s[0], conversion: { sourceUnit: sourceUnitRaw, canonicalUnit: canonical, factor: s[0], method: s[1] } };165 // emballages : besoin de la quantité par emballage166 if ((PACK_UNITS.has(tok) || direct === "unit" || tok === "") && packQty && packQty > 0) {167 const f = 1 / packQty;168 return {169 price: price * f,170 conversion: { sourceUnit: sourceUnitRaw, canonicalUnit: canonical, factor: f, method: `1 ${sourceUnitRaw || "emballage"} = ${packQty} ${UNIT_LABELS[canonical].fr}` },171 };172 }173 throw new Error(`Conversion impossible : « ${sourceUnitRaw} » → ${canonical}${packQty ? "" : " (quantité par emballage inconnue)"}`);174}175176/** Vrai si l'unité source est reconnue (canonique, métrique/impériale ou emballage). */177export function isKnownUnit(raw: string): boolean {178 const tok = normalizeUnitToken(raw);179 return tok in DIRECT || PACK_UNITS.has(tok) || ["m", "verge3", "cu_yd", "tonne"].includes(tok);180}181182export const sqftFromM2 = (m2: number): number => m2 * SQFT_PER_M2;183export const m2FromSqft = (sqft: number): number => sqft * M2_PER_SQFT;184