SPB Git

Repository Public

Trends.tsx 20.1 KB 399 lines tsx

1// Tendances (GET /api/admin/trends) : espace par boîte avec projection, issue des remises dans le temps, utilisation de l'API ;2// remises à problème récentes avec la réponse SMTP et un diagnostic. Courbes et barres en SVG nu, chacune doublée d'un tableau.3import { useEffect, useId, useRef, useState, type ReactNode } from "react"4import { zeroCounts, type DayRow } from "../../../admin/charts"5import { fillDaily, parseApiTrend, parseDeliveryTrend, parseProblems, parseStorageTrend, problemReply, projectLinear, smtpHint, type ApiDay, type DeliveryDay, type Point, type ProblemDelivery, type StorageTrend } from "../../../admin/ops"6import { fmtDateTime, fmtNumber, t } from "../../../i18n"7import { apiGet } from "../../../jmap/http"8import { linkProps } from "../../../state/session"9import { Field, Icon, Spinner } from "../../kit"10import { DayChart, Legend, ViewToggle, dayLabel } from "../infra/Charts"11import { DASH, errorText, fmtBytes, useLoad, type LoadState } from "../shared"12import { Stat, TrendChart } from "./common"1314const PERIODS = [14, 30, 90] as const15type Period = (typeof PERIODS)[number]16type View = "chart" | "table"1718function PeriodPicker({ value, onChange, label }: { value: Period; onChange: (p: Period) => void; label: string }) {19  return (20    <div className="segmented" role="group" aria-label={label}>21      {PERIODS.map((p) => (22        <button key={p} type="button" aria-pressed={value === p} onClick={() => onChange(p)} data-period={p}>23          {t("adm.infra.metrics.period.days", { n: p })}24        </button>25      ))}26    </div>27  )28}2930/** Section autonome : son propre chargement, sa propre erreur (elle ne bloque jamais le reste de l'onglet). */31function TrendSection<T>({ title, description, load, actions, testId, children }: { title: string; description: string; load: LoadState<T>; actions?: ReactNode; testId: string; children: (data: T) => ReactNode }) {32  return (33    <section className="card section" data-testid={testId} aria-label={title}>34      <div className="row wrap section-head">35        <h3>{title}</h3>36        <span className="spacer" />37        {load.loading && load.data !== null ? <Spinner /> : null}38        {actions}39      </div>40      <p className="muted small section-desc">{description}</p>41      {load.error ? (42        <div className="banner danger" role="alert">43          <Icon name="warn" />44          <span className="adm-grow">{errorText(load.error)}</span>45          <button type="button" className="btn small" onClick={load.reload}>46            {t("common.retry")}47          </button>48        </div>49      ) : load.data === null ? (50        <Spinner label={t("common.loading")} />51      ) : (52        <div className="stack">{children(load.data)}</div>53      )}54    </section>55  )56}5758function useTrend<T>(metric: string, period: Period, parse: (raw: unknown) => T): LoadState<T> {59  const load = useLoad(async (signal) => parse(await apiGet<unknown>(`/api/admin/trends?metric=${metric}&days=${period}`, signal)))60  const first = useRef(true)61  useEffect(() => {62    if (first.current) first.current = false63    else load.reload()64    // eslint-disable-next-line react-hooks/exhaustive-deps65  }, [period])66  return load67}6869// ---------------------------------------------------------------- espace70const perDay = (v: number): string => `${v >= 0 ? "+" : "−"}${fmtBytes(Math.abs(Math.round(v)))}`7172/** Tendance de l'espace : total ou une boîte, projection linéaire à 30 jours, délai avant le quota quand il y en a un. */73export function StorageTrendSection({ quotas }: { quotas: ReadonlyMap<string, number> }) {74  const [period, setPeriod] = useState<Period>(30)75  const [view, setView] = useState<View>("chart")76  const [box, setBox] = useState("")77  const load = useTrend<StorageTrend>("storage", period, parseStorageTrend)78  const id = useId()79  const title = t("adm.ops.trend.storage.title")80  return (81    <TrendSection title={title} description={t("adm.ops.trend.storage.desc")} load={load} testId="trend-storage" actions={<PeriodPicker value={period} onChange={setPeriod} label={t("adm.ops.trend.period", { title })} />}>82      {(tr) => {83        const picked = tr.mailboxes.find((m) => m.mailboxId === box)84        const points: Point[] = picked ? picked.points : tr.total85        const quota = picked ? (quotas.get(picked.address.toLowerCase()) ?? null) : null86        const proj = projectLinear(points, 30, quota)87        const last = points.at(-1)88        const name = picked ? picked.address : t("adm.ops.trend.storage.all")89        const desc = !last90          ? t("adm.ops.trend.storage.none")91          : proj92            ? t("adm.ops.trend.storage.summary", { name, used: fmtBytes(last.value), rate: perDay(proj.perDay), projected: fmtBytes(Math.round(proj.projected)) })93            : t("adm.ops.trend.storage.single", { name, used: fmtBytes(last.value) })94        if (!last) return <p className="muted" data-testid="trend-storage-empty">{t("adm.ops.trend.storage.none")}</p>95        return (96          <>97            <div className="row wrap">98              <div className="adm-filter">99                <Field label={t("adm.ops.trend.storage.box")} id={id}>100                  <select id={id} className="select" value={picked ? box : ""} onChange={(e) => setBox(e.target.value)} data-testid="trend-storage-box">101                    <option value="">{t("adm.ops.trend.storage.all")}</option>102                    {tr.mailboxes.map((m) => (103                      <option key={m.mailboxId} value={m.mailboxId}>104                        {m.address}105                      </option>106                    ))}107                  </select>108                </Field>109              </div>110              <span className="spacer" />111              <ViewToggle value={view} onChange={setView} label={t("adm.infra.view.label", { title })} />112            </div>113            <div className="adm-stats">114              <Stat label={t("adm.ops.trend.storage.now")} value={fmtBytes(last.value)} testId="trend-storage-now" />115              <Stat label={t("adm.ops.trend.storage.rate")} value={proj ? `${perDay(proj.perDay)}${t("adm.ops.trend.perDay")}` : DASH} testId="trend-storage-rate" />116              <Stat label={t("adm.ops.trend.storage.in30")} value={proj ? fmtBytes(Math.round(proj.projected)) : DASH} testId="trend-storage-projected" />117              {quota ? <Stat label={t("adm.ops.trend.storage.toQuota")} value={proj?.daysToCapacity === null || !proj ? t("adm.ops.trend.storage.never") : t("adm.ops.days", { n: proj.daysToCapacity })} tone={proj && proj.daysToCapacity !== null && proj.daysToCapacity < 30 ? "danger" : undefined} /> : null}118            </div>119            {view === "chart" ? (120              <TrendChart series={[{ id: "used", label: t("adm.ops.trend.storage.series"), points }]} title={`${title} — ${name}`} desc={desc} format={(v) => fmtBytes(Math.round(v))} binary projected={proj ? { days: proj.horizonDays, value: proj.projected } : null} testId="trend-storage-chart" />121            ) : (122              <div className="table-wrap">123                <table className="table cards-sm" data-testid="trend-storage-table">124                  <caption className="sr-only">{`${title} — ${name}`}</caption>125                  <thead>126                    <tr>127                      <th scope="col">{t("adm.infra.metrics.col.day")}</th>128                      <th scope="col" className="adm-num">129                        {t("adm.ops.trend.storage.series")}130                      </th>131                    </tr>132                  </thead>133                  <tbody>134                    {[...points].reverse().map((p) => (135                      <tr key={p.day} data-day={p.day}>136                        <th scope="row" className="adm-rowhead adm-nowrap">137                          {dayLabel(p.day, true)}138                        </th>139                        <td data-label={t("adm.ops.trend.storage.series")} className="adm-num">140                          {fmtBytes(p.value)}141                        </td>142                      </tr>143                    ))}144                  </tbody>145                </table>146              </div>147            )}148            <p className="small muted" data-testid="trend-storage-summary">149              {desc} {proj ? t("adm.ops.trend.storage.method", { n: proj.samples }) : t("adm.ops.trend.storage.needTwo")}150            </p>151          </>152        )153      }}154    </TrendSection>155  )156}157158// ---------------------------------------------------------------- remises159const toDayRow = (d: DeliveryDay): DayRow => {160  const counts = { ...zeroCounts(), delivered: d.delivered, deferred: d.deferred, bounced: d.bounced, failed: d.failed }161  return { day: d.day, counts, total: d.delivered + d.deferred + d.bounced + d.failed }162}163const zeroDay = (day: string): DeliveryDay => ({ day, received: 0, sent: 0, delivered: 0, deferred: 0, bounced: 0, failed: 0 })164165/** Issue des remises par jour (livrés, différés ou en cours, rebondis, échoués) et volume reçu, d'après les relevés quotidiens. */166export function DeliveryTrendSection() {167  const [period, setPeriod] = useState<Period>(14)168  const [view, setView] = useState<View>("chart")169  const load = useTrend<DeliveryDay[]>("deliveries", period, parseDeliveryTrend)170  const title = t("adm.ops.trend.delivery.title")171  return (172    <TrendSection173      title={title}174      description={t("adm.ops.trend.delivery.desc")}175      load={load}176      testId="trend-deliveries"177      actions={178        <span className="row wrap">179          <PeriodPicker value={period} onChange={setPeriod} label={t("adm.ops.trend.period", { title })} />180          <ViewToggle value={view} onChange={setView} label={t("adm.infra.view.label", { title })} />181        </span>182      }183    >184      {(raw) => {185        const days = fillDaily(raw, period, new Date(), zeroDay)186        const rows = days.map(toDayRow)187        const sum = (k: keyof Omit<DeliveryDay, "day">) => days.reduce((n, d) => n + d[k], 0)188        const tot = { ...zeroCounts(), delivered: sum("delivered"), deferred: sum("deferred"), bounced: sum("bounced"), failed: sum("failed") }189        const out = tot.delivered + tot.deferred + tot.bounced + tot.failed190        const bad = tot.bounced + tot.failed191        const desc = out === 0 ? t("adm.ops.trend.delivery.none", { n: period }) : t("adm.ops.trend.delivery.summary", { n: out, delivered: tot.delivered, deferred: tot.deferred, bounced: tot.bounced, failed: tot.failed })192        return (193          <>194            <div className="adm-stats">195              <Stat label={t("adm.ops.trend.delivery.out")} value={fmtNumber(out)} testId="trend-deliveries-total" />196              <Stat label={t("adm.ops.trend.delivery.bad")} value={out ? `${fmtNumber(Math.round((bad / out) * 1000) / 10)} %` : DASH} tone={out >= 10 && bad / out >= 0.2 ? "danger" : undefined} testId="trend-deliveries-bad" />197              <Stat label={t("adm.ops.trend.delivery.received")} value={fmtNumber(sum("received"))} testId="trend-deliveries-received" />198            </div>199            {out === 0 ? (200              <p className="muted" data-testid="trend-deliveries-empty">201                {desc}202              </p>203            ) : view === "chart" ? (204              <>205                <DayChart rows={rows} title={title} desc={desc} />206                <Legend totals={tot} />207              </>208            ) : null}209            {view === "table" || out === 0 ? null : <p className="small muted">{desc}</p>}210            {view === "table" ? (211              <div className="table-wrap">212                <table className="table cards-sm" data-testid="trend-deliveries-table">213                  <caption className="sr-only">{title}</caption>214                  <thead>215                    <tr>216                      <th scope="col">{t("adm.infra.metrics.col.day")}</th>217                      {(["delivered", "deferred", "bounced", "failed", "received"] as const).map((k) => (218                        <th key={k} scope="col" className="adm-num">219                          {t(`adm.ops.trend.delivery.col.${k}`)}220                        </th>221                      ))}222                    </tr>223                  </thead>224                  <tbody>225                    {[...days].reverse().filter((d) => d.sent + d.received + d.delivered + d.bounced + d.failed > 0).map((d) => (226                      <tr key={d.day} data-day={d.day}>227                        <th scope="row" className="adm-rowhead adm-nowrap">228                          {dayLabel(d.day, true)}229                        </th>230                        {(["delivered", "deferred", "bounced", "failed", "received"] as const).map((k) => (231                          <td key={k} data-label={t(`adm.ops.trend.delivery.col.${k}`)} className="adm-num" data-series={k}>232                            {fmtNumber(d[k])}233                          </td>234                        ))}235                      </tr>236                    ))}237                  </tbody>238                </table>239              </div>240            ) : null}241            <p className="small muted">{t("adm.ops.trend.delivery.note")}</p>242          </>243        )244      }}245    </TrendSection>246  )247}248249// ---------------------------------------------------------------- diagnostics250/** « Pourquoi est-ce bloqué ? » : diagnostic tiré du code SMTP, la réponse d'origine restant visible. */251export function SmtpHintBox({ reply }: { reply: string | null }) {252  const h = smtpHint(reply)253  return (254    <div className="adm-hint" data-testid="smtp-hint" data-kind={h.kind} data-transient={h.transient}>255      <Icon name={h.transient ? "clock" : "close"} small />256      <div className="adm-hint-body">257        <strong>{t(`adm.ops.smtp.${h.kind}`)}</strong>258        <span className="muted">259          {t(h.transient ? "adm.ops.smtp.transient" : "adm.ops.smtp.final")}260          {h.code || h.enhanced ? ` · ${[h.code, h.enhanced].filter(Boolean).join(" ")}` : ""}261        </span>262        {reply ? (263          <p className="adm-reply" lang="en">264            {reply.slice(0, 400)}265          </p>266        ) : null}267      </div>268    </div>269  )270}271272/** Remises récentes différées, rebondies ou échouées, avec la réponse du serveur distant. */273export function ProblemDeliveries() {274  const load = useLoad(async (signal) => parseProblems(await apiGet<unknown>("/api/admin/deliveries/problems?limit=30", signal)))275  return (276    <TrendSection title={t("adm.ops.problems.title")} description={t("adm.ops.problems.desc")} load={load} testId="problem-deliveries" actions={<a className="btn small" {...linkProps("/admin/queue")}>{t("adm.ops.link.queue")}</a>}>277      {(list: ProblemDelivery[]) =>278        list.length === 0 ? (279          <p className="muted" data-testid="problem-deliveries-empty">280            {t("adm.ops.problems.empty")}281          </p>282        ) : (283          <div className="adm-cards">284            {list.map((p) => (285              <article key={p.id} className="card" data-testid="problem-delivery" data-outbound-id={p.id} data-status={p.status}>286                <div className="adm-card-head">287                  <span className={`badge ${p.status === "deferred" ? "warn" : "danger"}`}>288                    <Icon name={p.status === "deferred" ? "clock" : "close"} small />289                    {t(`adm.infra.series.${p.status}`)}290                  </span>291                  <span className="mono adm-break">{p.from}</span>292                  <span className="muted">→</span>293                  <span className="mono adm-break">{p.recipients.map((r) => r.address).join(", ") || DASH}</span>294                  <span className="spacer" />295                  <span className="muted small">{p.updatedAt ? fmtDateTime(p.updatedAt) : DASH}</span>296                </div>297                <SmtpHintBox reply={problemReply(p)} />298                <span className="muted small">{t("adm.ops.problems.attempts", { n: p.attempts })}</span>299              </article>300            ))}301          </div>302        )303      }304    </TrendSection>305  )306}307308// ---------------------------------------------------------------- API309const zeroApi = (day: string): ApiDay => ({ day, requests: 0, errors: 0, rateLimited: 0, avgMs: 0 })310311/** Utilisation de l'API, toutes clés confondues : requêtes et erreurs par jour, limitations de débit, durée moyenne. */312export function ApiTrendSection({ children }: { children?: ReactNode }) {313  const [period, setPeriod] = useState<Period>(14)314  const [view, setView] = useState<View>("chart")315  const load = useTrend<ApiDay[]>("api", period, parseApiTrend)316  const title = t("adm.ops.trend.api.title")317  return (318    <TrendSection319      title={title}320      description={t("adm.ops.trend.api.desc")}321      load={load}322      testId="trend-api"323      actions={324        <span className="row wrap">325          <PeriodPicker value={period} onChange={setPeriod} label={t("adm.ops.trend.period", { title })} />326          <ViewToggle value={view} onChange={setView} label={t("adm.infra.view.label", { title })} />327        </span>328      }329    >330      {(raw) => {331        const days = fillDaily(raw, period, new Date(), zeroApi)332        const requests = days.reduce((n, d) => n + d.requests, 0)333        const errors = days.reduce((n, d) => n + d.errors, 0)334        const limited = days.reduce((n, d) => n + d.rateLimited, 0)335        const avg = requests ? Math.round(days.reduce((n, d) => n + d.avgMs * d.requests, 0) / requests) : 0336        const desc = requests === 0 ? t("adm.ops.trend.api.none", { n: period }) : t("adm.ops.trend.api.summary", { n: requests, errors, limited, ms: avg })337        return (338          <>339            <div className="adm-stats">340              <Stat label={t("adm.ops.trend.api.requests")} value={fmtNumber(requests)} testId="trend-api-requests" />341              <Stat label={t("adm.ops.trend.api.errors")} value={requests ? `${fmtNumber(Math.round((errors / requests) * 1000) / 10)} %` : DASH} testId="trend-api-errors" />342              <Stat label={t("adm.ops.trend.api.limited")} value={fmtNumber(limited)} />343              <Stat label={t("adm.ops.trend.api.avg")} value={requests ? `${fmtNumber(avg)} ms` : DASH} />344            </div>345            {requests === 0 ? (346              <p className="muted" data-testid="trend-api-empty">347                {desc}348              </p>349            ) : view === "chart" ? (350              <>351                <TrendChart352                  series={[353                    { id: "requests", label: t("adm.ops.trend.api.col.requests"), points: days.map((d) => ({ day: d.day, value: d.requests })) },354                    { id: "errors", label: t("adm.ops.trend.api.col.errors"), points: days.map((d) => ({ day: d.day, value: d.errors })) },355                  ]}356                  title={title}357                  desc={desc}358                  testId="trend-api-chart"359                />360                <p className="small muted">{desc}</p>361              </>362            ) : (363              <div className="table-wrap">364                <table className="table cards-sm" data-testid="trend-api-table">365                  <caption className="sr-only">{title}</caption>366                  <thead>367                    <tr>368                      <th scope="col">{t("adm.infra.metrics.col.day")}</th>369                      {(["requests", "errors", "limited", "avg"] as const).map((k) => (370                        <th key={k} scope="col" className="adm-num">371                          {t(`adm.ops.trend.api.col.${k}`)}372                        </th>373                      ))}374                    </tr>375                  </thead>376                  <tbody>377                    {[...days].reverse().filter((d) => d.requests > 0).map((d) => (378                      <tr key={d.day} data-day={d.day}>379                        <th scope="row" className="adm-rowhead adm-nowrap">380                          {dayLabel(d.day, true)}381                        </th>382                        <td data-label={t("adm.ops.trend.api.col.requests")} className="adm-num">{fmtNumber(d.requests)}</td>383                        <td data-label={t("adm.ops.trend.api.col.errors")} className="adm-num">{fmtNumber(d.errors)}</td>384                        <td data-label={t("adm.ops.trend.api.col.limited")} className="adm-num">{fmtNumber(d.rateLimited)}</td>385                        <td data-label={t("adm.ops.trend.api.col.avg")} className="adm-num">{`${fmtNumber(d.avgMs)} ms`}</td>386                      </tr>387                    ))}388                  </tbody>389                </table>390              </div>391            )}392            {children}393          </>394        )395      }}396    </TrendSection>397  )398}399
Files main
Menu

Theme