Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | ACADEMIC RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project : UQO Éval10 * File : src/components/metre/RsmeansPanel.tsx11 * Module : components12 * Repository : https://git.spboucher.ai/uqo-eval13 * Project Website : https://www.uqo-eval.app14 * Created : 2026-10-2815 * Last Modified : 2026-10-2816 *17 * =============================================================================18 * SOFTWARE MAINTAINER & AFFILIATION19 * =============================================================================20 *21 * Maintainer : Simon-Pierre Boucher22 * Position : Professor of Finance23 * Institution : Université du Québec en Outaouais (UQO)24 * Department : Département des sciences administratives25 * Website : https://spboucher.ai26 * Git : https://git.spboucher.ai27 *28 * Research Contact : research@spboucher.ai29 * Direct Contact : simon@spboucher.ai30 * Security/Admin : admin@spboucher.ai31 *32 * The affiliation is descriptive. It is not an institutional endorsement,33 * a license grant or a determination of ownership.34 *35 * =============================================================================36 * COPYRIGHT, AUTHORSHIP & DATA37 * =============================================================================38 *39 * Copyright (c) the author(s) of this work.40 * Ownership is not asserted by this notice; see the repository records.41 *42 * This header identifies the maintainer of the software. Scientific43 * authorship of any associated paper is stated in the paper itself and44 * is not changed by this notice. Datasets and third-party materials45 * remain the property of their respective owners and licensors.46 *47 * This file is governed by the applicable project license, copyright48 * notices, institutional agreements and relevant law.49 *50 * =============================================================================51 * LICENSE & MAINTENANCE52 * =============================================================================53 *54 * License : None specified (no license file in this repository)55 * Classification : Public56 *57 * =============================================================================58 * END OF SP BOUCHER SOURCE HEADER59 * =============================================================================60 */6162// UQO Éval — Quantity Survey : données RSMeans localisées pour le Québec — explorateur (catalogue), sélecteur de ligne (estimation), facteurs.63"use client";64import { useEffect, useState } from "react";65import { api, Btn, Field, Input, money, num, Select } from "./ui";66import type { RsmLine, RsmLocation, RsmPrice, RsmUnitMap } from "@/lib/metre/rsmeans";6768export interface RsmMeta { available: boolean; meta: Record<string, unknown>; locations: RsmLocation[]; labors: { code: string; fr: string; en: string }[]; divisions: Record<string, { fr: string; en: string }> }69export interface RsmRow extends RsmLine { unitMap: RsmUnitMap | null; price: RsmPrice | null }7071/** prix RSMeans par unité RSMeans → prix par unité du module (impérial) ou métrique */72export function perUnit(price: number | null, um: RsmUnitMap | null, metric: boolean): { value: number | null; unit: string } {73 if (price == null || !um) return { value: null, unit: "—" };74 const base = price / um.divisor;75 const METRIC: Record<string, [number, string]> = { ft2: [10.7639, "m²"], ft: [3.28084, "m"], yd3: [1.30795, "m³"], ft3: [35.3147, "m³"], in: [39.3701, "m"] };76 const IMP: Record<string, string> = { ft2: "pi²", ft: "pi", yd3: "vg³", ft3: "pi³", in: "po", unit: um.note?.replace("unité RSMeans : ", "") ?? "unité", h: "h" };77 if (metric && METRIC[um.unit]) return { value: base * METRIC[um.unit][0], unit: METRIC[um.unit][1] };78 return { value: base, unit: IMP[um.unit] ?? um.unit };79}8081export function useRsmMeta(): RsmMeta | null | undefined {82 const [m, setM] = useState<RsmMeta | null | undefined>(undefined);83 useEffect(() => { api<RsmMeta>("/rsmeans?meta=1").then(setM).catch(() => setM(null)); }, []);84 return m;85}8687/** Sélecteur d'une ligne RSMeans pour une ligne d'estimation (basis = rsmeans). */88export function RsmeansPicker({ line, fr, lang, canWrite, projectId, loc, labor, onChange }: { line: string | null; fr: boolean; lang: string; canWrite: boolean; projectId: string; loc: number | null; labor: string; onChange: (p: { rsmeansLine: string; description?: string; unit?: string }) => void }) {89 const [open, setOpen] = useState(false); const [q, setQ] = useState(""); const [div, setDiv] = useState(""); const [rows, setRows] = useState<RsmRow[]>([]); const [busy, setBusy] = useState(false);90 const meta = useRsmMeta();91 useEffect(() => { if (!open) return; const t = setTimeout(() => { setBusy(true); api<{ rows: RsmRow[] }>(`/rsmeans?q=${encodeURIComponent(q)}${div ? `&division=${div}` : ""}&loc=${loc ?? "auto"}&project=${projectId}&labor=${labor}&limit=40`).then((r) => setRows(r.rows)).catch(() => setRows([])).finally(() => setBusy(false)); }, 250); return () => clearTimeout(t); }, [q, div, open, loc, labor, projectId]);92 return (93 <div className="relative">94 <button type="button" disabled={!canWrite} onClick={() => setOpen((o) => !o)} className="vp-mono border-b border-[var(--line-strong)] px-1 py-1 text-left text-[12px] min-w-[180px]" title={fr ? "ligne RSMeans (coûts « bare » localisés)" : "RSMeans line (localized bare costs)"}>{line ? `RSMeans ${line}` : fr ? "choisir une ligne RSMeans…" : "choose an RSMeans line…"}</button>95 {open && (96 <div className="absolute z-20 mt-1 w-[560px] max-w-[90vw] border border-[var(--line-strong)] bg-surface p-2 shadow-lg">97 <div className="flex gap-2"><Input autoFocus value={q} onChange={(ev) => setQ(ev.target.value)} placeholder={fr ? "mots-clés anglais ou n° de ligne (ex. wall framing 2x6, 061110)" : "English keywords or line number (e.g. wall framing 2x6, 061110)"} className="!min-h-0 !py-1 text-[12px]" />98 <Select value={div} onChange={(ev) => setDiv(ev.target.value)} className="!min-h-0 !py-1 w-[180px] text-[12px]"><option value="">{fr ? "toutes divisions" : "all divisions"}</option>{Object.entries(meta?.divisions ?? {}).map(([k, v]) => <option key={k} value={k}>{k} — {fr ? v.fr : v.en}</option>)}</Select></div>99 <ul className="mt-1 max-h-72 overflow-auto text-[12px]">{busy && !rows.length && <li className="text-ink-3">…</li>}{rows.map((h) => (<li key={h.line}><button type="button" className="flex w-full items-baseline justify-between gap-2 px-1 py-1 text-left hover:bg-surface-2" onClick={() => { onChange({ rsmeansLine: h.line, description: h.fullDesc.slice(0, 200), ...(h.unitMap ? { unit: h.unitMap.unit } : {}) }); setOpen(false); }}>100 <span><span className="vp-mono text-ink-3">{h.line}</span> {h.fullDesc}</span><span className="vp-mono whitespace-nowrap text-right">{h.price?.total != null ? `${money(h.price.total, lang, 2)}/${h.unit}` : "—"}{h.price?.method === "factor" && <span className="text-ink-3" title={fr ? "national × facteur" : "national × factor"}> ƒ</span>}</span></button></li>))}101 {!busy && !rows.length && <li className="text-ink-3">{fr ? "aucune ligne" : "no line"}</li>}</ul>102 <div className="mt-1 flex justify-between"><span className="vp-mono text-[10px] text-ink-3">{meta?.locations.find((l) => l.id === loc)?.name ?? (fr ? "ville du projet" : "project city")} · {labor}</span><button type="button" className="vp-mono text-[10px] uppercase text-ink-3" onClick={() => setOpen(false)}>{fr ? "fermer" : "close"}</button></div>103 </div>104 )}105 </div>106 );107}108109/** Explorateur RSMeans du catalogue : recherche, division, ville, type de MO, métrique ; facteurs de localisation ; métadonnées et licence. */110export default function RsmeansPanel({ fr, lang }: { fr: boolean; lang: string }) {111 const meta = useRsmMeta();112 const [q, setQ] = useState("wall framing 2 x 6"); const [div, setDiv] = useState("06"); const [loc, setLoc] = useState(238); const [labor, setLabor] = useState("STD"); const [metric, setMetric] = useState(true);113 const [rows, setRows] = useState<RsmRow[]>([]); const [busy, setBusy] = useState(false); const [factors, setFactors] = useState<{ division: string; labor: string; materialF: number | null; laborF: number | null; equipmentF: number | null; nMaterial: number; sdMaterial: number | null; method: string }[]>([]); const [showF, setShowF] = useState(false);114 useEffect(() => { if (meta === null) return; const t = setTimeout(() => { setBusy(true); api<{ rows: RsmRow[] }>(`/rsmeans?q=${encodeURIComponent(q)}${div ? `&division=${div}` : ""}&loc=${loc}&labor=${labor}&limit=120`).then((r) => setRows(r.rows)).catch(() => setRows([])).finally(() => setBusy(false)); }, 250); return () => clearTimeout(t); }, [q, div, loc, labor, meta]);115 useEffect(() => { if (!showF) return; api<{ factors: typeof factors }>(`/rsmeans?factors=${loc}`).then((r) => setFactors(r.factors)).catch(() => setFactors([])); }, [showF, loc]);116 if (meta === undefined) return <p className="vp-mono text-[11px] uppercase text-ink-3">…</p>;117 if (meta === null) return <p className="text-ink-2">{fr ? "Base RSMeans non installée sur ce nœud (scripts/rsmeans-build.py)." : "RSMeans database not installed on this node (scripts/rsmeans-build.py)."}</p>;118 const m = meta.meta as { release?: string; lines?: number; prices?: number; extracted_at?: string; full_locations?: string[]; sample_locations?: string[]; validation?: Record<string, Record<string, { n: number; mdape_pct: number; p90_pct: number }>>; licence?: string };119 const locObj = meta.locations.find((l) => l.id === loc);120 return (121 <div className="space-y-5">122 <p className="text-[13px] text-ink-2">{fr ? <>Coûts unitaires <b>RSMeans {m.release}</b> (Gordian, MasterFormat 2018) — {num(m.lines ?? 0, lang, 0)} lignes, {num(m.prices ?? 0, lang, 0)} prix localisés, extraits le {m.extracted_at}. Villes extraites <b>en entier</b> : {(m.full_locations ?? []).join(", ")} ; autres villes du Québec : national × facteur de division (échantillon validé, étiqueté « ƒ »). Les coûts affichés sont « <b>bare</b> » (matériau, main-d'œuvre, équipement, sans O&P de l'installateur) ; la colonne Total O&P est la référence RSMeans. Les majorations du module (conditions générales, frais généraux, profit, contingence, taxes) s'appliquent ensuite.</> : <>Unit costs <b>RSMeans {m.release}</b> (Gordian, MasterFormat 2018) — {num(m.lines ?? 0, lang, 0)} lines, {num(m.prices ?? 0, lang, 0)} localized prices, extracted {m.extracted_at}. Cities extracted <b>in full</b>: {(m.full_locations ?? []).join(", ")}; other Québec cities: national × division factor (validated sample, flagged “ƒ”). Costs shown are <b>bare</b> (material, labour, equipment, no installer O&P); the Total O&P column is the RSMeans reference. Module markups apply afterwards.</>}</p>123 <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">124 <Field label={fr ? "Mots-clés (anglais) ou n° de ligne" : "Keywords (English) or line number"}><Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="wall framing 2x6, asphalt shingles, 033053…" /></Field>125 <Field label="Division"><Select value={div} onChange={(e) => setDiv(e.target.value)}><option value="">{fr ? "toutes" : "all"}</option>{Object.entries(meta.divisions).map(([k, v]) => <option key={k} value={k}>{k} — {fr ? v.fr : v.en}</option>)}</Select></Field>126 <Field label={fr ? "Ville (indice de coût)" : "City (cost index)"}><Select value={loc} onChange={(e) => setLoc(Number(e.target.value))}>{meta.locations.map((l) => <option key={l.id} value={l.id}>{l.name}{l.full ? "" : " · ƒ"}</option>)}</Select></Field>127 <Field label={fr ? "Main-d'œuvre" : "Labour"}><Select value={labor} onChange={(e) => setLabor(e.target.value)}>{meta.labors.map((l) => <option key={l.code} value={l.code}>{fr ? l.fr : l.en}</option>)}</Select></Field>128 <Field label={fr ? "Unités" : "Units"}><div className="flex gap-3 pt-2 text-[13px]"><label className="flex items-center gap-1"><input type="radio" checked={metric} onChange={() => setMetric(true)} /> {fr ? "métrique" : "metric"}</label><label className="flex items-center gap-1"><input type="radio" checked={!metric} onChange={() => setMetric(false)} /> {fr ? "impérial (RSMeans)" : "imperial (RSMeans)"}</label></div></Field>129 </div>130 <div className="src-wrap"><table className="src-table"><thead><tr><th>{fr ? "Ligne" : "Line"}</th><th>Description</th><th>{fr ? "Unité" : "Unit"}</th><th>{fr ? "Équipe" : "Crew"}</th><th className="text-right">{fr ? "Prod./jour" : "Daily output"}</th><th className="text-right">{fr ? "h MO" : "Labour h"}</th><th className="text-right">{fr ? "Matériau" : "Material"}</th><th className="text-right">{fr ? "MO" : "Labour"}</th><th className="text-right">{fr ? "Équip." : "Equip."}</th><th className="text-right">{fr ? "Total bare" : "Bare total"}</th><th className="text-right">Total O&P</th><th>{fr ? "Méthode" : "Method"}</th></tr></thead><tbody>131 {rows.map((h) => { const u = perUnit(h.price?.total ?? null, h.unitMap, metric); const f = (v: number | null | undefined) => (v == null ? null : perUnit(v, h.unitMap, metric).value); return (132 <tr key={h.line} className={h.format === "H" ? "bg-surface-2 font-semibold" : ""}><td className="vp-mono whitespace-nowrap text-[11px]">{h.line}</td><td className="text-[12.5px]" style={{ paddingLeft: 4 + h.indent * 10, minWidth: 420 }} title={h.fullDesc}>{h.format === "H" ? h.shortDesc : h.fullDesc}</td><td className="vp-mono whitespace-nowrap text-[11px]">{h.unit ? `$/${u.unit}` : ""}</td><td className="vp-mono whitespace-nowrap text-[11px]">{h.crew ?? ""}</td><td className="vp-mono text-right text-[11px]">{h.dailyOutput != null ? num(h.dailyOutput, lang, 2) : ""}</td><td className="vp-mono text-right text-[11px]">{h.laborHours != null ? num(h.laborHours, lang, 3) : ""}</td>133 <td className="vp-mono text-right text-[12px]">{h.price ? money(f(h.price.material), lang, 2) : ""}</td><td className="vp-mono text-right text-[12px]">{h.price ? money(f(h.price.labor_cost), lang, 2) : ""}</td><td className="vp-mono text-right text-[12px]">{h.price ? money(f(h.price.equipment), lang, 2) : ""}</td><td className="vp-mono whitespace-nowrap text-right text-[12px]"><b>{h.price ? money(u.value, lang, 2) : ""}</b></td><td className="vp-mono whitespace-nowrap text-right text-[12px]">{h.price ? money(f(h.price.totalOp), lang, 2) : ""}</td><td className="vp-mono whitespace-nowrap text-[10px] uppercase text-ink-3">{h.price ? (h.price.method === "full" ? (fr ? "extrait" : "extracted") : "ƒ national × facteur") : h.unit ? (fr ? "sans prix" : "no price") : ""}{h.price && h.price.labor !== h.price.laborRequested ? ` · ${h.price.labor}` : ""}</td></tr>); })}134 {!rows.length && <tr><td colSpan={12} className="text-ink-2">{busy ? "…" : fr ? "Aucune ligne." : "No line."}</td></tr>}135 </tbody></table></div>136 <div className="flex flex-wrap items-center gap-3"><Btn small onClick={() => setShowF((v) => !v)}>{showF ? (fr ? "Masquer les facteurs" : "Hide factors") : (fr ? `Facteurs de localisation — ${locObj?.name ?? ""}` : `Location factors — ${locObj?.name ?? ""}`)}</Btn><span className="text-[12px] text-ink-2">{fr ? "Facteur = médiane des ratios ville / moyenne nationale par division et nature de coût (lignes ≥ 1 $). Validation sur les villes extraites en entier : " : "Factor = median of city / national ratios per division and cost nature (lines ≥ $1). Validation on fully extracted cities: "}{Object.entries(m.validation ?? {}).map(([k, v]) => `${k} ${Object.entries(v).map(([kk, vv]) => `${kk} MdAPE ${vv.mdape_pct} % (p90 ${vv.p90_pct} %, n = ${vv.n})`).join(", ")}`).join(" · ") || "—"}</span></div>137 {showF && <div className="src-wrap"><table className="src-table"><thead><tr><th>Division</th><th>{fr ? "MO" : "Labour"}</th><th className="text-right">{fr ? "Matériau ×" : "Material ×"}</th><th className="text-right">{fr ? "MO ×" : "Labour ×"}</th><th className="text-right">{fr ? "Équip. ×" : "Equip. ×"}</th><th className="text-right">n</th><th className="text-right">{fr ? "écart-type" : "sd"}</th><th>{fr ? "Méthode" : "Method"}</th></tr></thead><tbody>138 {factors.map((f) => <tr key={`${f.labor}-${f.division}`}><td className="vp-mono text-[11px]">{f.division} — {fr ? meta.divisions[f.division]?.fr : meta.divisions[f.division]?.en}</td><td className="vp-mono text-[11px]">{f.labor}</td><td className="vp-mono text-right">{f.materialF != null ? num(f.materialF, lang, 3) : "—"}</td><td className="vp-mono text-right">{f.laborF != null ? num(f.laborF, lang, 3) : "—"}</td><td className="vp-mono text-right">{f.equipmentF != null ? num(f.equipmentF, lang, 3) : "—"}</td><td className="vp-mono text-right">{f.nMaterial}</td><td className="vp-mono text-right">{f.sdMaterial != null ? num(f.sdMaterial, lang, 3) : "—"}</td><td className="vp-mono text-[10px] uppercase text-ink-3">{f.method}</td></tr>)}139 {!factors.length && <tr><td colSpan={8} className="text-ink-2">{fr ? "Aucun facteur pour cette ville (ville extraite en entier : prix directs)." : "No factor for this city (fully extracted city: direct prices)."}</td></tr>}140 </tbody></table></div>}141 <p className="vp-mono text-[10.5px] uppercase tracking-[0.04em] text-ink-3">{m.licence}</p>142 </div>143 );144}145