1// Auteur : Simon-Pierre Boucher — contact@spboucher.ai2// ka-ui/stats/kacharts.tsx — kit de graphiques SVG du module Stats commun3// Groupe KA (zéro dépendance, React 18+). Style : design system ka-ui4// (bordures encre, accent de la plateforme via var(--accent)).5// Composants : KpiCard, PeriodSelector, LineChart (infobulle + légende6// cliquable + comparaison N-1), BarChart, Donut, CalendarHeatmap, DataTable7// (tri/recherche/pagination), RecordCard, PdfButton, EmptyBlock, Fraicheur.8import { useMemo, useState } from "react";910/* ---------- types (contrat SPEC.md) ---------- */11export type Kpi = {12 id: string; label: string; value: number | string; unit?: string;13 delta_pct?: number | null; direction?: "up" | "down";14};15export type Point = { t: string; v: number };16export type Serie = {17 id: string; title: string; unit?: string; kind?: "line" | "bar";18 points: Point[]; compare?: Point[];19};20export type BreakItem = { label: string; value: number };21export type TableSpec = { id: string; title: string; columns: string[]; rows: (string | number)[][] };22export type RecordFact = { label: string; value: string; date?: string };2324export const PERIODS: { id: string; label: string }[] = [25 { id: "auj", label: "Aujourd'hui" },26 { id: "7j", label: "7 jours" },27 { id: "30j", label: "30 jours" },28 { id: "3m", label: "3 mois" },29 { id: "6m", label: "6 mois" },30 { id: "12m", label: "12 mois" },31 { id: "annee", label: "Année en cours" },32 { id: "tout", label: "Tout" },33];3435export const fmtInt = (n: number) => n.toLocaleString("fr-CA");36export const fmtNum = (n: number) =>37 Number.isInteger(n) ? fmtInt(n) : n.toLocaleString("fr-CA", { maximumFractionDigits: 2 });3839/* ---------- KPI ---------- */40export function KpiCard({ k }: { k: Kpi }) {41 const up = (k.direction ?? ((k.delta_pct ?? 0) >= 0 ? "up" : "down")) === "up";42 return (43 <article className="card" style={{ padding: "14px 16px", minWidth: 0 }}>44 <p style={{ margin: 0, fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(22px,2.4vw,30px)", letterSpacing: "-0.02em" }}>45 {typeof k.value === "number" ? fmtNum(k.value) : k.value}46 {k.unit ? <span style={{ fontSize: "0.6em", color: "var(--ink-2)" }}> {k.unit}</span> : null}47 </p>48 <p className="klabel" style={{ margin: "6px 0 0" }}>{k.label}</p>49 {k.delta_pct !== undefined && k.delta_pct !== null && (50 <p style={{ margin: "8px 0 0", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 700, color: up ? "var(--green)" : "var(--danger)" }}>51 {up ? "▲" : "▼"} {k.delta_pct >= 0 ? "+" : ""}{fmtNum(k.delta_pct)} % <span style={{ color: "var(--ink-3)", fontWeight: 500 }}>vs période préc.</span>52 </p>53 )}54 </article>55 );56}5758/* ---------- Sélecteur de période ---------- */59export function PeriodSelector({60 value, onChange, custom, onCustom,61}: {62 value: string; onChange: (p: string) => void;63 custom?: { from: string; to: string }; onCustom?: (from: string, to: string) => void;64}) {65 return (66 <div style={{ display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center" }}>67 {PERIODS.map((p) => (68 <button key={p.id} type="button" onClick={() => onChange(p.id)}69 className="chip" aria-pressed={value === p.id}70 style={{ cursor: "pointer", minHeight: 44, background: value === p.id ? "var(--accent)" : "var(--surface)", color: value === p.id ? "var(--on-accent)" : "var(--ink)" }}>71 {p.label}72 </button>73 ))}74 {onCustom && (75 <span style={{ display: "inline-flex", gap: 6, alignItems: "center" }}>76 <input className="input" type="date" style={{ width: 150 }} value={custom?.from ?? ""} aria-label="Du"77 onChange={(e) => onCustom(e.target.value, custom?.to ?? "")} />78 <span className="klabel">au</span>79 <input className="input" type="date" style={{ width: 150 }} value={custom?.to ?? ""} aria-label="Au"80 onChange={(e) => onCustom(custom?.from ?? "", e.target.value)} />81 </span>82 )}83 </div>84 );85}8687/* ---------- Courbe ---------- */88export function LineChart({ serie, height = 240 }: { serie: Serie; height?: number }) {89 const [hide, setHide] = useState<{ cur: boolean; cmp: boolean }>({ cur: false, cmp: false });90 const [hover, setHover] = useState<number | null>(null);91 const W = 720, H = height, PL = 54, PR = 10, PT = 14, PB = 26;92 const pts = serie.points ?? [];93 if (pts.length < 2) return <EmptyBlock title={serie.title} />;94 const all = [...(hide.cur ? [] : pts), ...(!hide.cmp && serie.compare ? serie.compare : [])];95 const vmax = Math.max(...all.map((p) => p.v), 1);96 const vmin = Math.min(0, ...all.map((p) => p.v));97 const X = (i: number, n: number) => PL + ((W - PL - PR) * i) / (n - 1);98 const Y = (v: number) => PT + (H - PT - PB) * (1 - (v - vmin) / (vmax - vmin || 1));99 const path = (s: Point[]) => s.map((p, i) => `${i ? "L" : "M"}${X(i, s.length)},${Y(p.v)}`).join("");100 const hi = hover !== null ? Math.min(pts.length - 1, Math.max(0, hover)) : null;101 return (102 <figure className="card" style={{ margin: 0, padding: 16 }}>103 <figcaption style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 8 }}>104 <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{serie.title}</b>105 <span style={{ display: "flex", gap: 10 }}>106 <LegendChip label="Période courante" color="var(--accent)" off={hide.cur} onClick={() => setHide((h) => ({ ...h, cur: !h.cur }))} />107 {serie.compare && <LegendChip label="Période comparée" color="var(--ink-3)" dashed off={hide.cmp} onClick={() => setHide((h) => ({ ...h, cmp: !h.cmp }))} />}108 </span>109 </figcaption>110 <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", height: "auto", marginTop: 10, touchAction: "pan-y" }} role="img" aria-label={serie.title}111 onMouseMove={(e) => {112 const r = (e.currentTarget as SVGSVGElement).getBoundingClientRect();113 const fx = ((e.clientX - r.left) / r.width) * W;114 setHover(Math.round(((fx - PL) / (W - PL - PR)) * (pts.length - 1)));115 }}116 onMouseLeave={() => setHover(null)}>117 {[0, 1, 2, 3, 4].map((g) => {118 const y = PT + ((H - PT - PB) * g) / 4;119 const v = vmax - ((vmax - vmin) * g) / 4;120 return (121 <g key={g}>122 <line x1={PL} x2={W - PR} y1={y} y2={y} stroke="var(--line)" strokeWidth={1} />123 <text x={PL - 6} y={y + 3} textAnchor="end" fontSize={10} fill="var(--ink-3)" fontFamily="var(--font-mono)">{fmtInt(Math.round(v))}</text>124 </g>125 );126 })}127 {[0, Math.floor(pts.length / 2), pts.length - 1].map((i) => (128 <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>129 ))}130 {!hide.cmp && serie.compare && serie.compare.length > 1 && (131 <path d={path(serie.compare)} fill="none" stroke="var(--ink-3)" strokeWidth={1.4} strokeDasharray="4 4" />132 )}133 {!hide.cur && <path d={path(pts)} fill="none" stroke="var(--accent)" strokeWidth={2.4} />}134 {hi !== null && (135 <g>136 <line x1={X(hi, pts.length)} x2={X(hi, pts.length)} y1={PT} y2={H - PB} stroke="var(--ink)" strokeWidth={1} strokeDasharray="2 3" />137 <circle cx={X(hi, pts.length)} cy={Y(pts[hi].v)} r={4} fill="var(--accent)" stroke="var(--ink)" strokeWidth={1.5} />138 </g>139 )}140 </svg>141 {hi !== null && (142 <p className="chip" style={{ marginTop: 8 }}>143 {pts[hi].t} — <b>{fmtNum(pts[hi].v)}{serie.unit ? ` ${serie.unit}` : ""}</b>144 {serie.compare?.[hi] && !hide.cmp ? <span style={{ color: "var(--ink-3)" }}> · N-1 : {fmtNum(serie.compare[hi].v)}</span> : null}145 </p>146 )}147 </figure>148 );149}150151function LegendChip({ label, color, off, dashed, onClick }: { label: string; color: string; off: boolean; dashed?: boolean; onClick: () => void }) {152 return (153 <button type="button" onClick={onClick} aria-pressed={!off}154 style={{ display: "inline-flex", alignItems: "center", gap: 6, border: 0, background: "none", cursor: "pointer", opacity: off ? 0.4 : 1, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.06em", minHeight: 44 }}>155 <span style={{ width: 18, height: 0, borderTop: `3px ${dashed ? "dashed" : "solid"} ${color}` }} />156 {label}157 </button>158 );159}160161/* ---------- Barres horizontales (répartitions, géo) ---------- */162export function BarChart({ title, items, unit }: { title: string; items: BreakItem[]; unit?: string }) {163 const rows = (items ?? []).slice(0, 14);164 if (!rows.length) return <EmptyBlock title={title} />;165 const max = Math.max(...rows.map((r) => r.value), 1);166 return (167 <figure className="card" style={{ margin: 0, padding: 16 }}>168 <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b></figcaption>169 <div style={{ marginTop: 12, display: "grid", gap: 9 }}>170 {rows.map((r) => (171 <div key={r.label} title={`${r.label} — ${fmtNum(r.value)}${unit ? ` ${unit}` : ""}`}>172 <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}>173 <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>174 <b style={{ fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{fmtNum(r.value)}{unit ? ` ${unit}` : ""}</b>175 </div>176 <div style={{ marginTop: 3, height: 12, background: "rgba(20,24,20,0.06)", borderRadius: "0 3px 3px 0" }}>177 <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" }} />178 </div>179 </div>180 ))}181 </div>182 </figure>183 );184}185186/* ---------- Anneau ---------- */187export function Donut({ title, items }: { title: string; items: BreakItem[] }) {188 const rows = (items ?? []).filter((i) => i.value > 0).slice(0, 8);189 const total = rows.reduce((s, r) => s + r.value, 0);190 if (!total) return <EmptyBlock title={title} />;191 const R = 74, C = 2 * Math.PI * R;192 let acc = 0;193 const shades = [1, 0.78, 0.58, 0.42, 0.3, 0.22, 0.15, 0.1];194 return (195 <figure className="card" style={{ margin: 0, padding: 16 }}>196 <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b></figcaption>197 <div style={{ display: "flex", flexWrap: "wrap", gap: 18, alignItems: "center", marginTop: 12 }}>198 <svg viewBox="0 0 200 200" style={{ width: 180, maxWidth: "100%" }} role="img" aria-label={title}>199 {rows.map((r, i) => {200 const frac = r.value / total;201 const off = acc; acc += frac;202 return (203 <circle key={r.label} cx={100} cy={100} r={R} fill="none"204 stroke="var(--accent)" strokeOpacity={shades[i % shades.length]}205 strokeWidth={30} strokeDasharray={`${frac * C} ${C}`} strokeDashoffset={-off * C}206 transform="rotate(-90 100 100)">207 <title>{`${r.label} — ${fmtNum(r.value)} (${((100 * r.value) / total).toFixed(1)} %)`}</title>208 </circle>209 );210 })}211 <circle cx={100} cy={100} r={R} fill="none" stroke="var(--ink)" strokeWidth={1} opacity={0.5} />212 </svg>213 <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "grid", gap: 6, minWidth: 200, flex: 1 }}>214 {rows.map((r, i) => (215 <li key={r.label} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5 }}>216 <span style={{ width: 11, height: 11, borderRadius: 3, border: "1px solid var(--ink)", background: "var(--accent)", opacity: shades[i % shades.length] }} />217 <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.label}</span>218 <b style={{ fontFamily: "var(--font-mono)", fontSize: 11 }}>{((100 * r.value) / total).toFixed(1)} %</b>219 </li>220 ))}221 </ul>222 </div>223 </figure>224 );225}226227/* ---------- Calendrier de chaleur ---------- */228export function CalendarHeatmap({ title, cells }: { title: string; cells: { date: string; value: number }[] }) {229 if (!cells?.length) return <EmptyBlock title={title} />;230 const byDate = new Map(cells.map((c) => [c.date, c.value]));231 const dates = cells.map((c) => c.date).sort();232 const end = new Date(dates[dates.length - 1] + "T12:00:00");233 const max = Math.max(...cells.map((c) => c.value), 1);234 const weeks = 26, cols: { date: string; v: number }[][] = [];235 const cur = new Date(end);236 cur.setDate(cur.getDate() - (weeks * 7 - 1));237 for (let w = 0; w < weeks; w++) {238 const col: { date: string; v: number }[] = [];239 for (let d = 0; d < 7; d++) {240 const iso = cur.toISOString().slice(0, 10);241 col.push({ date: iso, v: byDate.get(iso) ?? 0 });242 cur.setDate(cur.getDate() + 1);243 }244 cols.push(col);245 }246 return (247 <figure className="card" style={{ margin: 0, padding: 16 }}>248 <figcaption><b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{title}</b> <span className="klabel">26 dernières semaines</span></figcaption>249 <div className="tbl-wrap" style={{ marginTop: 12 }}>250 <svg viewBox={`0 0 ${weeks * 14} ${7 * 14}`} style={{ minWidth: 480, width: "100%", height: "auto" }} role="img" aria-label={title}>251 {cols.map((col, w) => col.map((c, d) => (252 <rect key={c.date} x={w * 14} y={d * 14} width={12} height={12} rx={2.5}253 fill={c.v ? "var(--accent)" : "rgba(20,24,20,0.07)"} fillOpacity={c.v ? 0.25 + 0.75 * (c.v / max) : 1}254 stroke="rgba(20,24,20,0.15)" strokeWidth={0.5}>255 <title>{`${c.date} — ${fmtNum(c.v)}`}</title>256 </rect>257 )))}258 </svg>259 </div>260 </figure>261 );262}263264/* ---------- Tableau : tri, recherche, pagination ---------- */265export function DataTable({ spec, pageSize = 25 }: { spec: TableSpec; pageSize?: number }) {266 const [q, setQ] = useState("");267 const [sort, setSort] = useState<{ col: number; dir: 1 | -1 } | null>(null);268 const [page, setPage] = useState(0);269 const rows = useMemo(() => {270 let r = spec.rows ?? [];271 if (q) r = r.filter((row) => row.some((c) => String(c).toLowerCase().includes(q.toLowerCase())));272 if (sort) r = [...r].sort((a, b) => {273 const x = a[sort.col], y = b[sort.col];274 const nx = typeof x === "number" ? x : parseFloat(String(x).replace(/[^\d.,-]/g, "").replace(",", "."));275 const ny = typeof y === "number" ? y : parseFloat(String(y).replace(/[^\d.,-]/g, "").replace(",", "."));276 if (!Number.isNaN(nx) && !Number.isNaN(ny)) return (nx - ny) * sort.dir;277 return String(x).localeCompare(String(y), "fr") * sort.dir;278 });279 return r;280 }, [spec.rows, q, sort]);281 const pages = Math.max(1, Math.ceil(rows.length / pageSize));282 const cur = Math.min(page, pages - 1);283 return (284 <section className="card" style={{ padding: 16 }}>285 <div style={{ display: "flex", flexWrap: "wrap", gap: 10, justifyContent: "space-between", alignItems: "center" }}>286 <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{spec.title}</b>287 <input className="input" style={{ maxWidth: 240 }} placeholder="Rechercher…" value={q}288 onChange={(e) => { setQ(e.target.value); setPage(0); }} aria-label={`Rechercher dans ${spec.title}`} />289 </div>290 <div className="tbl-wrap" style={{ marginTop: 10 }}>291 <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>292 <thead>293 <tr>294 {spec.columns.map((c, i) => (295 <th key={c} onClick={() => setSort((s) => ({ col: i, dir: s?.col === i && s.dir === 1 ? -1 : 1 }))}296 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" }}297 aria-sort={sort?.col === i ? (sort.dir === 1 ? "ascending" : "descending") : "none"}>298 {c} {sort?.col === i ? (sort.dir === 1 ? "▲" : "▼") : "↕"}299 </th>300 ))}301 </tr>302 </thead>303 <tbody>304 {rows.slice(cur * pageSize, (cur + 1) * pageSize).map((row, ri) => (305 <tr key={ri} style={{ background: ri % 2 ? "var(--surface-2)" : "var(--surface)" }}>306 {row.map((c, ci) => (307 <td key={ci} style={{ padding: "7px 10px", borderBottom: "1px solid var(--line)", whiteSpace: "nowrap" }}>308 {typeof c === "number" ? fmtNum(c) : c}309 </td>310 ))}311 </tr>312 ))}313 </tbody>314 </table>315 </div>316 <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 10, flexWrap: "wrap", gap: 8 }}>317 <span className="klabel">{fmtInt(rows.length)} lignes</span>318 <span style={{ display: "flex", gap: 6 }}>319 <button type="button" className="btn btn-ghost" disabled={cur === 0} onClick={() => setPage(cur - 1)}>←</button>320 <span className="chip">{cur + 1} / {pages}</span>321 <button type="button" className="btn btn-ghost" disabled={cur >= pages - 1} onClick={() => setPage(cur + 1)}>→</button>322 </span>323 </div>324 </section>325 );326}327328/* ---------- Records / faits marquants ---------- */329export function RecordCard({ r }: { r: RecordFact }) {330 return (331 <article className="card" style={{ padding: "12px 16px", display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline", background: "var(--surface-2)" }}>332 <span style={{ fontSize: 13, color: "var(--ink-2)" }}>{r.label}</span>333 <span style={{ textAlign: "right" }}>334 <b style={{ fontFamily: "var(--font-display)", fontSize: 15 }}>{r.value}</b>335 {r.date && <span className="klabel" style={{ display: "block" }}>{r.date}</span>}336 </span>337 </article>338 );339}340341/* ---------- Bouton PDF ---------- */342export function PdfButton({ period, from, to, endpoint = "/api/stats/report" }: { period: string; from?: string; to?: string; endpoint?: string }) {343 const [busy, setBusy] = useState(false);344 const url = (mode: string) => {345 const p = new URLSearchParams({ period, mode });346 if (from) p.set("from", from);347 if (to) p.set("to", to);348 return `${endpoint}?${p}`;349 };350 const dl = (mode: string) => {351 setBusy(true);352 const a = document.createElement("a");353 a.href = url(mode);354 a.download = "";355 document.body.appendChild(a);356 a.click();357 a.remove();358 setTimeout(() => setBusy(false), 2500);359 };360 return (361 <span style={{ display: "inline-flex", gap: 8, flexWrap: "wrap" }}>362 <button type="button" className="btn btn-primary" onClick={() => dl("complet")} disabled={busy}>363 {busy ? "Génération…" : "⬇ Télécharger le rapport PDF"}364 </button>365 <button type="button" className="btn btn-ghost" onClick={() => dl("synthese")} disabled={busy}>366 Synthèse (2 p.)367 </button>368 </span>369 );370}371372/* ---------- États ---------- */373export function EmptyBlock({ title }: { title: string }) {374 return (375 <div className="card" style={{ padding: 20, background: "var(--surface-2)", borderStyle: "dashed" }}>376 <b style={{ fontFamily: "var(--font-display)", fontSize: 14 }}>{title}</b>377 <p className="klabel" style={{ margin: "6px 0 0" }}>Pas encore mesuré — aucune donnée disponible pour cette période.</p>378 </div>379 );380}381382export function Fraicheur({ updated, onRefresh }: { updated: string; onRefresh: () => void }) {383 return (384 <p style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap", margin: 0 }}>385 <span className="klabel">Mis à jour le {new Date(updated).toLocaleString("fr-CA", { dateStyle: "medium", timeStyle: "short" })}</span>386 <button type="button" className="btn btn-ghost" onClick={onRefresh}>↻ Rafraîchir</button>387 </p>388 );389}390