SPB Git

Repository Public

MetreHome.tsx 19.5 KB 163 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | ACADEMIC RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project          : UQO Éval10 * File             : src/components/metre/MetreHome.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é : tableau de bord (coquille ERP) — KPI, actions rapides, projets (tous visibles : plateforme ouverte), gabarits, révisions, devoirs, activité.63"use client";64import { useCallback, useEffect, useState } from "react";65import Link from "next/link";66import { useRouter, useSearchParams } from "next/navigation";67import { useLang } from "@/components/LangContext";68import { api, Btn, dt, Err, Field, Input, money, num, Select, useMe } from "./ui";69import type { BuildingKind, Project } from "@/lib/metre/types";7071interface Dash { user: { id: string; displayName: string; role: string }; projects: (Project & { access: string; versions: number; lastVersionAt: string | null; ownerName: string; measurements: number; pages: number; mine: boolean })[]; versions: { id: string; projectId: string; number: number; label: string; total: number; createdAt: string; projectName: string }[]; catalogue: Record<string, unknown>; observations: { evidenceClass: string; n: number; last: string | null }[]; assignments: { id: string; course: string; title: string; dueAt: string | null; submissions: number; mySubmission: string | null }[] }72const KINDS: { k: BuildingKind; fr: string; en: string }[] = [{ k: "detached", fr: "Unifamiliale détachée", en: "Detached single-family" }, { k: "semi_detached", fr: "Jumelée", en: "Semi-detached" }, { k: "row", fr: "En rangée", en: "Row" }, { k: "plex", fr: "Plex", en: "Plex" }, { k: "condo", fr: "Copropriété", en: "Condo" }, { k: "chalet", fr: "Chalet", en: "Cottage" }, { k: "commercial", fr: "Commercial", en: "Commercial" }, { k: "other", fr: "Autre", en: "Other" }];7374export default function MetreHome() {75  const { lang } = useLang(); const fr = lang === "fr";76  const me = useMe(); const router = useRouter(); const sp = useSearchParams();77  const tab = sp.get("tab") ?? "accueil";78  const [d, setD] = useState<Dash | null>(null);79  const [err, setErr] = useState<string | null>(null);80  const [showNew, setShowNew] = useState(sp.get("nouveau") === "plan");81  const [filter, setFilter] = useState("");82  const load = useCallback(() => api<Dash>("/dashboard").then(setD).catch((e) => setErr(e.message)), []);83  useEffect(() => { if (me.user) void load(); }, [me.user, load]);84  if (me.loading || !me.user) return <div className="py-16 vp-mono text-[11px] uppercase tracking-[0.08em] text-ink-3">{fr ? "Ouverture de la session…" : "Opening session…"}</div>;85  const cat = d?.catalogue ?? {};86  const projects = (d?.projects ?? []).filter((p) => !filter || `${p.name} ${p.address ?? ""} ${p.municipality ?? ""} ${p.ownerName}`.toLowerCase().includes(filter.toLowerCase()));87  const templates = projects.filter((p) => p.isTemplate), others = projects.filter((p) => !p.isTemplate);88  const dup = async (id: string) => { try { const r = await api<{ project: Project }>(`/projects/${id}/duplicate`, { method: "POST", json: {} }); router.push(`/quantity-survey/projets/${r.project.id}`); } catch (e) { setErr((e as Error).message); } };89  const quick = async (kind: "blank" | "template" | "map") => {90    try { const r = await api<{ project: Project }>("/projects", { method: "POST", json: { name: fr ? "Nouveau projet" : "New project", valuationDate: new Date().toISOString().slice(0, 10) } }); router.push(`/quantity-survey/projets/${r.project.id}?tab=plans&nouveau=${kind}`); } catch (e) { setErr((e as Error).message); }91  };92  return (93    <div>94      <div className="mt-topbar"><div><p className="kicker">{fr ? "Quantity Survey · intelligence de la construction" : "Quantity Survey · construction intelligence"}</p><h1>{tab === "projets" ? (fr ? "Projets" : "Projects") : tab === "devoirs" ? (fr ? "Devoirs" : "Assignments") : (fr ? "Tableau de bord" : "Dashboard")}</h1></div>95        <div className="flex flex-wrap gap-2"><Btn tone="primary" onClick={() => setShowNew((v) => !v)}>{fr ? "+ Nouveau projet" : "+ New project"}</Btn><Link href="/quantity-survey/catalogue" className="btn btn-ghost">{fr ? "Catalogue" : "Catalogue"}</Link></div></div>96      <Err msg={err} />97      {showNew && <NewProject fr={fr} onCreated={(p) => router.push(`/quantity-survey/projets/${p.id}?tab=plans`)} onCancel={() => setShowNew(false)} />}98      {tab === "accueil" && (<div className="mt-grid">99        <div className="mt-kpis">100          <div className="mt-kpi"><div className="k">{fr ? "Projets" : "Projects"}</div><div className="v">{d ? others.length : "…"}</div><div className="s">{d ? `${others.filter((p) => p.mine).length} ${fr ? "à vous" : "yours"} · ${templates.length} ${fr ? "gabarits" : "templates"}` : ""}</div></div>101          <div className="mt-kpi"><div className="k">{fr ? "Révisions figées" : "Frozen revisions"}</div><div className="v">{d ? projects.reduce((s, p) => s + p.versions, 0) : "…"}</div><div className="s">{d?.versions[0] ? `${fr ? "dernière" : "last"} ${dt(d.versions[0].createdAt, lang)}` : ""}</div></div>102          <div className="mt-kpi"><div className="k">{fr ? "Mesures au registre" : "Ledger measurements"}</div><div className="v">{d ? projects.reduce((s, p) => s + p.measurements, 0) : "…"}</div><div className="s">{d ? `${projects.reduce((s, p) => s + p.pages, 0)} ${fr ? "pages de plan" : "plan pages"}` : ""}</div></div>103          <div className="mt-kpi"><div className="k">{fr ? "Prix observés (catalogue)" : "Observed prices (catalogue)"}</div><div className="v">{cat.available ? num(cat.observedPrices as number, lang, 0) : "—"}</div><div className="s">{cat.available ? `${cat.items} ${fr ? "articles" : "items"} · ${cat.assemblies} ${fr ? "assemblages" : "assemblies"} · ${String(cat.lastPrice ?? "")}` : ""}</div></div>104          <div className="mt-kpi"><div className="k">{fr ? "Main-d'œuvre APCHQ" : "APCHQ labour"}</div><div className="v">{cat.available ? num(cat.labourRates as number, lang, 0) : "—"}</div><div className="s">{cat.available ? `${fr ? "taux · en vigueur" : "rates · effective"} ${String(cat.labourLast ?? "")}` : ""}</div></div>105          <div className="mt-kpi"><div className="k">{fr ? "Observations SEAO / permis" : "SEAO / permit observations"}</div><div className="v">{d ? num(d.observations.reduce((s, o) => s + o.n, 0), lang, 0) : "…"}</div><div className="s">{d?.observations.map((o) => `${o.evidenceClass.replace(/_/g, " ")} ${o.n}`).join(" · ")}</div></div>106        </div>107        <div className="mt-card"><h2>{fr ? "Commencer" : "Start"}</h2><div className="pl-new">108          <button type="button" className="mt-action" onClick={() => void quick("blank")}><b>✎ {fr ? "Dessiner un plan" : "Draw a plan"}</b><span>{fr ? "Plan vierge à l'échelle : murs, portes, fenêtres, pièces, cotations — comme un architecte." : "Blank plan to scale: walls, doors, windows, rooms, dimensions — like an architect."}</span></button>109          <button type="button" className="mt-action" onClick={() => void quick("template")}><b>⌂ {fr ? "Partir d'un gabarit" : "Start from a template"}</b><span>{fr ? "Bungalow, cottage, garage déjà tracés." : "Bungalow, cottage, garage already drawn."}</span></button>110          <button type="button" className="mt-action" onClick={() => void quick("map")}><b>🛰 {fr ? "Plan de site satellite" : "Satellite site plan"}</b><span>{fr ? "Tracez lot et empreinte sur l'image géoréférencée d'une adresse." : "Trace lot and footprint on a georeferenced image of an address."}</span></button>111          <button type="button" className="mt-action" onClick={() => setShowNew(true)}><b>⇪ {fr ? "Importer des plans" : "Import plans"}</b><span>{fr ? "PDF, PNG, JPG ou DXF d'un projet existant, puis calibration." : "PDF, PNG, JPG or DXF of an existing project, then calibration."}</span></button>112        </div></div>113        <div className="mt-grid mt-grid-2">114          <div className="mt-card"><h2>{fr ? "Projets récents" : "Recent projects"} <Link href="/quantity-survey?tab=projets" className="text-ink-3 normal-case tracking-normal">{fr ? "tous →" : "all →"}</Link></h2><ProjectsTable rows={others.slice(0, 8)} fr={fr} lang={lang} onDup={dup} /></div>115          <div className="space-y-3">116            <div className="mt-card"><h2>{fr ? "Gabarits et cas d'étude" : "Templates and study cases"}</h2>{templates.map((p) => <div key={p.id} className="flex items-center justify-between gap-2 py-1.5 text-[13px] border-b border-[#eef1f3] last:border-0"><Link href={`/quantity-survey/projets/${p.id}`} className="font-semibold text-accent-deep hover:underline">{p.name}</Link><Btn small onClick={() => void dup(p.id)}>{fr ? "Utiliser" : "Use"}</Btn></div>)}{!templates.length && <p className="text-[12.5px] text-ink-3">—</p>}</div>117            <div className="mt-card"><h2>{fr ? "Dernières révisions" : "Latest revisions"}</h2>{d?.versions.slice(0, 6).map((v) => <div key={v.id} className="flex items-baseline justify-between gap-2 py-1 text-[12.5px]"><Link href={`/quantity-survey/projets/${v.projectId}?tab=rapports`} className="text-accent-deep hover:underline truncate">{v.projectName} · r{v.number}</Link><span className="vp-mono whitespace-nowrap">{money(v.total, lang)}</span></div>)}{!d?.versions.length && <p className="text-[12.5px] text-ink-3">—</p>}</div>118            <div className="mt-card"><h2>{fr ? "Devoirs" : "Assignments"}</h2>{d?.assignments.map((a) => <div key={a.id} className="py-1 text-[12.5px]"><b>{a.course}</b> · {a.title} <span className="vp-mono text-[10px] text-ink-3">{a.dueAt ? dt(a.dueAt, lang) : ""}{a.mySubmission ? ` · ${fr ? "remis" : "submitted"}` : ""}</span></div>)}{!d?.assignments.length && <p className="text-[12.5px] text-ink-3">{fr ? "Aucun devoir actif." : "No active assignment."}</p>}</div>119          </div>120        </div>121      </div>)}122      {tab === "projets" && (<div className="mt-card"><h2>{fr ? "Tous les projets (plateforme ouverte : chacun peut voir et modifier ; verrouillez les vôtres pour les protéger)" : "All projects (open platform: anyone can view and edit; lock yours to protect them)"}<Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder={fr ? "filtrer…" : "filter…"} className="!min-h-0 max-w-[240px] !py-1 text-[12px]" /></h2><ProjectsTable rows={[...templates, ...others]} fr={fr} lang={lang} onDup={dup} /></div>)}123      {tab === "devoirs" && (<div className="mt-card"><h2>{fr ? "Devoirs" : "Assignments"}</h2>{d?.assignments.length ? <table className="mt-table"><thead><tr><th>{fr ? "Cours" : "Course"}</th><th>{fr ? "Titre" : "Title"}</th><th>{fr ? "Échéance" : "Due"}</th><th>{fr ? "Remises" : "Submissions"}</th></tr></thead><tbody>{d.assignments.map((a) => <tr key={a.id}><td>{a.course}</td><td>{a.title}</td><td className="vp-mono">{a.dueAt ? dt(a.dueAt, lang) : "—"}</td><td className="vp-mono">{a.submissions}{a.mySubmission ? ` · ${fr ? "la vôtre est remise" : "yours submitted"}` : ""}</td></tr>)}</tbody></table> : <p className="text-[13px] text-ink-2">{fr ? "Aucun devoir actif. Les enseignant·es les créent dans Administration ; les remises se font depuis l'onglet Rapports d'un projet." : "No active assignment. Instructors create them in Administration; submissions are made from a project's Reports tab."}</p>}</div>)}124    </div>125  );126}127128function ProjectsTable({ rows, fr, lang, onDup }: { rows: Dash["projects"]; fr: boolean; lang: string; onDup: (id: string) => void }) {129  if (!rows.length) return <p className="text-[13px] text-ink-2">{fr ? "Aucun projet pour l'instant." : "No project yet."}</p>;130  return (131    <div className="overflow-x-auto"><table className="mt-table"><thead><tr><th>{fr ? "Projet" : "Project"}</th><th>{fr ? "Lieu" : "Place"}</th><th>{fr ? "Type" : "Type"}</th><th className="text-right">{fr ? "Plans" : "Plans"}</th><th className="text-right">{fr ? "Mesures" : "Measures"}</th><th className="text-right">{fr ? "Révisions" : "Revisions"}</th><th>{fr ? "Par" : "By"}</th><th>{fr ? "Modifié" : "Updated"}</th><th></th></tr></thead><tbody>132      {rows.map((p) => <tr key={p.id}><td><Link href={`/quantity-survey/projets/${p.id}`} className="font-semibold text-accent-deep hover:underline">{p.name}</Link> {p.isTemplate && <span className="pill pill-conf-B">{fr ? "gabarit" : "template"}</span>} {p.locked && <span title={fr ? "verrouillé" : "locked"}>🔒</span>} {p.mine && !p.isTemplate && <span className="vp-mono text-[9.5px] uppercase text-accent">{fr ? "à vous" : "yours"}</span>}</td><td className="text-[12.5px]">{[p.address, p.municipality].filter(Boolean).join(", ") || "—"}</td><td className="text-[12.5px]">{KINDS.find((k) => k.k === p.buildingKind)?.[fr ? "fr" : "en"] ?? p.buildingKind}</td><td className="vp-mono text-right">{p.pages}</td><td className="vp-mono text-right">{p.measurements}</td><td className="vp-mono text-right">{p.versions}</td><td className="text-[12px] text-ink-2">{p.ownerName}</td><td className="vp-mono text-[11px]">{dt(p.updatedAt, lang)}</td><td className="whitespace-nowrap"><Link href={`/quantity-survey/projets/${p.id}?tab=plans`} className="btn btn-ghost !min-h-0 !px-2.5 !py-1 text-[11.5px]">{fr ? "Ouvrir" : "Open"}</Link> <Btn small onClick={() => onDup(p.id)}>{fr ? "Dupliquer" : "Duplicate"}</Btn></td></tr>)}133    </tbody></table></div>134  );135}136137function NewProject({ fr, onCreated, onCancel }: { fr: boolean; onCreated: (p: Project) => void; onCancel: () => void }) {138  const [f, setF] = useState({ name: "", address: "", municipality: "", propertyId: "", valuationDate: new Date().toISOString().slice(0, 10), buildingKind: "detached", stories: 1, unitSystem: "metric", regionCode: "", notes: "" });139  const [err, setErr] = useState<string | null>(null); const [busy, setBusy] = useState(false); const [pre, setPre] = useState<string | null>(null);140  const set = (k: string, v: unknown) => setF((x) => ({ ...x, [k]: v }));141  const prefill = async () => { if (!f.propertyId) return; try { const p = await api<Record<string, unknown>>(`/prefill?id=${encodeURIComponent(f.propertyId)}`); setF((x) => ({ ...x, address: String(p.address ?? x.address), municipality: String(p.municipality ?? x.municipality), buildingKind: String(p.buildingKind ?? x.buildingKind), stories: Number(p.stories ?? x.stories), regionCode: String(p.regionCode ?? x.regionCode), name: x.name || String(p.address ?? "") })); setPre(`${fr ? "Préremplie depuis" : "Prefilled from"} ${p.source} — ${fr ? "aire d'étages" : "floor area"} ${p.grossFloorAreaM2 ?? "?"} m², ${fr ? "terrain au rôle" : "land (roll)"} ${p.landValue ?? "?"} $`); } catch (e) { setErr((e as Error).message); } };142  const save = async () => { setBusy(true); setErr(null); try { const r = await api<{ project: Project }>("/projects", { method: "POST", json: { ...f, regionCode: f.regionCode || null, propertyId: f.propertyId || null } }); onCreated(r.project); } catch (e) { setErr((e as Error).message); setBusy(false); } };143  return (144    <div className="mt-card mb-4">145      <h2>{fr ? "Nouveau projet" : "New project"}</h2>146      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">147        <Field label={fr ? "Identifiant MAMH (facultatif)" : "MAMH id (optional)"}><div className="flex gap-2"><Input value={f.propertyId} onChange={(e) => set("propertyId", e.target.value)} className="vp-mono" placeholder="id_provinc" /><Btn small onClick={() => void prefill()}>{fr ? "Préremplir" : "Prefill"}</Btn></div></Field>148        <Field label={fr ? "Nom du projet" : "Project name"}><Input value={f.name} onChange={(e) => set("name", e.target.value)} required /></Field>149        <Field label={fr ? "Date d'évaluation" : "Valuation date"}><Input type="date" value={f.valuationDate} onChange={(e) => set("valuationDate", e.target.value)} /></Field>150        <Field label={fr ? "Adresse" : "Address"}><Input value={f.address} onChange={(e) => set("address", e.target.value)} /></Field>151        <Field label={fr ? "Municipalité" : "Municipality"}><Input value={f.municipality} onChange={(e) => set("municipality", e.target.value)} /></Field>152        <Field label={fr ? "Type de bâtiment" : "Building type"}><Select value={f.buildingKind} onChange={(e) => set("buildingKind", e.target.value)}>{KINDS.map((k) => <option key={k.k} value={k.k}>{fr ? k.fr : k.en}</option>)}</Select></Field>153        <Field label={fr ? "Étages" : "Storeys"}><Input type="number" min={1} max={60} value={f.stories} onChange={(e) => set("stories", Number(e.target.value))} /></Field>154        <Field label={fr ? "Unités" : "Units"}><Select value={f.unitSystem} onChange={(e) => set("unitSystem", e.target.value)}><option value="metric">{fr ? "Métriques (m, m²)" : "Metric (m, m²)"}</option><option value="imperial">{fr ? "Impériales (pi, pi²)" : "Imperial (ft, sq ft)"}</option></Select></Field>155        <Field label={fr ? "Région de prix (code)" : "Price region (code)"} hint="QC-MTL, QC-QUE, QC-GAT, QC-LAV…"><Input value={f.regionCode} onChange={(e) => set("regionCode", e.target.value)} className="vp-mono" placeholder={fr ? "auto (municipalité)" : "auto (municipality)"} /></Field>156      </div>157      {pre && <p className="vp-mono mt-3 text-[10.5px] uppercase tracking-[0.05em] text-ink-2">{pre}</p>}158      <Err msg={err} />159      <div className="mt-4 flex gap-2"><Btn tone="primary" disabled={busy || !f.name} onClick={() => void save()}>{fr ? "Créer et ouvrir le Plan Studio" : "Create and open Plan Studio"}</Btn><Btn onClick={onCancel}>{fr ? "Annuler" : "Cancel"}</Btn></div>160    </div>161  );162}163
Files main
Menu

Theme