Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/components/charts/charts.tsx9 * Module : components10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-08-1712 * Last Modified : 2026-08-2313 *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// Auteur : Simon-Pierre Boucher — contact@spboucher.ai43// Kit de graphiques SVG du tableau de bord statistique44// (zéro dépendance, React 18+). Style : jetons de src/styles/tokens.css45// (bordures encre, accent de la plateforme via var(--accent)).46// v2 — composants : KpiCard (+sparkline), PeriodSelector, LineChart (ligne/47// aire, infobulle + légende cliquable + comparaison N-1), MultiLineChart48// (≤4 séries, pointillés distincts = jamais la couleur seule), VBarChart49// (barres verticales / histogrammes), StackedBarChart, BarChart (horizontal,50// deltas), Donut, GaugeCard, CalendarHeatmap, HourHeatmap (7×24),51// StatSummary (min/max/moy/méd/σ), DataTable (tri/recherche/pagination),52// RecordCard, PdfButton (menu de rapports), EmptyBlock, Fraicheur.53import { useEffect, useMemo, useRef, useState } from "react";5455/* ---------- types (contrat SPEC.md v2) ---------- */56export type Kpi = {57 id: string; label: string; value: number | string; unit?: string;58 delta_pct?: number | null; direction?: "up" | "down";59 spark?: Point[]; help?: string;60};61export type Point = { t: string; v: number };62export type Serie = {63 id: string; title: string; unit?: string;64 kind?: "line" | "bar" | "area";65 points: Point[]; compare?: Point[];66};67export type MultiSerie = {68 id: string; title: string; unit?: string;69 series: { label: string; points: Point[] }[]; // ≤ 4 séries70};71export type StackedSerie = {72 id: string; title: string; unit?: string;73 keys: string[]; points: { t: string; values: number[] }[];74};75export type BreakItem = { label: string; value: number; delta_pct?: number | null };76export type Distribution = { id: string; title: string; unit?: string; bins: { label: string; value: number }[] };77export type Gauge = { id: string; label: string; value: number; max: number; unit?: string; help?: string };78export type HourCell = { dow: number; hour: number; value: number }; // dow 0=lun … 6=dim79export type TableSpec = { id: string; title: string; columns: string[]; rows: (string | number)[][] };80export type RecordFact = { label: string; value: string; date?: string };8182export const PERIODS: { id: string; label: string }[] = [83 { id: "auj", label: "Aujourd'hui" },84 { id: "7j", label: "7 jours" },85 { id: "30j", label: "30 jours" },86 { id: "3m", label: "3 mois" },87 { id: "6m", label: "6 mois" },88 { id: "12m", label: "12 mois" },89 { id: "annee", label: "Année en cours" },90 { id: "tout", label: "Tout" },91];9293export const REPORT_MODES: { id: string; label: string; desc: string }[] = [94 { id: "complet", label: "Rapport complet", desc: "Toutes les sections — KPI, tendances, répartitions, tableaux, records" },95 { id: "synthese", label: "Synthèse exécutive", desc: "2 pages — indicateurs clés et faits marquants" },96 { id: "tendances", label: "Tendances & évolution", desc: "Courbes, comparaisons N-1 et statistiques de séries" },97 { id: "repartitions", label: "Répartitions & géographie", desc: "Catégories, distributions, régions et activité" },98 { id: "donnees", label: "Données détaillées", desc: "Tous les tableaux, en version longue" },99];100101export const fmtInt = (n: number) => n.toLocaleString("fr-CA");102export const fmtNum = (n: number) =>103 Number.isInteger(n) ? fmtInt(n) : n.toLocaleString("fr-CA", { maximumFractionDigits: 2 });104const fmtPct = (n: number) => `${n >= 0 ? "+" : ""}${fmtNum(n)} %`;105106/* Styles des séries multiples : couleur + motif de trait (l'identité n'est107 jamais portée par la couleur seule — règle d'accessibilité). */108const MULTI_STYLES = [109 { stroke: "var(--accent)", dash: undefined, width: 2.4 },110 { stroke: "var(--ink)", dash: undefined, width: 1.6 },111 { stroke: "var(--accent-deep, var(--accent))", dash: "6 3", width: 2 },112 { stroke: "var(--ink-3)", dash: "2 3", width: 2 },113];114115/* ---------- KPI (+ sparkline) ---------- */116export function KpiCard({ k }: { k: Kpi }) {117 const up = (k.direction ?? ((k.delta_pct ?? 0) >= 0 ? "up" : "down")) === "up";118 const sp = (k.spark ?? []).filter((p) => typeof p.v === "number");119 const spark = useMemo(() => {120 if (sp.length < 2) return null;121 const w = 120, h = 30;122 const vmax = Math.max(...sp.map((p) => p.v));123 const vmin = Math.min(...sp.map((p) => p.v));124 const rng = vmax - vmin || 1;125 const X = (i: number) => (w * i) / (sp.length - 1);126 const Y = (v: number) => 2 + (h - 4) * (1 - (v - vmin) / rng);127 const d = sp.map((p, i) => `${i ? "L" : "M"}${X(i).toFixed(1)},${Y(p.v).toFixed(1)}`).join("");128 return { w, h, d, area: `${d}L${w},${h}L0,${h}Z` };129 }, [k.spark]);130 return (131 <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={k.help}>132 <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px,2.4vw,30px)", letterSpacing: "-0.02em" }}>133 {typeof k.value === "number" ? fmtNum(k.value) : k.value}134 {k.unit ? <span style={{ fontSize: "0.6em", color: "var(--ink-2)" }}> {k.unit}</span> : null}135 </p>136 <p className="klabel" style={{ margin: "6px 0 0" }}>{k.label}</p>137 <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 8 }}>138 {k.delta_pct !== undefined && k.delta_pct !== null ? (139 <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}>140 {up ? "▲" : "▼"} {fmtPct(k.delta_pct)} <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span>141 </p>142 ) : <span />}143 {spark && (144 <svg viewBox={`0 0 ${spark.w} ${spark.h}`} style={{ width: 96, height: 24, flex: "none" }} aria-hidden="true">145 <path d={spark.area} fill="var(--accent)" opacity={0.14} />146 <path d={spark.d} fill="none" stroke="var(--accent)" strokeWidth={1.8} />147 </svg>148 )}149 </div>150 </article>151 );152}153154/* ---------- Sélecteur de période ---------- */155export function PeriodSelector({156 value, onChange, custom, onCustom,157}: {158 value: string; onChange: (p: string) => void;159 custom?: { from: string; to: string }; onCustom?: (from: string, to: string) => void;160}) {161 return (162 <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>163 {PERIODS.map((p) => (164 <button key={p.id} type="button" onClick={() => onChange(p.id)}165 className="chip" aria-pressed={value === p.id}166 style={{ cursor: "pointer", minHeight: 44, background: value === p.id ? "var(--accent)" : "var(--surface)", color: value === p.id ? "var(--on-accent)" : "var(--ink)" }}>167 {p.label}168 </button>169 ))}170 {onCustom && (171 <span style={{ display: "inline-flex", gap: 6, alignItems: "center" }}>172 <input className="input" type="date" style={{ width: 150 }} value={custom?.from ?? ""} aria-label="Du"173 onChange={(e) => onCustom(e.target.value, custom?.to ?? "")} />174 <span className="klabel">au</span>175 <input className="input" type="date" style={{ width: 150 }} value={custom?.to ?? ""} aria-label="Au"176 onChange={(e) => onCustom(custom?.from ?? "", e.target.value)} />177 </span>178 )}179 </div>180 );181}182183/* ---------- Courbe / aire ---------- */184export function LineChart({ serie, height = 240 }: { serie: Serie; height?: number }) {185 const [hide, setHide] = useState<{ cur: boolean; cmp: boolean }>({ cur: false, cmp: false });186 const [hover, setHover] = useState<number | null>(null);187 const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;188 const pts = serie.points ?? [];189 if (serie.kind === "bar") return <VBarChart serie={serie} height={height} />;190 if (pts.length < 2) return <EmptyBlock title={serie.title} />;191 const all = [...(hide.cur ? [] : pts), ...(!hide.cmp && serie.compare ? serie.compare : [])];192 const vmax = Math.max(...all.map((p) => p.v), 1);193 const vmin = Math.min(0, ...all.map((p) => p.v));194 const X = (i: number, n: number) => PL + ((W - PL - PR) * i) / (n - 1);195 const Y = (v: number) => PT + (H - PT - PB) * (1 - (v - vmin) / (vmax - vmin || 1));196 const path = (s: Point[]) => s.map((p, i) => `${i ? "L" : "M"}${X(i, s.length)},${Y(p.v)}`).join("");197 const hi = hover !== null ? Math.min(pts.length - 1, Math.max(0, hover)) : null;198 return (199 <figure className="card" style={{ margin: 0, padding: 16 }}>200 <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>201 <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{serie.title}</b>202 <span style={{ display: "flex", gap: 10 }}>203 <LegendChip label="Période courante" color="var(--accent)" off={hide.cur} onClick={() => setHide((h) => ({ ...h, cur: !h.cur }))} />204 {serie.compare && <LegendChip label="Période comparée" color="var(--ink-3)" dashed off={hide.cmp} onClick={() => setHide((h) => ({ ...h, cmp: !h.cmp }))} />}205 </span>206 </figcaption>207 <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10, touchAction: "pan-y" }} role="img" aria-label={serie.title}208 onMouseMove={(e) => {209 const r = (e.currentTarget as SVGSVGElement).getBoundingClientRect();210 const fx = ((e.clientX - r.left) / r.width) * W;211 setHover(Math.round(((fx - PL) / (W - PL - PR)) * (pts.length - 1)));212 }}213 onMouseLeave={() => setHover(null)}>214 {[0, 1, 2, 3, 4].map((g) => {215 const y = PT + ((H - PT - PB) * g) / 4;216 const v = vmax - ((vmax - vmin) * g) / 4;217 return (218 <g key={g}>219 <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />220 <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>221 </g>222 );223 })}224 {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => (225 <text key={i} x={X(i, pts.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>226 ))}227 {serie.kind === "area" && !hide.cur && (228 <path d={`${path(pts)}L${X(pts.length - 1, pts.length)},${Y(0)}L${X(0, pts.length)},${Y(0)}Z`} fill="var(--accent)" opacity={0.13} />229 )}230 {!hide.cmp && serie.compare && serie.compare.length > 1 && (231 <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" />232 )}233 {!hide.cur && <path d={path(pts)} fill="none" stroke="var(--accent)" strokeWidth={2.4} />}234 {hi !== null && (235 <g>236 <line x1={X(hi, pts.length)} x2={X(hi, pts.length)} y1={PT} y2={H - PB} stroke="var(--ink)" strokeWidth={1} strokeDasharray="2 3" />237 <circle cx={X(hi, pts.length)} cy={Y(pts[hi].v)} r={4} fill="var(--accent)" stroke="var(--ink)" strokeWidth={1.5} />238 </g>239 )}240 </svg>241 {hi !== null && (242 <p className="chip" style={{ marginTop: 8 }}>243 {pts[hi].t} — <b>{fmtNum(pts[hi].v)}{serie.unit ? ` ${serie.unit}` : ""}</b>244 {serie.compare?.[hi] && !hide.cmp ? <span style={{ color: "var(--ink-3)" }}> · N-1 : {fmtNum(serie.compare[hi].v)}</span> : null}245 </p>246 )}247 </figure>248 );249}250251function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off?: boolean; dashed?: boolean; onClick?: () => void }) {252 return (253 <button type="button" onClick={onClick} aria-pressed={!off} disabled={!onClick}254 style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: onClick ? "pointer" : "default", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}>255 <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} />256 {label}257 </button>258 );259}260261/* ---------- Multi-courbes (≤ 4 séries, motifs distincts) ---------- */262export function MultiLineChart({ ms, height = 260 }: { ms: MultiSerie; height?: number }) {263 const series = (ms.series ?? []).filter((s) => (s.points ?? []).length > 1).slice(0, 4);264 const [off, setOff] = useState<Record<string, boolean>>({});265 const [hover, setHover] = useState<number | null>(null);266 if (!series.length) return <EmptyBlock title={ms.title} />;267 const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;268 const n = Math.max(...series.map((s) => s.points.length));269 const shown = series.filter((s) => !off[s.label]);270 const all = shown.flatMap((s) => s.points.map((p) => p.v));271 const vmax = Math.max(...(all.length ? all : [1]), 1);272 const vmin = Math.min(0, ...(all.length ? all : [0]));273 const X = (i: number, len: number) => PL + ((W - PL - PR) * i) / (len - 1);274 const Y = (v: number) => PT + (H - PT - PB) * (1 - (v - vmin) / (vmax - vmin || 1));275 const ref = series[0].points;276 const hi = hover !== null ? Math.min(n - 1, Math.max(0, hover)) : null;277 return (278 <figure className="card" style={{ margin: 0, padding: 16 }}>279 <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>280 <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{ms.title}</b>281 <span style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>282 {series.map((s, i) => (283 <LegendChip key={s.label} label={s.label} color={MULTI_STYLES[i].stroke}284 dashed={!!MULTI_STYLES[i].dash} off={!!off[s.label]}285 onClick={() => setOff((o) => ({ ...o, [s.label]: !o[s.label] }))} />286 ))}287 </span>288 </figcaption>289 <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10, touchAction: "pan-y" }} role="img" aria-label={ms.title}290 onMouseMove={(e) => {291 const r = (e.currentTarget as SVGSVGElement).getBoundingClientRect();292 const fx = ((e.clientX - r.left) / r.width) * W;293 setHover(Math.round(((fx - PL) / (W - PL - PR)) * (n - 1)));294 }}295 onMouseLeave={() => setHover(null)}>296 {[0, 1, 2, 3, 4].map((g) => {297 const y = PT + ((H - PT - PB) * g) / 4;298 const v = vmax - ((vmax - vmin) * g) / 4;299 return (300 <g key={g}>301 <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />302 <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>303 </g>304 );305 })}306 {[0, Math.floor(ref.length / 2), ref.length - 1].map((i) => (307 <text key={i} x={X(i, ref.length)} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{ref[i]?.t}</text>308 ))}309 {series.map((s, i) => off[s.label] ? null : (310 <path key={s.label}311 d={s.points.map((p, j) => `${j ? "L" : "M"}${X(j, s.points.length)},${Y(p.v)}`).join("")}312 fill="none" stroke={MULTI_STYLES[i].stroke} strokeWidth={MULTI_STYLES[i].width}313 strokeDasharray={MULTI_STYLES[i].dash} />314 ))}315 {hi !== null && (316 <line x1={X(hi, n)} x2={X(hi, n)} y1={PT} y2={H - PB} stroke="var(--ink)" strokeWidth={1} strokeDasharray="2 3" />317 )}318 </svg>319 {hi !== null && (320 <p className="chip" style={{ marginTop: 8, display: "inline-flex", gap: 12, flexWrap: "wrap" }}>321 <b>{ref[hi]?.t}</b>322 {shown.map((s) => (323 <span key={s.label}>{s.label} : <b>{s.points[hi] ? fmtNum(s.points[hi].v) : "—"}{ms.unit ? ` ${ms.unit}` : ""}</b></span>324 ))}325 </p>326 )}327 </figure>328 );329}330331/* ---------- Barres verticales (volumes quotidiens, histogrammes) ---------- */332export function VBarChart({ serie, height = 240 }: { serie: Serie; height?: number }) {333 const [hover, setHover] = useState<number | null>(null);334 const pts = serie.points ?? [];335 if (!pts.length) return <EmptyBlock title={serie.title} />;336 const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;337 const vmax = Math.max(...pts.map((p) => p.v), 1);338 const bw = Math.max(2, (W - PL - PR) / pts.length - 2);339 return (340 <figure className="card" style={{ margin: 0, padding: 16 }}>341 <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{serie.title}</b></figcaption>342 <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10 }} role="img" aria-label={serie.title}343 onMouseLeave={() => setHover(null)}>344 {[0, 1, 2, 3, 4].map((g) => {345 const y = PT + ((H - PT - PB) * g) / 4;346 const v = vmax - (vmax * g) / 4;347 return (348 <g key={g}>349 <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />350 <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>351 </g>352 );353 })}354 {pts.map((p, i) => {355 const x = PL + ((W - PL - PR) * i) / pts.length;356 const h = (H - PT - PB) * (p.v / vmax);357 return (358 <rect key={i} x={x + 1} y={H - PB - h} width={bw} height={Math.max(h, p.v > 0 ? 1.5 : 0)} rx={2}359 fill="var(--accent)" opacity={hover === null || hover === i ? 1 : 0.45}360 stroke="var(--ink)" strokeWidth={0.5}361 onMouseEnter={() => setHover(i)}>362 <title>{`${p.t} — ${fmtNum(p.v)}${serie.unit ? ` ${serie.unit}` : ""}`}</title>363 </rect>364 );365 })}366 {[0, Math.floor(pts.length / 2), pts.length - 1].filter((v, i, a) => a.indexOf(v) === i).map((i) => (367 <text key={i} x={PL + ((W - PL - PR) * (i + 0.5)) / pts.length} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>368 ))}369 </svg>370 {hover !== null && (371 <p className="chip" style={{ marginTop: 8 }}>{pts[hover].t} — <b>{fmtNum(pts[hover].v)}{serie.unit ? ` ${serie.unit}` : ""}</b></p>372 )}373 </figure>374 );375}376377/* ---------- Histogramme (distribution) ---------- */378export function Histogram({ dist }: { dist: Distribution }) {379 const serie: Serie = {380 id: dist.id, title: dist.title, unit: dist.unit, kind: "bar",381 points: (dist.bins ?? []).map((b) => ({ t: b.label, v: b.value })),382 };383 return <VBarChart serie={serie} height={220} />;384}385386/* ---------- Barres empilées (composition dans le temps) ---------- */387export function StackedBarChart({ st, height = 260 }: { st: StackedSerie; height?: number }) {388 const [hover, setHover] = useState<number | null>(null);389 const keys = (st.keys ?? []).slice(0, 6);390 const pts = st.points ?? [];391 if (!keys.length || !pts.length) return <EmptyBlock title={st.title} />;392 const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;393 const totals = pts.map((p) => p.values.slice(0, keys.length).reduce((s, v) => s + (v || 0), 0));394 const vmax = Math.max(...totals, 1);395 const bw = Math.max(2, (W - PL - PR) / pts.length - 2);396 const shades = [1, 0.72, 0.5, 0.34, 0.22, 0.13];397 return (398 <figure className="card" style={{ margin: 0, padding: 16 }}>399 <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>400 <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{st.title}</b>401 <span style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>402 {keys.map((k, i) => (403 <span key={k} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em" }}>404 <span style={{ width: 11, height: 11, borderRadius: 3, border: "1px solid var(--ink)", background: "var(--accent)", opacity: shades[i] }} />405 {k}406 </span>407 ))}408 </span>409 </figcaption>410 <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10 }} role="img" aria-label={st.title}411 onMouseLeave={() => setHover(null)}>412 {[0, 1, 2, 3, 4].map((g) => {413 const y = PT + ((H - PT - PB) * g) / 4;414 return (415 <g key={g}>416 <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />417 <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(vmax - (vmax * g) / 4))}</text>418 </g>419 );420 })}421 {pts.map((p, i) => {422 const x = PL + ((W - PL - PR) * i) / pts.length;423 let yAcc = H - PB;424 return (425 <g key={i} onMouseEnter={() => setHover(i)} opacity={hover === null || hover === i ? 1 : 0.5}>426 {keys.map((k, j) => {427 const v = p.values[j] || 0;428 const h = (H - PT - PB) * (v / vmax);429 yAcc -= h;430 return v > 0 ? (431 <rect key={k} x={x + 1} y={yAcc} width={bw} height={Math.max(h - 1, 0.8)} rx={1.5}432 fill="var(--accent)" opacity={shades[j]} stroke="var(--ink)" strokeWidth={0.4}>433 <title>{`${p.t} · ${k} — ${fmtNum(v)}${st.unit ? ` ${st.unit}` : ""}`}</title>434 </rect>435 ) : null;436 })}437 </g>438 );439 })}440 {[0, Math.floor(pts.length / 2), pts.length - 1].filter((v, i, a) => a.indexOf(v) === i).map((i) => (441 <text key={i} x={PL + ((W - PL - PR) * (i + 0.5)) / pts.length} y={H - 8} textAnchor="middle" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{pts[i].t}</text>442 ))}443 </svg>444 {hover !== null && (445 <p className="chip" style={{ marginTop: 8, display: "inline-flex", gap: 12, flexWrap: "wrap" }}>446 <b>{pts[hover].t}</b>447 {keys.map((k, j) => <span key={k}>{k} : <b>{fmtNum(pts[hover].values[j] || 0)}</b></span>)}448 <span style={{ color: "var(--ink-3)" }}>total {fmtNum(totals[hover])}</span>449 </p>450 )}451 </figure>452 );453}454455/* ---------- Barres horizontales (répartitions, géo) — deltas optionnels ---------- */456export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) {457 const rows = (items ?? []).slice(0, 14);458 if (!rows.length) return <EmptyBlock title={title} />;459 const max = Math.max(...rows.map((r) => r.value), 1);460 return (461 <figure className="card" style={{ margin: 0, padding: 16 }}>462 <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b></figcaption>463 <div style={{ marginTop: 12, display: "grid", gap: 9 }}>464 {rows.map((r) => (465 <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}>466 <div style={{ display: "flex", justifyContent: "space-between", gap: 8, fontSize: 12.5 }}>467 <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>468 <span style={{ display: "inline-flex", gap: 8, alignItems: "baseline", flex: "none" }}>469 {r.delta_pct !== undefined && r.delta_pct !== null && (470 <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 700, color: r.delta_pct >= 0 ? "var(--green)" : "var(--danger)" }}>471 {r.delta_pct >= 0 ? "▲" : "▼"} {fmtPct(r.delta_pct)}472 </span>473 )}474 <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b>475 </span>476 </div>477 <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}>478 <div style={{ height: "100%", width: `${Math.max((r.value / max) * 100, 1)}%`, background: "var(--accent)", border: "1px solid var(--ink)", borderRadius: "0 3px 3px 0", boxSizing: "border-box" }} />479 </div>480 </div>481 ))}482 </div>483 </figure>484 );485}486487/* ---------- Anneau ---------- */488export function Donut({ title, items }: { title: string; items: BreakItem[] }) {489 const rows = (items ?? []).filter((i) => i.value > 0).slice(0, 8);490 const total = rows.reduce((s, r) => s + r.value, 0);491 if (!total) return <EmptyBlock title={title} />;492 const R = 74, C = 2 * Math.PI * R;493 let acc = 0;494 const shades = [1, 0.78, 0.58, 0.42, 0.3, 0.22, 0.15, 0.1];495 return (496 <figure className="card" style={{ margin: 0, padding: 16 }}>497 <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b></figcaption>498 <div style={{ display: "flex", flexWrap: "wrap", gap: 18, alignItems: "center", marginTop: 12 }}>499 <svg viewBox="0 0 200 200" style={{ width: 180, maxWidth: "100%" }} role="img" aria-label={title}>500 {rows.map((r, i) => {501 const frac = r.value / total;502 const off = acc; acc += frac;503 return (504 <circle key={r.label} cx={100} cy={100} r={R} fill="none"505 stroke="var(--accent)" strokeOpacity={shades[i % shades.length]}506 strokeWidth={30} strokeDasharray={`${frac * C} ${C}`} strokeDashoffset={-off * C}507 transform="rotate(-90 100 100)">508 <title>{`${r.label} — ${fmtNum(r.value)} (${((100 * r.value) / total).toFixed(1)} %)`}</title>509 </circle>510 );511 })}512 <circle cx={100} cy={100} r={R} fill="none" stroke="var(--ink)" strokeWidth={1} opacity={0.5} />513 </svg>514 <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "grid", gap: 6, minWidth: 200, flex: 1 }}>515 {rows.map((r, i) => (516 <li key={r.label} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>517 <span style={{ width: 11, height: 11, borderRadius: 3, border: "1px solid var(--ink)", background: "var(--accent)", opacity: shades[i % shades.length] }} />518 <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>519 <b style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}>{((100 * r.value) / total).toFixed(1)} %</b>520 </li>521 ))}522 </ul>523 </div>524 </figure>525 );526}527528/* ---------- Jauge (taux, complétude, couverture) ---------- */529export function GaugeCard({ g }: { g: Gauge }) {530 const frac = Math.max(0, Math.min(1, g.max ? g.value / g.max : 0));531 const R = 60, C = Math.PI * R;532 return (533 <article className="card" style={{ padding: "14px 16px", minWidth: 0 }} title={g.help}>534 <svg viewBox="0 0 150 84" style={{ width: "100%", maxWidth: 190, display: "block", margin: "0 auto" }} role="img" aria-label={`${g.label} : ${fmtNum(g.value)}${g.unit ?? ""} sur ${fmtNum(g.max)}`}>535 <path d={`M15,75 A${R},${R} 0 0 1 135,75`} fill="none" stroke="rgba(20,24,20,0.08)" strokeWidth={13} strokeLinecap="round" />536 <path d={`M15,75 A${R},${R} 0 0 1 135,75`} fill="none" stroke="var(--accent)" strokeWidth={13} strokeLinecap="round"537 strokeDasharray={`${frac * C} ${C}`} />538 <text x={75} y={66} textAnchor="middle" fontFamily="var(--font-display)" fontWeight={700} fontSize={22} fill="var(--ink)">539 {fmtNum(g.value)}{g.unit ? <tspan fontSize={12} fill="var(--ink-2)"> {g.unit}</tspan> : null}540 </text>541 <text x={75} y={80} textAnchor="middle" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{(frac * 100).toFixed(0)} % de {fmtNum(g.max)}{g.unit ? ` ${g.unit}` : ""}</text>542 </svg>543 <p className="klabel" style={{ margin: "8px 0 0", textAlign: "center" }}>{g.label}</p>544 </article>545 );546}547548/* ---------- Calendrier de chaleur ---------- */549export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) {550 if (!cells?.length) return <EmptyBlock title={title} />;551 const byDate = new Map(cells.map((c) => [c.date, c.value]));552 const dates = cells.map((c) => c.date).sort();553 const end = new Date(dates[dates.length - 1] + "T12:00:00");554 const max = Math.max(...cells.map((c) => c.value), 1);555 const weeks = 26, cols: { date: string; v: number }[][] = [];556 const cur = new Date(end);557 cur.setDate(cur.getDate() - (weeks * 7 - 1));558 for (let w = 0; w < weeks; w++) {559 const col: { date: string; v: number }[] = [];560 for (let d = 0; d < 7; d++) {561 const iso = cur.toISOString().slice(0, 10);562 col.push({ date: iso, v: byDate.get(iso) ?? 0 });563 cur.setDate(cur.getDate() + 1);564 }565 cols.push(col);566 }567 return (568 <figure className="card" style={{ margin: 0, padding: 16 }}>569 <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b> <span className="klabel">26 dernières semaines</span></figcaption>570 <div className="tbl-wrap" style={{ marginTop: 12 }}>571 <svg viewBox={`0 0 ${weeks * 14} ${7 * 14}`} style={{ minWidth: 480, width: "100%", height: "auto" }} role="img" aria-label={title}>572 {cols.map((col, w) => col.map((c, d) => (573 <rect key={c.date} x={w * 14} y={d * 14} width={12} height={12} rx={2.5}574 fill={c.v ? "var(--accent)" : "rgba(20,24,20,0.07)"} fillOpacity={c.v ? 0.25 + 0.75 * (c.v / max) : 1}575 stroke="rgba(20,24,20,0.15)" strokeWidth={0.5}>576 <title>{`${c.date} — ${fmtNum(c.v)}`}</title>577 </rect>578 )))}579 </svg>580 </div>581 </figure>582 );583}584585/* ---------- Heatmap horaire 7 × 24 (activité par heure) ---------- */586const DOW = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];587export function HourHeatmap({ title, cells }: { title: string; cells: HourCell[] }) {588 if (!cells?.length) return <EmptyBlock title={title} />;589 const grid = new Map(cells.map((c) => [`${c.dow}-${c.hour}`, c.value]));590 const max = Math.max(...cells.map((c) => c.value), 1);591 const CW = 24, CH = 20, LX = 34, LY = 16;592 return (593 <figure className="card" style={{ margin: 0, padding: 16 }}>594 <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b> <span className="klabel">jour × heure</span></figcaption>595 <div className="tbl-wrap" style={{ marginTop: 12 }}>596 <svg viewBox={`0 0 ${LX + 24 * CW} ${LY + 7 * CH}`} style={{ minWidth: 520, width: "100%", height: "auto" }} role="img" aria-label={title}>597 {[0, 6, 12, 18, 23].map((h) => (598 <text key={h} x={LX + h * CW + CW / 2} y={11} textAnchor="middle" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{h} h</text>599 ))}600 {DOW.map((d, i) => (601 <text key={d} x={LX - 6} y={LY + i * CH + CH / 2 + 3} textAnchor="end" fontSize={9} fill="var(--ink-3)" fontFamily="var(--font-mono)">{d}</text>602 ))}603 {Array.from({ length: 7 }, (_, d) => Array.from({ length: 24 }, (_, h) => {604 const v = grid.get(`${d}-${h}`) ?? 0;605 return (606 <rect key={`${d}-${h}`} x={LX + h * CW} y={LY + d * CH} width={CW - 2} height={CH - 2} rx={2.5}607 fill={v ? "var(--accent)" : "rgba(20,24,20,0.07)"} fillOpacity={v ? 0.22 + 0.78 * (v / max) : 1}608 stroke="rgba(20,24,20,0.15)" strokeWidth={0.5}>609 <title>{`${DOW[d]} ${h} h — ${fmtNum(v)}`}</title>610 </rect>611 );612 }))}613 </svg>614 </div>615 </figure>616 );617}618619/* ---------- Statistiques de série (min/max/moy/méd/σ) ---------- */620export function StatSummary({ serie }: { serie: Serie }) {621 const vs = (serie.points ?? []).map((p) => p.v).filter((v) => typeof v === "number");622 if (vs.length < 2) return null;623 const sorted = [...vs].sort((a, b) => a - b);624 const mean = vs.reduce((s, v) => s + v, 0) / vs.length;625 const med = sorted[Math.floor(sorted.length / 2)];626 const sd = Math.sqrt(vs.reduce((s, v) => s + (v - mean) ** 2, 0) / vs.length);627 const items: [string, number][] = [628 ["Min", sorted[0]], ["Max", sorted[sorted.length - 1]],629 ["Moyenne", Math.round(mean * 100) / 100], ["Médiane", med],630 ["Écart-type", Math.round(sd * 100) / 100],631 ];632 return (633 <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 }}>634 {items.map(([l, v]) => (635 <span key={l} className="chip" style={{ fontSize: 11 }}>636 <span style={{ color: "var(--ink-3)" }}>{l}</span> <b style={{ fontFamily: "var(--font-mono)" }}>{fmtNum(v)}</b>637 </span>638 ))}639 </div>640 );641}642643/* ---------- Tableau : tri, recherche, pagination ---------- */644export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) {645 const [q, setQ] = useState("");646 const [sort, setSort] = useState<{ col: number; dir: 1 | -1 } | null>(null);647 const [page, setPage] = useState(0);648 const rows = useMemo(() => {649 let r = spec.rows ?? [];650 if (q) r = r.filter((row) => row.some((c) => String(c).toLowerCase().includes(q.toLowerCase())));651 if (sort) r = [...r].sort((a, b) => {652 const x = a[sort.col], y = b[sort.col];653 const nx = typeof x === "number" ? x : parseFloat(String(x).replace(/[^\d.,-]/g, "").replace(",", "."));654 const ny = typeof y === "number" ? y : parseFloat(String(y).replace(/[^\d.,-]/g, "").replace(",", "."));655 if (!Number.isNaN(nx) && !Number.isNaN(ny)) return (nx - ny) * sort.dir;656 return String(x).localeCompare(String(y), "fr") * sort.dir;657 });658 return r;659 }, [spec.rows, q, sort]);660 const pages = Math.max(1, Math.ceil(rows.length / pageSize));661 const cur = Math.min(page, pages - 1);662 return (663 <section className="card" style={{ padding: 16 }}>664 <div style={{ display: "flex", flexWrap: "wrap", gap: 10, justifyContent: "space-between", alignItems: "center" }}>665 <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{spec.title}</b>666 <input className="input" style={{ maxWidth: 240 }} placeholder="Rechercher…" value={q}667 onChange={(e) => { setQ(e.target.value); setPage(0); }} aria-label={`Rechercher dans ${spec.title}`} />668 </div>669 <div className="tbl-wrap" style={{ marginTop: 10 }}>670 <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>671 <thead>672 <tr>673 {spec.columns.map((c, i) => (674 <th key={c} onClick={() => setSort((s) => ({ col: i, dir: s?.col === i && s.dir === 1 ? -1 : 1 }))}675 style={{ cursor: "pointer", textAlign: "left", padding: "8px 10px", background: "var(--ink)", color: "var(--paper)", fontFamily: "var(--font-mono)", fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.06em", whiteSpace: "nowrap", userSelect: "none" }}676 aria-sort={sort?.col === i ? (sort.dir === 1 ? "ascending" : "descending") : "none"}>677 {c} {sort?.col === i ? (sort.dir === 1 ? "▲" : "▼") : "↕"}678 </th>679 ))}680 </tr>681 </thead>682 <tbody>683 {rows.slice(cur * pageSize, (cur + 1) * pageSize).map((row, ri) => (684 <tr key={ri} style={{ background: ri % 2 ? "var(--surface-2)" : "var(--surface)" }}>685 {row.map((c, ci) => (686 <td key={ci} style={{ padding: "7px 10px", borderBottom: "1px solid var(--line)", whiteSpace: "nowrap" }}>687 {typeof c === "number" ? fmtNum(c) : c}688 </td>689 ))}690 </tr>691 ))}692 </tbody>693 </table>694 </div>695 <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10, flexWrap: "wrap", gap: 8 }}>696 <span className="klabel">{fmtInt(rows.length)} lignes</span>697 <span style={{ display: "flex", gap: 6 }}>698 <button type="button" className="btn btn-ghost" disabled={cur === 0} onClick={() => setPage(cur - 1)}>←</button>699 <span className="chip">{cur + 1} / {pages}</span>700 <button type="button" className="btn btn-ghost" disabled={cur >= pages - 1} onClick={() => setPage(cur + 1)}>→</button>701 </span>702 </div>703 </section>704 );705}706707/* ---------- Records / faits marquants ---------- */708export function RecordCard({ r }: { r: RecordFact }) {709 return (710 <article className="card" style={{ padding: "12px 16px", display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline", background: "var(--surface-2)" }}>711 <span style={{ fontSize: 13, color: "var(--ink-2)" }}>{r.label}</span>712 <span style={{ textAlign: "right" }}>713 <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{r.value}</b>714 {r.date && <span className="klabel" style={{ display: "block" }}>{r.date}</span>}715 </span>716 </article>717 );718}719720/* ---------- Menu de rapports PDF (5 rapports + personnalisé v3) ---------- */721export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) {722 const [open, setOpen] = useState(false);723 const [busy, setBusy] = useState<string | null>(null);724 const [builder, setBuilder] = useState(false);725 const box = useRef<HTMLSpanElement>(null);726 useEffect(() => {727 if (!open) return;728 const close = (e: MouseEvent) => {729 if (box.current && !box.current.contains(e.target as Node)) setOpen(false);730 };731 document.addEventListener("mousedown", close);732 return () => document.removeEventListener("mousedown", close);733 }, [open]);734 const url = (mode: string) => {735 const p = new URLSearchParams({ period, mode });736 if (from) p.set("from", from);737 if (to) p.set("to", to);738 return `${endpoint}?${p}`;739 };740 const dl = (mode: string) => {741 setBusy(mode);742 setOpen(false);743 const a = document.createElement("a");744 a.href = url(mode);745 a.download = "";746 document.body.appendChild(a);747 a.click();748 a.remove();749 setTimeout(() => setBusy(null), 3000);750 };751 return (752 <span ref={box} style={{ position: "relative", display: "inline-flex", gap: 8, flexWrap: "wrap" }}>753 <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={!!busy}>754 {busy ? "Génération…" : "⬇ Rapport PDF complet"}755 </button>756 <button type="button" className="btn btn-ghost" onClick={() => setOpen((o) => !o)} disabled={!!busy}757 aria-haspopup="menu" aria-expanded={open}>758 Autres rapports ▾759 </button>760 <button type="button" className="btn btn-ghost" onClick={() => setBuilder(true)} disabled={!!busy}>761 🛠 Rapport personnalisé762 </button>763 {builder && (764 <ReportBuilder period={period} from={from} to={to} endpoint={endpoint}765 onClose={() => setBuilder(false)} />766 )}767 {open && (768 <div role="menu" className="card" style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, zIndex: 50, minWidth: 300, padding: 6, background: "var(--surface)", boxShadow: "0 10px 28px rgba(20,24,20,0.18)" }}>769 {REPORT_MODES.map((m) => (770 <button key={m.id} type="button" role="menuitem" onClick={() => dl(m.id)}771 style={{ display: "block", width: "100%", textAlign: "left", border: 0, background: "none", cursor: "pointer", padding: "9px 10px", borderRadius: 6 }}772 onMouseEnter={(e) => (e.currentTarget.style.background = "var(--surface-2)")}773 onMouseLeave={(e) => (e.currentTarget.style.background = "none")}>774 <b style={{ display: "block", fontSize: 13, fontFamily: "var(--font-display)" }}>{m.label}</b>775 <span className="klabel" style={{ fontSize: 11 }}>{m.desc}</span>776 </button>777 ))}778 </div>779 )}780 </span>781 );782}783784/* ---------- v3 : constructeur de rapports personnalisés ----------785 Compose un PDF bloc par bloc : catalogue dérivé du dashboard786 (GET /api/stats/catalog), rendu au choix par bloc, ordre libre, modèles787 sauvegardés en localStorage (clé vp-stats-rapports, propre au site).788 Contrat : SPEC.md §3bis. Rendu dans PdfButton — aucune modif des pages. */789export type CatalogBlock = {790 key: string; section: string; title: string;791 renders: string[]; default_render: string; count?: number;792};793type BuilderSel = { key: string; render: string };794type BuilderTpl = { name: string; title: string; blocks: BuilderSel[] };795796const RENDER_LABELS: Record<string, string> = {797 line: "Courbe", area: "Aire", bar: "Barres verticales",798 bars: "Barres horizontales", donut: "Anneau", lines: "Multi-courbes",799 stacked: "Barres empilées", histogram: "Histogramme", heatmap: "Heatmap",800 cards: "Cartes", gauges: "Jauges", table: "Tableau",801};802const SECTION_LABELS: Record<string, string> = {803 kpis: "Indicateurs", gauges: "Jauges", series: "Évolution",804 multiseries: "Multi-courbes", stacked: "Compositions",805 breakdowns: "Répartitions", distributions: "Distributions",806 geo: "Géographie", heatmap: "Calendrier", hourly: "Activité horaire",807 tables: "Tableaux", records: "Records",808};809const TPL_KEY = "vp-stats-rapports";810811function loadTemplates(): BuilderTpl[] {812 try { return JSON.parse(localStorage.getItem(TPL_KEY) ?? "[]"); }813 catch { return []; }814}815function saveTemplates(t: BuilderTpl[]) {816 try { localStorage.setItem(TPL_KEY, JSON.stringify(t)); } catch { /* plein/privé */ }817}818819export function ReportBuilder({820 period, from, to, endpoint = "/api/stats/report", onClose,821}: {822 period: string; from?: string; to?: string; endpoint?: string; onClose: () => void;823}) {824 const [cat, setCat] = useState<CatalogBlock[] | null>(null);825 const [err, setErr] = useState("");826 const [sel, setSel] = useState<BuilderSel[]>([]);827 const [title, setTitle] = useState("");828 const [busy, setBusy] = useState(false);829 const [tpls, setTpls] = useState<BuilderTpl[]>(loadTemplates);830 const catalogUrl = endpoint.replace(/\/report$/, "/catalog");831832 useEffect(() => {833 const p = new URLSearchParams({ period });834 if (from) p.set("from", from);835 if (to) p.set("to", to);836 fetch(`${catalogUrl}?${p}`)837 .then((r) => (r.ok ? r.json() : Promise.reject(r.status)))838 .then((d) => setCat(d.blocks ?? []))839 .catch(() => setErr("Catalogue indisponible — réessayez plus tard."));840 }, [period, from, to, catalogUrl]);841842 useEffect(() => {843 const esc = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };844 document.addEventListener("keydown", esc);845 const prev = document.body.style.overflow;846 document.body.style.overflow = "hidden";847 return () => { document.removeEventListener("keydown", esc); document.body.style.overflow = prev; };848 }, [onClose]);849850 const add = (b: CatalogBlock) =>851 setSel((s) => s.some((x) => x.key === b.key && x.render === b.default_render)852 ? s : [...s, { key: b.key, render: b.default_render }]);853 const move = (i: number, d: number) => setSel((s) => {854 const j = i + d;855 if (j < 0 || j >= s.length) return s;856 const n = [...s]; [n[i], n[j]] = [n[j], n[i]]; return n;857 });858859 const generate = async () => {860 if (busy || !sel.length) return;861 setBusy(true); setErr("");862 try {863 const body: Record<string, unknown> = { title, period, blocks: sel };864 if (from && to) { body.from = from; body.to = to; }865 const r = await fetch(`${endpoint}/custom`, {866 method: "POST", headers: { "Content-Type": "application/json" },867 body: JSON.stringify(body),868 });869 if (!r.ok) throw new Error(String(r.status));870 const blob = await r.blob();871 const m = (r.headers.get("Content-Disposition") ?? "").match(/filename="?([^";]+)/);872 const a = document.createElement("a");873 a.href = URL.createObjectURL(blob);874 a.download = m ? m[1] : "rapport-personnalise.pdf";875 document.body.appendChild(a); a.click(); a.remove();876 setTimeout(() => URL.revokeObjectURL(a.href), 4000);877 } catch {878 setErr("La génération a échoué — réessayez.");879 }880 setBusy(false);881 };882883 const groups: [string, CatalogBlock[]][] = [];884 for (const b of cat ?? []) {885 const g = groups.find(([s]) => s === b.section);886 if (g) g[1].push(b); else groups.push([b.section, [b]]);887 }888 const selKeys = new Set(sel.map((s) => s.key));889 const mono: React.CSSProperties = { fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em" };890891 return (892 <div role="dialog" aria-modal="true" aria-label="Rapport personnalisé"893 onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}894 style={{ position: "fixed", inset: 0, zIndex: "var(--z-modal, 900)" as never, background: "rgba(20,24,20,0.45)", display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "4vh 14px", overflow: "auto" }}>895 <div className="card" style={{ width: "min(980px,100%)", maxHeight: "92vh", display: "flex", flexDirection: "column", background: "var(--surface)", padding: 0, textAlign: "left", cursor: "default" }}>896 <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, padding: "16px 20px", borderBottom: "1px solid var(--line)" }}>897 <b style={{ fontFamily: "var(--font-display)", fontSize: 18 }}>898 Rapport personnalisé <span className="klabel">· période : {from && to ? `${from} → ${to}` : (PERIODS.find((p) => p.id === period)?.label ?? period)}</span>899 </b>900 <button type="button" className="btn btn-ghost" onClick={onClose}>✕ Fermer</button>901 </div>902 <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", overflow: "auto", flex: 1 }}>903 <div style={{ padding: "14px 20px", minWidth: 0, borderRight: "1px solid var(--line)" }}>904 <h3 style={{ ...mono, color: "var(--ink-3)", margin: "4px 0 10px" }}>Blocs disponibles ({cat?.length ?? "…"})</h3>905 {!cat && !err && <p className="klabel">Chargement du catalogue…</p>}906 {groups.map(([secId, bs]) => (907 <div key={secId}>908 <p style={{ ...mono, color: "var(--ink-2)", margin: "12px 0 6px" }}>{SECTION_LABELS[secId] ?? secId}</p>909 {bs.map((b) => (910 <div key={b.key} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, padding: "7px 10px", border: "1px solid var(--line)", borderRadius: 8, marginBottom: 6, fontSize: 13, opacity: selKeys.has(b.key) ? 0.45 : 1 }}>911 <span style={{ minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={b.title}>{b.title}</span>912 <button type="button" className="btn btn-ghost" onClick={() => add(b)} aria-label={`Ajouter ${b.title}`} style={{ flex: "none" }}>+</button>913 </div>914 ))}915 </div>916 ))}917 </div>918 <div style={{ padding: "14px 20px", minWidth: 0 }}>919 <h3 style={{ ...mono, color: "var(--ink-3)", margin: "4px 0 10px" }}>Composition du rapport ({sel.length})</h3>920 <label className="klabel" htmlFor="rb-title">Titre du rapport</label>921 <input id="rb-title" className="input" style={{ width: "100%", margin: "4px 0 12px", boxSizing: "border-box" }}922 maxLength={80} placeholder="Ex. : Revue mensuelle" value={title} onChange={(e) => setTitle(e.target.value)} />923 {sel.length ? sel.map((s, i) => {924 const b = (cat ?? []).find((x) => x.key === s.key) ?? { title: s.key, renders: [s.render] } as CatalogBlock;925 return (926 <div key={`${s.key}:${s.render}:${i}`} style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 10px", border: "1px solid var(--ink)", borderRadius: 8, marginBottom: 6, background: "var(--surface-2)", fontSize: 13 }}>927 <button type="button" onClick={() => move(i, -1)} disabled={i === 0} aria-label="Monter" style={{ border: 0, background: "none", cursor: "pointer", opacity: i === 0 ? 0.25 : 1 }}>▲</button>928 <button type="button" onClick={() => move(i, 1)} disabled={i === sel.length - 1} aria-label="Descendre" style={{ border: 0, background: "none", cursor: "pointer", opacity: i === sel.length - 1 ? 0.25 : 1 }}>▼</button>929 <span style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={b.title}><b>{i + 1}.</b> {b.title}</span>930 {b.renders.length > 1 ? (931 <select className="input" value={s.render} aria-label="Rendu" style={{ maxWidth: 150, padding: "4px 6px", fontSize: 12 }}932 onChange={(e) => setSel((xs) => xs.map((x, j) => j === i ? { ...x, render: e.target.value } : x))}>933 {b.renders.map((r) => <option key={r} value={r}>{RENDER_LABELS[r] ?? r}</option>)}934 </select>935 ) : <span className="klabel">{RENDER_LABELS[s.render] ?? s.render}</span>}936 <button type="button" onClick={() => setSel((xs) => xs.filter((_, j) => j !== i))} aria-label="Retirer" style={{ border: 0, background: "none", cursor: "pointer" }}>✕</button>937 </div>938 );939 }) : (940 <div style={{ border: "1px dashed var(--line)", borderRadius: 8, padding: 16, color: "var(--ink-3)", fontSize: 13, textAlign: "center" }}>941 Aucun bloc — ajoutez des blocs depuis la colonne de gauche, ou chargez un modèle ci-dessous.942 </div>943 )}944 <p style={{ display: "flex", gap: 8, margin: "10px 0 0" }}>945 <button type="button" className="btn btn-ghost" disabled={!cat?.length}946 onClick={() => setSel((cat ?? []).map((b) => ({ key: b.key, render: b.default_render })))}>Tout ajouter</button>947 <button type="button" className="btn btn-ghost" disabled={!sel.length} onClick={() => setSel([])}>Vider</button>948 </p>949 {err && <p style={{ color: "var(--danger)", fontSize: 12.5, margin: "6px 0 0" }}>{err}</p>}950 </div>951 </div>952 <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10, flexWrap: "wrap", padding: "14px 20px", borderTop: "1px solid var(--line)" }}>953 <span style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>954 <select className="input" aria-label="Modèles sauvegardés" style={{ maxWidth: 210 }} value=""955 onChange={(e) => {956 const t = tpls[Number(e.target.value)];957 if (!t) return;958 setTitle(t.title || t.name);959 setSel((t.blocks ?? []).filter((s) => (cat ?? []).some((b) => b.key === s.key)).map((s) => ({ ...s })));960 }}>961 <option value="">Modèles ({tpls.length})…</option>962 {tpls.map((t, i) => <option key={t.name} value={i}>{t.name}</option>)}963 </select>964 <button type="button" className="btn btn-ghost" disabled={!sel.length}965 onClick={() => {966 const name = window.prompt("Nom du modèle :", title || "Mon rapport");967 if (!name) return;968 const next = [...tpls.filter((t) => t.name !== name), { name, title, blocks: sel.map((s) => ({ ...s })) }];969 setTpls(next); saveTemplates(next);970 }}>💾 Sauvegarder</button>971 <button type="button" className="btn btn-ghost" disabled={!tpls.length}972 onClick={() => {973 const name = window.prompt(`Nom du modèle à supprimer :\n${tpls.map((t) => `· ${t.name}`).join("\n")}`);974 if (!name) return;975 const next = tpls.filter((t) => t.name !== name);976 setTpls(next); saveTemplates(next);977 }}>🗑 Supprimer</button>978 </span>979 <button type="button" className="btn btn-primary" disabled={!sel.length || busy} onClick={generate}>980 {busy ? "Génération…" : "⬇ Générer le PDF"}981 </button>982 </div>983 </div>984 </div>985 );986}987988/* ---------- États ---------- */989export function EmptyBlock({ title }: { title: string }) {990 return (991 <div className="card" style={{ padding: 20, background: "var(--surface-2)", borderStyle: "dashed" }}>992 <b style={{ fontFamily: "var(--font-display)", fontSize: 14 }}>{title}</b>993 <p className="klabel" style={{ margin: "6px 0 0" }}>Pas encore mesuré — aucune donnée disponible pour cette période.</p>994 </div>995 );996}997998export function Fraicheur({ updated, onRefresh }: { updated: string; onRefresh: () => void }) {999 return (1000 <p style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap", margin: 0 }}>1001 <span className="klabel">Mis à jour le {new Date(updated).toLocaleString("fr-CA", { dateStyle: "medium", timeStyle: "short" })}</span>1002 <button type="button" className="btn btn-ghost" onClick={onRefresh}>↻ Rafraîchir</button>1003 </p>1004 );1005}1006