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/EstimateEditor.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 — Métré : éditeur d'estimation — lignes liées au registre, assemblages du catalogue/recettes ou prix supposés,63// paramètres (région, date des prix, majorations ordonnées, actualisation StatCan, taxes), scénarios, sensibilité, révisions immuables.64"use client";65import { useCallback, useEffect, useRef, useState } from "react";66import type { WorkspaceData } from "./ProjectWorkspace";67import { api, Block, Btn, dt, Err, Field, Input, money, num, Prov, Select } from "./ui";68import type { EstimateLineInput, EstimateParams, EstimateResult } from "@/lib/metre/types";69import { unitLabel } from "@/lib/metre/units";70import { RsmeansPicker, useRsmMeta } from "./RsmeansPanel";7172interface EstimateFull { id: string; name: string; params: EstimateParams; lines: EstimateLineInput[]; projectId: string }73interface Loaded { estimate: EstimateFull; result: EstimateResult; staleLinks: string[]; versions?: { id: string; number: number; label: string; total: number; createdAt: string }[] }74interface CatHit { code: string; nameFr: string; nameEn: string; unit: string; category: string; source: "catalogue" | "custom"; direct: number | null; observedShare: number | null }75const uuid = () => crypto.randomUUID();7677export default function EstimateEditor({ d, fr, lang, canWrite, reload }: { d: WorkspaceData; fr: boolean; lang: string; canWrite: boolean; reload: () => Promise<void> }) {78 const [estSel, setEstId] = useState<string | null>(null);79 const estId = estSel ?? d.estimates[0]?.id ?? null;80 const [data, setData] = useState<Loaded | null>(null);81 const [err, setErr] = useState<string | null>(null);82 const [saving, setSaving] = useState(false);83 const [hideCosts, setHideCosts] = useState(false);84 const [qsPricing, setQsPricing] = useState<"catalogue" | "rsmeans">("rsmeans");85 const rsm = useRsmMeta();86 const [qsBusy, setQsBusy] = useState(false); const [qsInfo, setQsInfo] = useState<{ summary: Record<string, number>; warnings: string[]; lines: number } | null>(null);87 const timer = useRef<ReturnType<typeof setTimeout> | null>(null);88 const load = useCallback((id: string) => api<Loaded>(`/estimates/${id}`).then(setData).catch((e) => setErr(e.message)), []);89 useEffect(() => { if (estId) void load(estId); }, [estId, load]);9091 const patch = (p: { lines?: EstimateLineInput[]; params?: Partial<EstimateParams>; name?: string }) => {92 if (!data || !canWrite) return;93 const next = { ...data, estimate: { ...data.estimate, ...(p.name ? { name: p.name } : {}), lines: p.lines ?? data.estimate.lines, params: { ...data.estimate.params, ...(p.params ?? {}) } } };94 setData(next);95 if (timer.current) clearTimeout(timer.current);96 timer.current = setTimeout(async () => { setSaving(true); try { const r = await api<Loaded>(`/estimates/${data.estimate.id}`, { method: "PATCH", json: { name: next.estimate.name, params: p.params ?? undefined, lines: next.estimate.lines } }); setData((cur) => (cur ? { ...r, versions: cur.versions } : r)); setErr(null); } catch (e) { setErr((e as Error).message); } finally { setSaving(false); } }, 450);97 };98 const create = async () => { try { const r = await api<{ estimate: { id: string } }>(`/projects/${d.project.id}/estimates`, { method: "POST", json: { name: `${fr ? "Estimation" : "Estimate"} ${d.estimates.length + 1}` } }); await reload(); setEstId(r.estimate.id); } catch (e) { setErr((e as Error).message); } };99 const freeze = async () => { if (!data) return; const label = prompt(fr ? "Libellé de la révision" : "Revision label", `${fr ? "Révision" : "Revision"} ${(data.versions?.length ?? 0) + 1}`); if (label == null) return; const scenario = prompt(fr ? "Scénario (facultatif)" : "Scenario (optional)", "") || null; try { await api(`/estimates/${data.estimate.id}/freeze`, { method: "POST", json: { label, scenario } }); await reload(); await load(data.estimate.id); } catch (e) { setErr((e as Error).message); } };100101 const qs = async () => { setQsBusy(true); setErr(null); try { const r = await api<{ estimate: { id: string }; summary: Record<string, number>; warnings: string[]; lines: number }>(`/projects/${d.project.id}/quantity-survey`, { method: "POST", json: { pricing: rsm ? qsPricing : "catalogue", estimateId: estId } }); setQsInfo(r); await reload(); setEstId(r.estimate.id); await load(r.estimate.id); } catch (e) { setErr((e as Error).message); } finally { setQsBusy(false); } };102 if (!d.estimates.length) return <Block num="01" title={fr ? "Estimation" : "Estimate"}><p className="text-[13.5px] text-ink-2">{fr ? "Aucune estimation pour ce projet." : "No estimate for this project yet."}</p><div className="flex flex-wrap gap-2">{canWrite && <Btn tone="primary" onClick={() => void create()}>{fr ? "+ Créer une estimation" : "+ Create an estimate"}</Btn>}{canWrite && <Btn tone="accent" disabled={qsBusy} onClick={() => void qs()}>{qsBusy ? "…" : fr ? "⚙ Relevé des quantités depuis les plans" : "⚙ Quantity survey from plans"}</Btn>}</div><Err msg={err} /></Block>;103 if (!data) return <div className="vp-mono text-[11px] uppercase text-ink-3">{fr ? "Chargement…" : "Loading…"}<Err msg={err} /></div>;104 const e = data.estimate, r = data.result, p = e.params;105 const setLine = (id: string, patchL: Partial<EstimateLineInput>) => patch({ lines: e.lines.map((l) => (l.id === id ? { ...l, ...patchL } : l)) });106 const addLine = (init: Partial<EstimateLineInput> = {}) => patch({ lines: [...e.lines, { id: uuid(), wbs: "00", description: "", assemblyCode: null, measurementId: null, quantity: 0, unit: d.project.unitSystem === "imperial" ? "ft2" : "m2", adjustmentFactor: 1, basis: "catalogue", unitPrice: null, installed: false, assumptionNote: null, excluded: false, sortOrder: e.lines.length, ...init }] });107 const res = (id: string) => r.lines.find((l) => l.id === id);108 const T = r.totals;109 return (110 <div className="space-y-12">111 <Block num="01" title={fr ? "Estimation" : "Estimate"} aside={<div className="flex flex-wrap items-center gap-2"><Select value={e.id} onChange={(ev) => setEstId(ev.target.value)} className="!min-h-0 !py-1 w-[220px] text-[12px]">{d.estimates.map((x) => <option key={x.id} value={x.id}>{x.name} ({x.versions} rév.)</option>)}</Select>{canWrite && <Btn small onClick={() => void create()}>+</Btn>}<label className="vp-mono flex items-center gap-1 text-[10.5px] uppercase"><input type="checkbox" checked={hideCosts} onChange={(ev) => setHideCosts(ev.target.checked)} /> 🎓 {fr ? "masquer les coûts" : "hide costs"}</label><span className="vp-mono text-[10px] uppercase text-ink-3">{saving ? (fr ? "enregistrement…" : "saving…") : `${fr ? "calculé" : "computed"} ${dt(r.computedAt, lang)}`}</span></div>}>112 <Field label={fr ? "Nom" : "Name"}><Input value={e.name} disabled={!canWrite} onChange={(ev) => patch({ name: ev.target.value })} /></Field>113 {data.staleLinks.length > 0 && <p className="border-l-2 border-[var(--amber)] pl-3 text-[13px]">{fr ? `${data.staleLinks.length} ligne(s) liée(s) à une mesure périmée — recalculez le registre (onglet Relevé).` : `${data.staleLinks.length} line(s) linked to a stale measurement — recompute the ledger (Takeoff tab).`}</p>}114 <div className="src-wrap"><table className="src-table"><thead><tr><th>{fr ? "Div." : "Div."}</th><th>{fr ? "Description" : "Description"}</th><th>{fr ? "Quantité" : "Quantity"}</th><th>{fr ? "Mesure liée" : "Linked measure"}</th><th>×</th><th>{fr ? "Assemblage / base" : "Assembly / basis"}</th>{!hideCosts && <><th className="text-right">{fr ? "Unitaire" : "Unit cost"}</th><th className="text-right">{fr ? "Localisé" : "Located"}</th><th>Prov.</th></>}<th></th></tr></thead><tbody>115 {e.lines.map((l) => { const rr = res(l.id); const m = l.measurementId ? d.measurements.find((x) => x.id === l.measurementId) : null; return (116 <tr key={l.id} className={l.excluded ? "opacity-50" : ""}>117 <td><Input value={l.wbs} disabled={!canWrite} onChange={(ev) => setLine(l.id, { wbs: ev.target.value })} className="vp-mono !min-h-0 !py-1 w-[64px] text-[12px]" /></td>118 <td>{l.origin === "qs" && <span className="vp-mono text-[9px] uppercase text-accent" title={fr ? "relevé des quantités" : "quantity survey"}>qs </span>}<Input value={l.description} disabled={!canWrite} onChange={(ev) => setLine(l.id, { description: ev.target.value })} className="!min-h-0 !py-1 min-w-[160px] text-[13px]" />{rr?.warnings.length ? <div className="text-[10.5px] text-[var(--amber)]">{rr.warnings.join(" · ")}</div> : null}</td>119 <td className="whitespace-nowrap">{m ? <span className="vp-mono text-[12px]">{num(m.value, lang, 3)} {unitLabel(m.unit, fr)}{m.stale && " ⚠"}</span> : <span className="flex items-center gap-1"><Input type="number" step="0.001" min={0} value={l.quantity} disabled={!canWrite} onChange={(ev) => setLine(l.id, { quantity: Number(ev.target.value) })} className="vp-mono !min-h-0 !py-1 w-[90px] text-[12px]" /><Select value={l.unit} disabled={!canWrite} onChange={(ev) => setLine(l.id, { unit: ev.target.value })} className="!min-h-0 !py-1 w-[72px] text-[11px]">{["m", "ft", "m2", "ft2", "m3", "ft3", "yd3", "unit", "h", "lump"].map((u) => <option key={u} value={u}>{unitLabel(u, fr)}</option>)}</Select></span>}</td>120 <td><Select value={l.measurementId ?? ""} disabled={!canWrite} onChange={(ev) => { const mm = d.measurements.find((x) => x.id === ev.target.value); setLine(l.id, { measurementId: ev.target.value || null, ...(mm ? { quantity: mm.value, unit: mm.unit, description: l.description || mm.name } : {}) }); }} className="!min-h-0 !py-1 w-[150px] text-[11px]"><option value="">{fr ? "— saisie —" : "— manual —"}</option>{d.measurements.map((x) => <option key={x.id} value={x.id}>{x.name} ({num(x.value, lang, 2)} {x.unit})</option>)}</Select></td>121 <td><Input type="number" step="0.01" min={0.0001} value={l.adjustmentFactor} disabled={!canWrite} title={fr ? "facteur d'ajustement explicite (ex. 1,05 = +5 %)" : "explicit adjustment factor (e.g. 1.05 = +5 %)"} onChange={(ev) => setLine(l.id, { adjustmentFactor: Number(ev.target.value) || 1 })} className="vp-mono !min-h-0 !py-1 w-[62px] text-[12px]" /></td>122 <td>{l.basis === "rsmeans" ? <RsmeansPicker line={l.rsmeansLine ?? null} fr={fr} lang={lang} canWrite={canWrite} projectId={d.project.id} loc={p.rsmeansLocationId ?? null} labor={p.rsmeansLabor ?? "STD"} onChange={(pl) => setLine(l.id, { rsmeansLine: pl.rsmeansLine, ...(l.description ? {} : pl.description ? { description: pl.description } : {}), ...(!l.measurementId && pl.unit ? { unit: pl.unit } : {}) })} /> : <AssemblyPicker l={l} fr={fr} lang={lang} canWrite={canWrite} projectId={d.project.id} date={p.priceDate} region={p.regionCode} onChange={(pl) => setLine(l.id, pl)} />}</td>123 {!hideCosts && <><td className="vp-mono text-right text-[12px]">{rr ? money(rr.unitDirect, lang, 2) : "—"}<div className="text-[10px] text-ink-3">{rr ? `/${unitLabel(rr.unit, fr)}` : ""}</div></td><td className="vp-mono text-right"><b>{rr ? money(rr.located, lang) : "—"}</b></td><td>{rr && <Prov kind={rr.provenance.kind} share={rr.provenance.observedShare} fr={fr} />}</td></>}124 <td className="whitespace-nowrap">{canWrite && <><button type="button" className="vp-mono text-[10px] uppercase text-ink-3 hover:text-accent" onClick={() => setLine(l.id, { excluded: !l.excluded })}>{l.excluded ? (fr ? "inclure" : "include") : (fr ? "exclure" : "exclude")}</button> <button type="button" className="vp-mono text-[10px] text-ink-3 hover:text-[var(--danger)]" onClick={() => patch({ lines: e.lines.filter((x) => x.id !== l.id) })}>✕</button></>}</td>125 </tr>); })}126 </tbody></table></div>127 {canWrite && <div className="mt-card !p-3"><div className="flex flex-wrap items-center gap-3"><Btn tone="accent" small disabled={qsBusy} onClick={() => void qs()}>{qsBusy ? "…" : fr ? "⚙ Générer le relevé des quantités (plans + fiche)" : "⚙ Generate the quantity survey (plans + sheet)"}</Btn>{rsm && <Select value={qsPricing} onChange={(ev) => setQsPricing(ev.target.value as "catalogue" | "rsmeans")} className="!min-h-0 !py-1 w-[300px] text-[12px]"><option value="rsmeans">{fr ? "prix RSMeans localisés (ville du projet)" : "localized RSMeans prices (project city)"}</option><option value="catalogue">{fr ? "catalogue UQO Éval (détaillants / APCHQ)" : "UQO Éval catalogue (retailers / APCHQ)"}</option></Select>}<span className="text-[12px] text-ink-2">{fr ? "Méthode du relevé des quantités : excavation, fondations, structure, enveloppe, toiture, ouvertures, isolation, finitions, cuisine, bains, plomberie, CVCA, électricité, extérieur — chaque ligne garde sa formule, ses entrées et ses pages sources ; les lignes « qs » sont remplacées à chaque génération, vos lignes saisies sont conservées. Complétez la fiche technique (onglet Fiche) pour les éléments invisibles sur le plan." : "Quantity survey method: excavation, foundations, structure, envelope, roofing, openings, insulation, finishes, kitchen, baths, plumbing, HVAC, electrical, exterior — each line keeps its formula, inputs and source pages; “qs” lines are replaced on each run, your own lines are kept. Fill the technical sheet (Sheet tab) for items not visible on the plan."}</span></div>128 {qsInfo && <p className="vp-mono mt-2 text-[10.5px] text-ink-2">{qsInfo.lines} {fr ? "lignes" : "lines"} · {Object.entries(qsInfo.summary).map(([k, v]) => `${k.replace(/_/g, " ")} ${v}`).join(" · ")}{qsInfo.warnings.length ? ` · ⚠ ${qsInfo.warnings.join(" ; ")}` : ""}</p>}</div>}129 {canWrite && <div className="flex flex-wrap gap-2"><Btn small onClick={() => addLine()}>{fr ? "+ Ligne (catalogue)" : "+ Line (catalogue)"}</Btn>{rsm && <Btn small onClick={() => addLine({ basis: "rsmeans", rsmeansLine: null, description: "" })}>{fr ? "+ Ligne RSMeans" : "+ RSMeans line"}</Btn>}<Btn small onClick={() => addLine({ basis: "assumption", unitPrice: 0, installed: true, description: fr ? "Prix supposé" : "Assumed price" })}>{fr ? "+ Ligne hypothèse (prix saisi)" : "+ Assumption line (entered price)"}</Btn><Btn small onClick={() => { const missing = d.measurements.filter((m) => !e.lines.some((l) => l.measurementId === m.id)); patch({ lines: [...e.lines, ...missing.map((m, i) => ({ id: uuid(), wbs: "00", description: m.name, assemblyCode: null, measurementId: m.id, quantity: m.value, unit: m.unit, adjustmentFactor: 1, basis: "catalogue" as const, unitPrice: null, installed: false, assumptionNote: null, excluded: false, sortOrder: e.lines.length + i }))] }); }}>{fr ? "+ Toutes les mesures non liées" : "+ All unlinked measurements"}</Btn></div>}130 <Err msg={err} />131 </Block>132133 <Block num="02" title={fr ? "Paramètres et ordre d'application" : "Parameters and application order"}>134 <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">135 <Field label={fr ? "Région de prix" : "Price region"}><Select value={p.regionCode ?? ""} disabled={!canWrite} onChange={(ev) => patch({ params: { regionCode: ev.target.value || null } })}><option value="">{fr ? "auto" : "auto"}</option>{d.locations.map((l) => <option key={l.code} value={l.code}>{l.code} — {fr ? l.nameFr : l.nameEn}</option>)}</Select></Field>136 <Field label={fr ? "Date des prix (instantané)" : "Price date (snapshot)"}><Input type="date" value={p.priceDate} disabled={!canWrite} onChange={(ev) => patch({ params: { priceDate: ev.target.value } })} /></Field>137 <Field label={fr ? "Actualiser au (StatCan 18-10-0289)" : "Escalate to (StatCan 18-10-0289)"}><Input type="date" value={p.escalateTo ?? ""} disabled={!canWrite} onChange={(ev) => patch({ params: { escalateTo: ev.target.value || null, escalationFactor: null } })} /></Field>138 <Field label={fr ? "Facteur d'actualisation" : "Escalation factor"}><span className="vp-mono text-[13px]">{p.escalationFactor ? `× ${p.escalationFactor.toFixed(4)}` : "—"}<div className="text-[10px] text-ink-3">{p.escalationSource ?? (p.escalateTo ? (fr ? "indice indisponible pour cet intervalle" : "index unavailable for this span") : "")}</div></span></Field>139 {([["generalConditionsPct", fr ? "Conditions générales (% du direct)" : "General conditions (% of direct)"], ["overheadPct", fr ? "Frais généraux (% du cumul)" : "Overhead (% of cumulative)"], ["profitPct", fr ? "Profit (% du cumul)" : "Profit (% of cumulative)"], ["contingencyPct", fr ? "Contingence (% du direct)" : "Contingency (% of direct)"]] as const).map(([k, lab]) => (<Field key={k} label={lab}><Input type="number" step="0.1" min={0} max={50} value={p[k]} disabled={!canWrite} onChange={(ev) => patch({ params: { [k]: Number(ev.target.value) } })} className="vp-mono" /></Field>))}140 {rsm && <Field label={fr ? "Ville RSMeans (lignes RSMeans)" : "RSMeans city (RSMeans lines)"}><Select value={p.rsmeansLocationId ?? ""} disabled={!canWrite} onChange={(ev) => patch({ params: { rsmeansLocationId: ev.target.value ? Number(ev.target.value) : null } })}><option value="">{fr ? "auto (municipalité du projet)" : "auto (project municipality)"}</option>{rsm.locations.map((l) => <option key={l.id} value={l.id}>{l.name}{l.full ? "" : " · ƒ"}</option>)}</Select></Field>}141 {rsm && <Field label={fr ? "Main-d'œuvre RSMeans" : "RSMeans labour"}><Select value={p.rsmeansLabor ?? "STD"} disabled={!canWrite} onChange={(ev) => patch({ params: { rsmeansLabor: ev.target.value as EstimateParams["rsmeansLabor"] } })}>{rsm.labors.map((l) => <option key={l.code} value={l.code}>{fr ? l.fr : l.en}</option>)}</Select></Field>}142 <Field label={fr ? "Taxes" : "Taxes"}><div className="flex gap-4 text-[13px]"><label className="flex items-center gap-1"><input type="checkbox" checked={p.applyGst} disabled={!canWrite} onChange={(ev) => patch({ params: { applyGst: ev.target.checked } })} /> TPS 5 %</label><label className="flex items-center gap-1"><input type="checkbox" checked={p.applyQst} disabled={!canWrite} onChange={(ev) => patch({ params: { applyQst: ev.target.checked } })} /> TVQ 9,975 %</label></div></Field>143 <Field label={fr ? "Arrondi du total" : "Total rounding"}><Select value={p.roundingCents} disabled={!canWrite} onChange={(ev) => patch({ params: { roundingCents: Number(ev.target.value) } })}><option value={1}>{fr ? "au cent" : "to the cent"}</option><option value={100}>{fr ? "au dollar" : "to the dollar"}</option><option value={10000}>{fr ? "à 100 $" : "to $100"}</option></Select></Field>144 </div>145 <ol className="vp-mono list-decimal space-y-0.5 pl-5 text-[11px] text-ink-2">{r.applicationOrder.map((s, i) => <li key={i}>{s}</li>)}</ol>146 </Block>147148 {!hideCosts && (149 <Block num="03" title={fr ? "Récapitulatif" : "Summary"} aside={canWrite && <Btn small tone="primary" onClick={() => void freeze()}>{fr ? "Figer une révision" : "Freeze a revision"}</Btn>}>150 <div className="grid gap-6 lg:grid-cols-[1fr_1fr]">151 <div className="src-wrap"><table className="src-table"><tbody>152 {([[fr ? "Direct" : "Direct", T.direct], [fr ? "Ajustement régional" : "Regional adjustment", T.locationAdjustment], [fr ? "Direct localisé" : "Located direct", T.located], [`${fr ? "Conditions générales" : "General conditions"} ${p.generalConditionsPct} %`, T.generalConditions], [`${fr ? "Frais généraux" : "Overhead"} ${p.overheadPct} %`, T.overhead], [`Profit ${p.profitPct} %`, T.profit], [`${fr ? "Contingence" : "Contingency"} ${p.contingencyPct} %`, T.contingency], [fr ? "Actualisation" : "Escalation", T.escalation], [fr ? "Sous-total avant taxes" : "Subtotal before tax", T.subtotalBeforeTax], ["TPS", T.gst], ["TVQ", T.qst]] as [string, number][]).map(([k, v], i) => (<tr key={i} className={i === 2 || i === 8 ? "bg-surface-2 font-semibold" : ""}><td>{k}</td><td className="vp-mono text-right">{money(v, lang, 2)}</td></tr>))}153 <tr className="bg-ink text-paper font-bold"><td>TOTAL</td><td className="vp-mono text-right">{money(T.total, lang, 2)}</td></tr>154 </tbody></table></div>155 <div className="space-y-3">156 <div className="flex flex-wrap gap-x-5 gap-y-2"><span className="stat-chip"><b>{money(T.material, lang)}</b> {fr ? "matériaux" : "materials"}</span><span className="stat-chip"><b>{money(T.labour, lang)}</b> {fr ? "MO" : "labour"}</span><span className="stat-chip"><b>{money(T.equipment, lang)}</b> {fr ? "équip." : "equip."}</span><span className="stat-chip"><b>{money(T.other, lang)}</b> {fr ? "autres" : "other"}</span></div>157 <div className="flex flex-wrap gap-x-5 gap-y-2"><span className="stat-chip"><b>{r.coverage.linesPriced}/{r.coverage.linesTotal}</b> {fr ? "lignes chiffrées" : "priced lines"}</span><span className="stat-chip"><b>{Math.round(r.coverage.observedShare * 100)} %</b> {fr ? "observé" : "observed"}</span><span className="stat-chip"><b>{Math.round(r.coverage.assumptionShare * 100)} %</b> {fr ? "hypothèses" : "assumptions"}</span></div>158 {r.byWbs.length > 0 && <div className="src-wrap"><table className="src-table"><thead><tr><th>{fr ? "Division" : "Division"}</th><th className="text-right">{fr ? "Localisé" : "Located"}</th><th className="text-right">%</th></tr></thead><tbody>{r.byWbs.map((w) => <tr key={w.wbs}><td>{w.wbs}</td><td className="vp-mono text-right">{money(w.located, lang)}</td><td className="vp-mono text-right">{w.sharePct}</td></tr>)}</tbody></table></div>}159 {r.warnings.length > 0 && <ul className="space-y-0.5 text-[12.5px] text-[var(--amber)]">{r.warnings.map((w, i) => <li key={i}>⚠ {w}</li>)}</ul>}160 </div>161 </div>162 <Analysis estId={e.id} fr={fr} lang={lang} params={p} />163 </Block>164 )}165166 <AiPanel estimateId={e.id} projectId={d.project.id} fr={fr} canWrite={canWrite} lines={e.lines} onApplyMapping={(targetType, targetId, code) => {167 if (targetType === "line") setLine(targetId, { assemblyCode: code, basis: "catalogue" });168 else { const m = d.measurements.find((x) => x.id === targetId); if (!m) return; const existing = e.lines.find((l) => l.measurementId === targetId); if (existing) setLine(existing.id, { assemblyCode: code, basis: "catalogue" }); else addLine({ measurementId: targetId, quantity: m.value, unit: m.unit, description: m.name, assemblyCode: code }); }169 }} />170171 <Block num="05" title={fr ? "Révisions figées" : "Frozen revisions"}>172 {!data.versions?.length ? <p className="text-[13.5px] text-ink-2">{fr ? "Aucune révision figée pour cette estimation." : "No frozen revision for this estimate."}</p> : <ul className="divide-y divide-[var(--line)] text-[13.5px]">{data.versions.map((v) => <li key={v.id} className="flex flex-wrap items-baseline justify-between gap-2 py-2"><span><b>r{v.number}</b> — {v.label}</span><span className="vp-mono text-[12px]">{money(v.total, lang)} · {dt(v.createdAt, lang)} · <a className="text-accent" href={`/api/metre/versions/${v.id}?format=pdf&lang=${lang}`}>PDF</a></span></li>)}</ul>}173 </Block>174 </div>175 );176}177178function AssemblyPicker({ l, fr, lang, canWrite, projectId, date, region, onChange }: { l: EstimateLineInput; fr: boolean; lang: string; canWrite: boolean; projectId: string; date: string; region: string | null; onChange: (p: Partial<EstimateLineInput>) => void }) {179 const [q, setQ] = useState(""); const [hits, setHits] = useState<CatHit[]>([]); const [open, setOpen] = useState(false);180 useEffect(() => { if (!open) return; const t = setTimeout(() => api<{ assemblies: CatHit[] }>(`/catalogue?project=${projectId}&q=${encodeURIComponent(q)}&date=${date}${region ? `®ion=${region}` : ""}&limit=25`).then((r) => setHits(r.assemblies)).catch(() => setHits([])), 250); return () => clearTimeout(t); }, [q, open, projectId, date, region]);181 if (l.basis === "assumption") return (182 <div className="flex flex-wrap items-center gap-1"><Input type="number" step="0.01" min={0} value={l.unitPrice ?? ""} disabled={!canWrite} placeholder="$" onChange={(ev) => onChange({ unitPrice: ev.target.value === "" ? null : Number(ev.target.value) })} className="vp-mono !min-h-0 !py-1 w-[90px] text-[12px]" /><span className="vp-mono text-[10px] text-ink-3">$/{unitLabel(l.unit, fr)}</span>183 <label className="vp-mono text-[10px] uppercase"><input type="checkbox" checked={l.installed} disabled={!canWrite} onChange={(ev) => onChange({ installed: ev.target.checked })} /> {fr ? "installé" : "installed"}</label>184 <Input value={l.assumptionNote ?? ""} disabled={!canWrite} placeholder={fr ? "justification (soumission, devis…)" : "rationale (quote, bid…)"} onChange={(ev) => onChange({ assumptionNote: ev.target.value })} className="!min-h-0 !py-1 min-w-[150px] text-[11.5px]" /></div>);185 return (186 <div className="relative">187 <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]">{l.assemblyCode ?? (fr ? "choisir…" : "choose…")}</button>188 {open && (189 <div className="absolute z-20 mt-1 w-[360px] border border-[var(--line-strong)] bg-surface p-2 shadow-lg">190 <Input autoFocus value={q} onChange={(ev) => setQ(ev.target.value)} placeholder={fr ? "rechercher (mur, toit, dalle, cuisine…)" : "search (wall, roof, slab, kitchen…)"} className="!min-h-0 !py-1 text-[12px]" />191 <ul className="mt-1 max-h-64 overflow-auto text-[12px]">{hits.map((h) => (<li key={h.code}><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({ assemblyCode: h.code, basis: h.source === "custom" ? "custom_assembly" : "catalogue", description: l.description || (fr ? h.nameFr : h.nameEn) }); setOpen(false); }}><span><span className="vp-mono text-accent">{h.code}</span> {fr ? h.nameFr : h.nameEn} <span className="text-ink-3">{h.source === "custom" ? "★" : ""}</span></span><span className="vp-mono whitespace-nowrap text-ink-2">{h.direct != null ? `${money(h.direct, lang, 2)}/${unitLabel(h.unit, fr)}` : "—"} {h.observedShare != null && <span className="text-ink-3">{Math.round(h.observedShare * 100)} %</span>}</span></button></li>))}{!hits.length && <li className="px-1 py-1 text-ink-3">—</li>}</ul>192 <div className="mt-1 flex justify-between"><button type="button" className="vp-mono text-[10px] uppercase text-ink-3" onClick={() => { onChange({ assemblyCode: null }); setOpen(false); }}>{fr ? "aucun" : "none"}</button><button type="button" className="vp-mono text-[10px] uppercase text-ink-3" onClick={() => setOpen(false)}>{fr ? "fermer" : "close"}</button></div>193 </div>194 )}195 </div>196 );197}198199function Analysis({ estId, fr, lang, params }: { estId: string; fr: boolean; lang: string; params: EstimateParams }) {200 const [sc, setSc] = useState<{ label: string; totals: EstimateResult["totals"]; deltaPct: number }[] | null>(null);201 const [se, setSe] = useState<{ param: string; minus: number; plus: number; base: number }[] | null>(null);202 const run = async () => {203 const variants = [{ label: fr ? "Marges basses (CG 5, FG 5, profit 5, cont. 3)" : "Low markups (GC 5, OH 5, profit 5, cont. 3)", params: { generalConditionsPct: 5, overheadPct: 5, profitPct: 5, contingencyPct: 3 } }, { label: fr ? "Marges hautes (CG 10, FG 10, profit 10, cont. 10)" : "High markups (GC 10, OH 10, profit 10, cont. 10)", params: { generalConditionsPct: 10, overheadPct: 10, profitPct: 10, contingencyPct: 10 } }, { label: fr ? "Taxes incluses" : "Taxes included", params: { applyGst: true, applyQst: true } }, ...(params.regionCode !== "QC-MTL" ? [{ label: "Montréal (QC-MTL)", params: { regionCode: "QC-MTL" } }] : []), ...(params.regionCode !== "QC-GAT" ? [{ label: "Gatineau (QC-GAT)", params: { regionCode: "QC-GAT" } }] : []), ...(params.regionCode !== "QC-QUE" ? [{ label: "Québec (QC-QUE)", params: { regionCode: "QC-QUE" } }] : [])];204 const [a, b] = await Promise.all([api<{ scenarios: typeof sc }>(`/estimates/${estId}/analyze`, { method: "POST", json: { kind: "scenarios", variants } }), api<{ sensitivity: typeof se }>(`/estimates/${estId}/analyze`, { method: "POST", json: { kind: "sensitivity" } })]);205 setSc(a.scenarios); setSe(b.sensitivity);206 };207 return (208 <div className="space-y-3">209 <Btn small onClick={() => void run()}>{fr ? "Scénarios et sensibilité" : "Scenarios and sensitivity"}</Btn>210 {sc && <div className="src-wrap"><table className="src-table"><thead><tr><th>{fr ? "Scénario" : "Scenario"}</th><th className="text-right">Total</th><th className="text-right">Δ</th></tr></thead><tbody>{sc.map((s) => <tr key={s.label}><td>{s.label}</td><td className="vp-mono text-right">{money(s.totals.total, lang)}</td><td className="vp-mono text-right">{s.deltaPct > 0 ? "+" : ""}{s.deltaPct} %</td></tr>)}</tbody></table></div>}211 {se && <div className="src-wrap"><table className="src-table"><thead><tr><th>{fr ? "Paramètre" : "Parameter"}</th><th className="text-right">−</th><th className="text-right">{fr ? "base" : "base"}</th><th className="text-right">+</th></tr></thead><tbody>{se.map((s) => <tr key={s.param}><td>{s.param}</td><td className="vp-mono text-right">{money(s.minus, lang)}</td><td className="vp-mono text-right">{money(s.base, lang)}</td><td className="vp-mono text-right">{money(s.plus, lang)}</td></tr>)}</tbody></table></div>}212 </div>213 );214}215216217/* ------------------------------------------------------------ assistance IA (Phase G) */218interface Suggestion { id: string; kind: string; model: string; promptVersion: string; output: unknown; evidence: unknown; status: string; createdAt: string; reviewNote: string | null; estimatedCostUsd: number | null }219function AiPanel({ estimateId, projectId, fr, canWrite, lines, onApplyMapping }: { estimateId: string; projectId: string; fr: boolean; canWrite: boolean; lines: EstimateLineInput[]; onApplyMapping: (targetType: string, targetId: string, code: string) => void }) {220 const [items, setItems] = useState<Suggestion[]>([]);221 const [busy, setBusy] = useState<string | null>(null);222 const [err, setErr] = useState<string | null>(null);223 const [anoms, setAnoms] = useState<{ lineId: string; description: string; reason: string }[] | null>(null);224 const load = useCallback(() => api<{ suggestions: Suggestion[] }>(`/ai?project=${projectId}`).then((r) => setItems(r.suggestions.filter((s) => s.kind !== "classify"))).catch(() => undefined), [projectId]);225 useEffect(() => { void load(); }, [load]);226 const ask = async (kind: string) => { setBusy(kind); setErr(null); try { const r = await api<{ suggestion: Suggestion | null; anomalies?: { lineId: string; description: string; reason: string }[] }>("/ai", { method: "POST", json: { kind, projectId, estimateId, lang: fr ? "fr" : "en" } }); if (r.anomalies) setAnoms(r.anomalies); await load(); } catch (e) { setErr((e as Error).message); } finally { setBusy(null); } };227 const review = async (id: string, status: "accepted" | "rejected") => { try { await api(`/ai/${id}`, { method: "POST", json: { status } }); await load(); } catch (e) { setErr((e as Error).message); } };228 const lineName = (id: string) => lines.find((l) => l.id === id)?.description ?? id.slice(0, 8);229 return (230 <Block num="04" title={fr ? "Assistance IA (suggestions à vérifier)" : "AI assistance (suggestions to review)"} aside={canWrite && <div className="flex flex-wrap gap-2">{[["assembly_mapping", fr ? "Proposer des assemblages" : "Suggest assemblies"], ["missing_scope", fr ? "Postes manquants ?" : "Missing scope?"], ["anomalies", fr ? "Anomalies" : "Anomalies"], ["explain", fr ? "Expliquer l'estimation" : "Explain the estimate"]].map(([k, l]) => <Btn key={k} small disabled={!!busy} onClick={() => void ask(k)}>{busy === k ? "…" : l}</Btn>)}</div>}>231 <p className="text-[12.5px] text-ink-2">{fr ? "Chaque suggestion est produite par un modèle de langage (modèle et version de prompt enregistrés), ne contient jamais de prix, cite ses éléments d'entrée et reste « en attente » tant qu'un humain ne l'a pas acceptée ou refusée. Les anomalies sont d'abord détectées par des règles déterministes ; l'IA ne fait que les commenter." : "Each suggestion comes from a language model (model and prompt version recorded), never contains a price, cites its inputs and stays “pending” until a human accepts or rejects it. Anomalies are first detected by deterministic rules; the AI only comments on them."}</p>232 {anoms && <div className="border-l-2 border-[var(--amber)] pl-3 text-[12.5px]">{anoms.length ? anoms.map((a) => <div key={a.lineId + a.reason}>⚠ <b>{a.description}</b> — {a.reason}</div>) : (fr ? "Aucune anomalie détectée par les règles." : "No anomaly detected by the rules.")}</div>}233 <Err msg={err} />234 {!items.length ? <p className="text-[12.5px] text-ink-3">—</p> : (235 <ul className="divide-y divide-[var(--line)]">{items.map((s) => {236 const o = s.output as { suggestions?: { targetType: string; targetId: string; assemblyCode: string; rationale: string; confidence: number }[]; missing?: { division: string; description: string; rationale: string; howToQuantify: string; importance: string }[]; explanation?: string; checks?: string[]; items?: { lineId: string; likelyCause: string; check: string }[] };237 return (<li key={s.id} className="py-3 text-[13px]">238 <div className="flex flex-wrap items-baseline justify-between gap-2"><span><span className="vp-mono text-[10px] uppercase text-accent">{s.kind}</span> · <span className="vp-mono text-[10px] text-ink-3">{s.model} · {s.promptVersion} · {dt(s.createdAt, fr ? "fr" : "en")}</span> <span className={`pill ${s.status === "accepted" ? "pill-conf-A" : s.status === "rejected" ? "pill-conf-D" : "pill-conf-C"}`}>{s.status}</span></span>239 {canWrite && s.status === "pending" && <span className="flex gap-1"><Btn small tone="accent" onClick={() => void review(s.id, "accepted")}>{fr ? "Accepter" : "Accept"}</Btn><Btn small onClick={() => void review(s.id, "rejected")}>{fr ? "Refuser" : "Reject"}</Btn></span>}</div>240 {o.suggestions && <ul className="mt-1 space-y-1">{o.suggestions.map((x, i) => <li key={i} className="flex flex-wrap items-baseline justify-between gap-2"><span>{x.targetType === "line" ? lineName(x.targetId) : (fr ? "mesure " : "measurement ") + x.targetId.slice(0, 8)} → <span className="vp-mono text-accent">{x.assemblyCode}</span> <span className="text-ink-2">— {x.rationale}</span> <span className="vp-mono text-[10px] text-ink-3">{Math.round(x.confidence * 100)} %</span></span>{canWrite && s.status === "accepted" && <Btn small onClick={() => onApplyMapping(x.targetType, x.targetId, x.assemblyCode)}>{fr ? "Appliquer" : "Apply"}</Btn>}</li>)}</ul>}241 {o.missing && <ul className="mt-1 list-disc space-y-0.5 pl-5">{o.missing.map((x, i) => <li key={i}><b>{x.division}</b> {x.description} <span className="text-ink-2">— {x.rationale}</span> <span className="vp-mono text-[10px] uppercase text-ink-3">{x.importance}</span><div className="text-[11.5px] text-ink-3">{x.howToQuantify}</div></li>)}</ul>}242 {o.explanation && <div className="mt-1 whitespace-pre-wrap text-ink-2">{o.explanation}{o.checks?.length ? <ul className="mt-1 list-disc pl-5">{o.checks.map((c, i) => <li key={i}>{c}</li>)}</ul> : null}</div>}243 {o.items && <ul className="mt-1 space-y-0.5">{o.items.map((x, i) => <li key={i}><b>{lineName(x.lineId)}</b> : {x.likelyCause} <span className="text-ink-2">→ {x.check}</span></li>)}</ul>}244 </li>);245 })}</ul>246 )}247 </Block>248 );249}250