Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/components/cout/Workbench.tsx9 * Module : components10 * 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// Vrai-Prix — méthode du coût : l'ATELIER (/cout?property=… | ?mode=construction | ?estimate=…).43// Deux modes, neuf sections, recalcul déterministe à chaque changement (debounce), état local persistant,44// mode exercice (masquer / estimer soi-même / révéler). Aucun calcul métier ici : tout passe par POST /api/cost/estimate.45"use client";46import { useEffect, useRef, useState } from "react";47import Link from "next/link";48import { useLang } from "@/components/LangContext";49import type { AttributeSource, BuildingSpec, CostEstimate, CostInput, CostLocation, CostParams, DepreciationInput, LandInput } from "@/lib/cost/types";50import { defaultInput } from "@/lib/cost/estimate-defaults";51import { money, num } from "@/components/avendre/fmt";52import { PropertyPanel, BuildingFormPanel, type PrefillMeta } from "./BuildingForm";53import { AssemblyLinesPanel, CostTablePanel, LabourPanel } from "./CostPanels";54import { DepreciationPanel, LandPanel, ResultPanel, SourcesPanel } from "./ResultPanels";55import { Toggle } from "./fields";5657interface PrefillResponse extends PrefillMeta { input: CostInput; otherReadings: CostEstimate["otherReadings"]; recent: { id: string; createdAt: string; rcn: number; value: number; letter: string }[] }5859const SECTIONS = ["01", "02", "03", "04", "05", "06", "07", "08", "09"];60const NAMES_FR = ["Propriété", "Caractéristiques", "Coût à neuf", "Assemblages", "Main-d'œuvre", "Dépréciation", "Terrain", "Résultat", "Sources"];61const NAMES_EN = ["Property", "Characteristics", "Cost new", "Assemblies", "Labour", "Depreciation", "Land", "Result", "Sources"];6263export default function Workbench({ propertyId, estimateId, locations }: { propertyId: string | null; estimateId: string | null; locations: CostLocation[] }) {64 const { lang } = useLang();65 const fr = lang === "fr";66 const storageKey = `vrai-prix-cout:${propertyId ?? "construction"}`;67 const [input, setInput] = useState<CostInput | null>(null);68 const [meta, setMeta] = useState<PrefillMeta | null>(null);69 const [est, setEst] = useState<CostEstimate | null>(null);70 const [computedKey, setComputedKey] = useState<string>("");71 const [error, setError] = useState<string | null>(null);72 const [saving, setSaving] = useState(false);73 const [savedId, setSavedId] = useState<string | null>(estimateId);74 const [exercise, setExercise] = useState(false);75 const [hideResult, setHideResult] = useState(false);76 const [hideCosts, setHideCosts] = useState(false);77 const [answer, setAnswer] = useState("");78 const [revealed, setRevealed] = useState(false);79 const [restored, setRestored] = useState(false);80 const timer = useRef<ReturnType<typeof setTimeout> | null>(null);8182 /* ---------------------------------------------------- chargement initial */83 useEffect(() => {84 let cancelled = false;85 (async () => {86 try {87 if (estimateId) {88 const r = await fetch(`/api/cost/estimate/${encodeURIComponent(estimateId)}`);89 if (!r.ok) throw new Error((await r.json()).error ?? r.statusText);90 const e = (await r.json()) as CostEstimate;91 if (cancelled) return;92 setEst(e); setInput(e.input); setComputedKey(JSON.stringify(e.input));93 setMeta({ unit: null, missing: [], location: e.location, locationMethod: null });94 if (e.input.propertyId) {95 const p = await fetch(`/api/cost/property?id=${encodeURIComponent(e.input.propertyId)}&readings=0`);96 if (p.ok && !cancelled) { const d = (await p.json()) as PrefillResponse; setMeta({ unit: d.unit, missing: d.missing, location: d.location, locationMethod: d.locationMethod }); }97 }98 return;99 }100 let saved: CostInput | null = null;101 try { const raw = window.localStorage.getItem(storageKey); if (raw) saved = JSON.parse(raw) as CostInput; } catch { /* ignore */ }102 if (propertyId) {103 const r = await fetch(`/api/cost/property?id=${encodeURIComponent(propertyId)}`);104 if (!r.ok) throw new Error((await r.json()).error ?? r.statusText);105 const d = (await r.json()) as PrefillResponse;106 if (cancelled) return;107 setMeta({ unit: d.unit, missing: d.missing, location: d.location, locationMethod: d.locationMethod });108 const use = saved && saved.propertyId === propertyId && saved.roll?.totalValue === d.input.roll?.totalValue ? { ...saved, roll: d.input.roll, lat: d.input.lat, lng: d.input.lng } : d.input;109 setInput(use); setRestored(!!saved && use === saved);110 } else {111 const base = saved && saved.mode === "construction" ? saved : defaultInput();112 if (cancelled) return;113 setInput(base); setRestored(!!saved && saved.mode === "construction");114 setMeta({ unit: null, missing: [], location: null, locationMethod: null });115 }116 } catch (e) { if (!cancelled) setError(e instanceof Error ? e.message : String(e)); }117 })();118 return () => { cancelled = true; };119 }, [propertyId, estimateId, storageKey]);120121 /* ---------------------------------------------------- recalcul (debounce) */122 const key = input ? JSON.stringify(input) : "";123 useEffect(() => {124 if (!input || key === computedKey) return;125 if (timer.current) clearTimeout(timer.current);126 timer.current = setTimeout(async () => {127 try {128 const r = await fetch("/api/cost/estimate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ input, save: false }) });129 const d = await r.json();130 if (!r.ok) throw new Error(d.error ?? r.statusText);131 setEst(d as CostEstimate); setComputedKey(key); setError(null);132 try { window.localStorage.setItem(storageKey, key); } catch { /* quota */ }133 } catch (e) { setError(e instanceof Error ? e.message : String(e)); }134 }, 400);135 return () => { if (timer.current) clearTimeout(timer.current); };136 }, [key, computedKey, input, storageKey]);137 const pending = !!input && key !== computedKey;138139 /* ----------------------------------------------------------- mutateurs */140 const patch = (p: Partial<CostInput>) => setInput((i) => (i ? { ...i, ...p } : i));141 const patchB = (p: Partial<BuildingSpec>) => setInput((i) => (i ? { ...i, building: { ...i.building, ...p } } : i));142 const patchP = (p: Partial<CostParams>) => setInput((i) => (i ? { ...i, params: { ...i.params, ...p } } : i));143 const patchD = (p: Partial<DepreciationInput>) => setInput((i) => (i ? { ...i, depreciation: { ...i.depreciation, ...p } } : i));144 const patchL = (p: Partial<LandInput>) => setInput((i) => (i ? { ...i, land: { ...i.land, ...p } } : i));145 const setSrc = (k: string, s: AttributeSource) => setInput((i) => (i ? { ...i, attributeSources: { ...i.attributeSources, [k]: s } } : i));146 const setQty = (code: string, q: number | null) => setInput((i) => { if (!i) return i; const o = { ...i.quantityOverrides }; if (q == null) delete o[code]; else o[code] = q; return { ...i, quantityOverrides: o }; });147 const toggleExclude = (code: string) => setInput((i) => (i ? { ...i, excludedAssemblies: i.excludedAssemblies.includes(code) ? i.excludedAssemblies.filter((c) => c !== code) : [...i.excludedAssemblies, code] } : i));148149 const save = async () => {150 if (!input) return;151 setSaving(true);152 try {153 const r = await fetch("/api/cost/estimate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ input, save: true }) });154 const d = await r.json();155 if (!r.ok) throw new Error(d.error ?? r.statusText);156 setEst(d as CostEstimate); setComputedKey(key); setSavedId((d as CostEstimate).id);157 const url = new URL(window.location.href); url.searchParams.set("estimate", (d as CostEstimate).id); window.history.replaceState(null, "", url.toString());158 } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setSaving(false); }159 };160 const refreshPrices = () => { patch({ priceDate: null }); setComputedKey(""); };161 const reset = () => { try { window.localStorage.removeItem(storageKey); } catch { /* ignore */ } window.location.href = propertyId ? `/cout?property=${encodeURIComponent(propertyId)}` : "/cout?mode=construction"; };162163 if (error && !input) return <div className="py-16"><p className="vp-display text-[22px] font-bold">{fr ? "Impossible de charger l'atelier" : "Cannot load the workshop"}</p><p className="mt-2 text-ink-2">{error}</p><Link href="/cout" className="btn btn-ghost mt-4">← {fr ? "Retour" : "Back"}</Link></div>;164 if (!input) return <div className="py-16 vp-mono text-[11px] uppercase tracking-[0.08em] text-ink-3">{fr ? "Chargement de la propriété…" : "Loading property…"}</div>;165166 const hide = exercise && hideResult;167 const hideC = exercise && hideCosts;168 const structure = est?.categories.find((c) => c.category === "structure");169 const structureAnswer = (170 <div className="border border-[var(--line-strong)] bg-surface p-4">171 <p className="kicker">{fr ? "Exercice" : "Exercise"}</p>172 <p className="vp-display mt-1 text-[16px] font-bold">{fr ? "Calculez le coût direct de la structure." : "Compute the direct cost of the structure."}</p>173 <p className="mt-1 text-[12.5px] text-ink-2">{fr ? "À partir des lignes de la catégorie Structure (section 04) : Σ quantité × coût unitaire, puis × facteur régional. Saisissez votre réponse, puis comparez." : "From the Structure lines (section 04): Σ quantity × unit cost, then × regional factor. Enter your answer, then compare."}</p>174 <div className="mt-2 flex flex-wrap items-center gap-3">175 <input value={answer} onChange={(e) => setAnswer(e.target.value)} inputMode="numeric" placeholder="$" className="vp-input vp-mono max-w-[200px] text-[14px]" />176 <button type="button" className="btn btn-primary !min-h-0 !py-2" onClick={() => setRevealed(true)}>{fr ? "Voir la correction" : "See the correction"}</button>177 {revealed && <button type="button" className="btn btn-ghost !min-h-0 !py-2" onClick={() => { setRevealed(false); setAnswer(""); }}>{fr ? "Recommencer" : "Try again"}</button>}178 </div>179 {revealed && structure && est && (180 <div className="mt-3">181 <p className="vp-mono text-[12px]">{fr ? "Réponse du moteur" : "Engine answer"} : <b>{money(structure.adjusted, lang)}</b>{answer && Number(answer.replace(/[^\d.]/g, "")) > 0 ? ` · ${fr ? "votre réponse" : "your answer"} ${money(Number(answer.replace(/[^\d.]/g, "")), lang)} (${fr ? "écart" : "gap"} ${num(((Number(answer.replace(/[^\d.]/g, "")) / structure.adjusted) - 1) * 100, lang, 1)} %)` : ""}</p>182 <div className="src-wrap mt-2"><table className="src-table"><thead><tr><th>{fr ? "Assemblage" : "Assembly"}</th><th className="text-right">{fr ? "Quantité" : "Quantity"}</th><th className="text-right">×</th><th className="text-right">{fr ? "Coût unitaire" : "Unit cost"}</th><th className="text-right">=</th><th className="text-right">{fr ? "Direct" : "Direct"}</th></tr></thead><tbody>183 {est.lines.filter((l) => l.category === "structure").map((l) => (<tr key={l.assemblyCode}><td>{fr ? l.nameFr : l.nameEn}</td><td className="vp-mono text-right">{num(l.quantity, lang, 1)} {l.unit}</td><td className="text-right">×</td><td className="vp-mono text-right">{num(l.unitCost, lang, 2)} $</td><td className="text-right">=</td><td className="vp-mono text-right">{money(l.direct, lang)}</td></tr>))}184 <tr className="bg-surface-2 font-bold"><td colSpan={5}>{fr ? "Direct × facteur régional" : "Direct × regional factor"} (M {est.location.materialFactor} · MO {est.location.labourFactor} · É {est.location.equipmentFactor})</td><td className="vp-mono text-right">{money(structure.adjusted, lang)}</td></tr>185 </tbody></table></div>186 </div>187 )}188 </div>189 );190191 return (192 <div className="py-8">193 {/* masthead */}194 <section className="rise">195 <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 border-b-2 border-ink pb-2.5">196 <nav className="vp-mono flex flex-wrap items-center gap-2 text-[10.5px] uppercase tracking-[0.08em] text-ink-3">197 <Link href="/" className="text-ink-2 hover:text-accent-deep">Vrai Prix</Link><span aria-hidden="true">/</span>198 <Link href="/cout" className="text-ink-2 hover:text-accent-deep">{fr ? "Coût" : "Cost"}</Link><span aria-hidden="true">/</span>199 <span>{input.mode === "property" ? (fr ? "Atelier — propriété" : "Workshop — property") : (fr ? "Atelier — construction" : "Workshop — construction")}</span>200 </nav>201 <span className="vp-mono text-[10px] uppercase tracking-[0.08em] text-ink-3">{pending ? (fr ? "recalcul…" : "recomputing…") : est ? `${fr ? "calculé en" : "computed"} ${est.priceDate}` : ""}</span>202 </div>203 <div className="mt-5 grid gap-x-10 gap-y-4 lg:grid-cols-[1.5fr_1fr]">204 <div>205 <span className="kicker">{fr ? "Méthode du coût — atelier" : "Cost approach — workshop"}</span>206 <h1 className="vp-display mt-2 text-[clamp(24px,3.6vw,38px)] font-bold uppercase leading-[1.02] tracking-[-0.03em]">{input.address ?? (fr ? "Bâtiment hypothétique" : "Hypothetical building")}</h1>207 <p className="mt-1 text-[14px] text-ink-2">{input.municipality ?? (fr ? "Sans adresse — décrivez le bâtiment" : "No address — describe the building")}{est ? ` · ${fr ? est.location.nameFr : est.location.nameEn}` : ""}</p>208 </div>209 <aside className="flex flex-col gap-2 lg:items-end">210 <div className="flex flex-wrap gap-2">211 <button type="button" aria-pressed={exercise} onClick={() => setExercise((v) => !v)} className={`btn !min-h-0 !px-3 !py-1.5 text-[12px] ${exercise ? "btn-primary" : "btn-ghost"}`}>✎ {fr ? "Mode exercice" : "Exercise mode"}</button>212 <button type="button" onClick={reset} className="btn btn-ghost !min-h-0 !px-3 !py-1.5 text-[12px]">{fr ? "Réinitialiser" : "Reset"}</button>213 </div>214 {exercise && (215 <div className="flex flex-wrap gap-x-4 gap-y-1">216 <Toggle checked={hideResult} onChange={setHideResult} label={fr ? "Masquer le résultat final" : "Hide final result"} />217 <Toggle checked={hideCosts} onChange={setHideCosts} label={fr ? "Masquer les coûts des lignes" : "Hide line costs"} />218 </div>219 )}220 {restored && <p className="vp-mono text-[10px] uppercase tracking-[0.05em] text-ink-3">{fr ? "état restauré depuis cet appareil" : "state restored from this device"}</p>}221 </aside>222 </div>223 {/* sommaire des sections */}224 <ol className="vp-mono mt-5 flex flex-wrap gap-x-4 gap-y-1.5 border-y border-[var(--line)] py-2.5 text-[10px] uppercase tracking-[0.08em]">225 {SECTIONS.map((s, i) => (<li key={s}><a href={`#s${s}`} className="text-ink-2 hover:text-accent"><b className="text-accent">{s}</b> {fr ? NAMES_FR[i] : NAMES_EN[i]}</a></li>))}226 </ol>227 {error && <p className="mt-3 border-l-2 border-[var(--danger)] pl-3 text-[13px] text-[var(--danger)]">{error}</p>}228 </section>229230 <div className="mt-8 space-y-12">231 <PropertyPanel input={input} meta={meta} fr={fr} locations={locations} patch={patch} setSrc={setSrc} />232 <BuildingFormPanel b={input.building} src={input.attributeSources} fr={fr} patchB={patchB} setSrc={setSrc} />233 <CostTablePanel est={est} params={input.params} fr={fr} patchP={patchP} hide={hide || hideC} />234 <AssemblyLinesPanel est={est} input={input} fr={fr} setQty={setQty} toggleExclude={toggleExclude} hide={hideC} />235 <LabourPanel est={est} fr={fr} hide={hideC} />236 <DepreciationPanel est={est} dep={input.depreciation} fr={fr} patchD={patchD} hide={hide} />237 <LandPanel input={input} fr={fr} patchL={patchL} />238 <ResultPanel est={est} fr={fr} hide={hide} exercise={exercise} onSave={save} saving={saving} savedId={savedId} onRefreshPrices={refreshPrices} structureAnswer={structureAnswer} />239 <SourcesPanel est={est} fr={fr} />240 </div>241 <p className="vp-mono mt-10 border-l-2 border-accent pl-4 text-[11px] uppercase leading-relaxed tracking-[0.05em] text-ink-2">242 {fr ? "Estimation indicative — les coûts présentés sont des estimations statistiques et ne constituent ni une soumission d'entrepreneur ni une évaluation professionnelle certifiée (OEAQ)." : "Building analysis — the costs shown are estimates and constitute neither a contractor's bid nor a certified professional appraisal (OEAQ)."}243 </p>244 </div>245 );246}247