Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Mail8 * File : web/src/ui/admin/infra/Charts.tsx9 * Module : ui10 * Repository : https://git.spboucher.ai/sp-mail11 * Project Website : https://mail.spboucher.ai12 * Created : 2026-11-1913 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Graphiques des métriques de remise, en SVG nu (aucune bibliothèque) : barres empilées par jour, barres horizontales par44// adresse. Chaque série a un motif distinct (jamais la couleur seule), les couleurs viennent des jetons (thème sombre compris),45// le graphique porte un nom et une description accessibles, et chaque graphique a son tableau équivalent.46import { useEffect, useId, useRef, useState, type ReactNode, type RefObject } from "react"47import { SERIES, clip, horizontalBars, labelIndexes, stackedBars, type AddressRow, type Counts, type DayRow, type Series } from "../../../admin/charts"48import { fmtNumber, getLang, t } from "../../../i18n"4950export const seriesLabel = (s: Series): string => t(`adm.infra.series.${s}`)5152/** Jour UTC « AAAA-MM-JJ » → « 17 nov. » (toujours lu en UTC : c'est le découpage du serveur). */53export function dayLabel(day: string, long = false): string {54 const d = new Date(`${day}T00:00:00Z`)55 if (Number.isNaN(d.getTime())) return day56 return d.toLocaleDateString(getLang() === "fr" ? "fr-CA" : "en-CA", long ? { day: "numeric", month: "long", year: "numeric", timeZone: "UTC" } : { day: "numeric", month: "short", timeZone: "UTC" })57}58/** « Livrés : 3, Échoués : 1 » — seules les séries non nulles. */59export function countsSentence(c: Counts): string {60 const parts = SERIES.filter((s) => c[s] > 0).map((s) => `${seriesLabel(s)} : ${fmtNumber(c[s])}`)61 return parts.length ? parts.join(", ") : t("adm.infra.metrics.noSend")62}6364/** Largeur réelle du conteneur : le graphique est tracé en pixels vrais, le texte reste lisible à 390 px. */65export function useWidth<T extends HTMLElement>(fallback: number): [RefObject<T | null>, number] {66 const ref = useRef<T>(null)67 const [width, setWidth] = useState(fallback)68 useEffect(() => {69 const el = ref.current70 if (!el) return71 const measure = () => setWidth(Math.max(240, Math.floor(el.clientWidth)))72 measure()73 if (typeof ResizeObserver === "undefined") return74 const ro = new ResizeObserver(measure)75 ro.observe(el)76 return () => ro.disconnect()77 }, [])78 return [ref, width]79}8081/** Motifs des séries : plein, hachures, points, croisillons, lignes, contour — distincts sans la couleur. */82function Patterns({ p }: { p: string }) {83 const pat = (s: Series, size: number, children: ReactNode) => (84 <pattern id={`${p}-${s}`} patternUnits="userSpaceOnUse" width={size} height={size}>85 <rect className="adm-chart-bg" width={size} height={size} />86 <g className={`adm-chart-ink adm-chart-${s}`}>{children}</g>87 </pattern>88 )89 return (90 <defs>91 {pat("delivered", 6, <rect className="solid" width="6" height="6" />)}92 {pat("sent", 6, <path d="M-1,1l2,-2M0,6l6,-6M5,7l2,-2" strokeWidth="1.6" />)}93 {pat("deferred", 6, <circle className="solid" cx="3" cy="3" r="1.5" />)}94 {pat("bounced", 6, <path d="M0,0l6,6M6,0l-6,6" strokeWidth="1.3" />)}95 {pat("failed", 4, <path d="M0,2h4" strokeWidth="2.2" />)}96 {pat("other", 6, <path d="M3,0v6" strokeWidth="1" />)}97 </defs>98 )99}100101/** Légende : motif + nom + total de la série (les valeurs ne reposent pas sur la couleur). */102export function Legend({ totals }: { totals: Counts }) {103 const p = useId().replace(/:/g, "")104 return (105 <ul className="adm-chart-legend" data-testid="chart-legend">106 <li className="adm-chart-defs" aria-hidden="true">107 <svg width="0" height="0" focusable="false">108 <Patterns p={p} />109 </svg>110 </li>111 {SERIES.map((s) => (112 <li key={s} data-series={s}>113 <svg width="16" height="16" aria-hidden="true" focusable="false">114 <rect className={`adm-chart-seg adm-chart-${s}`} x="0.5" y="0.5" width="15" height="15" rx="2" fill={`url(#${p}-${s})`} />115 </svg>116 <span>{seriesLabel(s)}</span>117 <span className="adm-chart-legend-n">{fmtNumber(totals[s])}</span>118 </li>119 ))}120 </ul>121 )122}123124export function DayChart({ rows, title, desc }: { rows: readonly DayRow[]; title: string; desc: string }) {125 const p = useId().replace(/:/g, "")126 const [ref, width] = useWidth<HTMLDivElement>(640)127 const height = 240128 const box = { width, height, top: 18, right: 8, bottom: 28, left: 40 }129 const l = stackedBars(rows, box)130 const labels = new Set(labelIndexes(rows.length, width < 480 ? 4 : 7))131 const direct = l.band >= 16132 return (133 <div ref={ref} className="adm-chart" data-testid="chart-days">134 <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} role="img" aria-labelledby={`${p}-t ${p}-d`}>135 <title id={`${p}-t`}>{title}</title>136 <desc id={`${p}-d`}>{desc}</desc>137 <Patterns p={p} />138 {l.ticks.map((tk) => (139 <g key={tk.value}>140 <line className="adm-chart-grid" x1={box.left} x2={width - box.right} y1={tk.y} y2={tk.y} />141 <text className="adm-chart-tick" x={box.left - 6} y={tk.y + 4} textAnchor="end">142 {fmtNumber(tk.value)}143 </text>144 </g>145 ))}146 {l.bars.map((b, i) => (147 <g key={b.day} data-day={b.day} data-total={b.total}>148 {b.rects.map((r) => (149 <rect key={r.series} className={`adm-chart-seg adm-chart-${r.series}`} x={r.x} y={r.y} width={r.width} height={Math.max(1, r.height)} fill={`url(#${p}-${r.series})`}>150 <title>{`${dayLabel(b.day, true)} — ${seriesLabel(r.series)} : ${fmtNumber(r.value)}`}</title>151 </rect>152 ))}153 {direct && b.total > 0 ? (154 <text className="adm-chart-value" x={b.x + l.band / 2} y={(b.rects[b.rects.length - 1]?.y ?? box.top) - 4} textAnchor="middle">155 {fmtNumber(b.total)}156 </text>157 ) : null}158 {labels.has(i) ? (159 <text className="adm-chart-tick" x={b.x + l.band / 2} y={height - 9} textAnchor={i === 0 ? "start" : i === rows.length - 1 ? "end" : "middle"}>160 {dayLabel(b.day)}161 </text>162 ) : null}163 </g>164 ))}165 <line className="adm-chart-axis" x1={box.left} x2={width - box.right} y1={height - box.bottom} y2={height - box.bottom} />166 </svg>167 </div>168 )169}170171export function AddressChart({ rows, title, desc }: { rows: readonly AddressRow[]; title: string; desc: string }) {172 const p = useId().replace(/:/g, "")173 const [ref, width] = useWidth<HTMLDivElement>(640)174 const left = Math.round(Math.min(260, width * 0.42))175 const l = horizontalBars(rows, { width, left, right: 44, top: 22, rowHeight: 30, barHeight: 16 })176 const chars = Math.max(8, Math.floor((left - 10) / 6.6))177 const height = l.height + 6178 return (179 <div ref={ref} className="adm-chart" data-testid="chart-addresses">180 <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} role="img" aria-labelledby={`${p}-t ${p}-d`}>181 <title id={`${p}-t`}>{title}</title>182 <desc id={`${p}-d`}>{desc}</desc>183 <Patterns p={p} />184 {l.ticks.map((tk) => (185 <g key={tk.value}>186 <line className="adm-chart-grid" x1={tk.x} x2={tk.x} y1={18} y2={l.height} />187 <text className="adm-chart-tick" x={tk.x} y={12} textAnchor="middle">188 {fmtNumber(tk.value)}189 </text>190 </g>191 ))}192 {l.rows.map((r) => (193 <g key={r.address} data-address={r.address} data-total={r.total}>194 <text className="adm-chart-label" x={left - 8} y={r.y + 12} textAnchor="end">195 <title>{r.address}</title>196 {clip(r.address, chars)}197 </text>198 {r.rects.map((x) => (199 <rect key={x.series} className={`adm-chart-seg adm-chart-${x.series}`} x={x.x} y={x.y} width={Math.max(1, x.width)} height={x.height} fill={`url(#${p}-${x.series})`}>200 <title>{`${r.address} — ${seriesLabel(x.series)} : ${fmtNumber(x.value)}`}</title>201 </rect>202 ))}203 <text className="adm-chart-value" x={(r.rects.length ? r.rects[r.rects.length - 1].x + r.rects[r.rects.length - 1].width : left) + 6} y={r.y + 12}>204 {fmtNumber(r.total)}205 </text>206 </g>207 ))}208 <line className="adm-chart-axis" x1={left} x2={left} y1={18} y2={l.height} />209 </svg>210 </div>211 )212}213214/** Bascule « Graphique / Tableau » d'une section. */215export function ViewToggle({ value, onChange, label }: { value: "chart" | "table"; onChange: (v: "chart" | "table") => void; label: string }) {216 return (217 <div className="segmented" role="group" aria-label={label}>218 <button type="button" aria-pressed={value === "chart"} onClick={() => onChange("chart")}>219 {t("adm.infra.view.chart")}220 </button>221 <button type="button" aria-pressed={value === "table"} onClick={() => onChange("table")}>222 {t("adm.infra.view.table")}223 </button>224 </div>225 )226}227