SPB Git

Repository Public

Metrics.tsx 11.5 KB 293 lines tsx

1// Onglet « Livraison » : métriques de remise des envois de l'API (par jour, par adresse), profondeur des files, arriéré des2// webhooks, approbations en attente. Graphiques SVG accessibles, chacun doublé d'un tableau.3import { useEffect, useRef, useState } from "react"4import { SERIES, fillDays, parseMetrics, percent, sumCounts, totals, type AddressRow, type Backlog, type Counts, type DayRow, type Metrics } from "../../../admin/charts"5import { addMessages, fmtNumber, t } from "../../../i18n"6import { enAdmInfra } from "../../../i18n/en.adm.infra"7import { frAdmInfra } from "../../../i18n/fr.adm.infra"8import { apiGet } from "../../../jmap/http"9import { Icon } from "../../kit"10import { Section } from "../../Page"11import { DeliveryTrendSection, ProblemDeliveries } from "../ops/Trends"12import { DASH, Loadable, fmtWhen, useLoad } from "../shared"13import { AddressChart, DayChart, Legend, ViewToggle, countsSentence, dayLabel, seriesLabel } from "./Charts"14import "./infra.css"1516addMessages("fr", frAdmInfra)17addMessages("en", enAdmInfra)1819const PERIODS = [14, 30, 90] as const20type Period = (typeof PERIODS)[number]21type View = "chart" | "table"2223function Stat({ label, value, testId }: { label: string; value: string; testId?: string }) {24  return (25    <div className="adm-stat">26      <span className="adm-stat-value" data-testid={testId}>27        {value}28      </span>29      <span className="muted small">{label}</span>30    </div>31  )32}3334function CountsCells({ c }: { c: Counts }) {35  return (36    <>37      {SERIES.map((s) => (38        <td key={s} data-label={seriesLabel(s)} data-series={s} className="adm-num">39          {fmtNumber(c[s])}40        </td>41      ))}42    </>43  )44}45function CountsHead() {46  return (47    <>48      {SERIES.map((s) => (49        <th key={s} scope="col" className="adm-num">50          {seriesLabel(s)}51        </th>52      ))}53      <th scope="col" className="adm-num">54        {t("adm.infra.metrics.total")}55      </th>56    </>57  )58}5960function DayTable({ rows, tot, caption }: { rows: readonly DayRow[]; tot: Counts; caption: string }) {61  const active = rows.filter((r) => r.total > 0).reverse()62  return (63    <div className="table-wrap">64      <table className="table cards-sm" data-testid="table-days">65        <caption className="sr-only">{caption}</caption>66        <thead>67          <tr>68            <th scope="col">{t("adm.infra.metrics.col.day")}</th>69            <CountsHead />70          </tr>71        </thead>72        <tbody>73          {active.map((r) => (74            <tr key={r.day} data-day={r.day}>75              <th scope="row" className="adm-rowhead adm-nowrap">76                {dayLabel(r.day, true)}77              </th>78              <CountsCells c={r.counts} />79              <td data-label={t("adm.infra.metrics.total")} className="adm-num" data-total>80                {fmtNumber(r.total)}81              </td>82            </tr>83          ))}84        </tbody>85        <tfoot>86          <tr data-testid="table-days-total">87            <th scope="row" className="adm-rowhead">88              {t("adm.infra.metrics.periodTotal")}89            </th>90            <CountsCells c={tot} />91            <td data-label={t("adm.infra.metrics.total")} className="adm-num" data-total>92              <strong>{fmtNumber(sumCounts(tot))}</strong>93            </td>94          </tr>95        </tfoot>96      </table>97    </div>98  )99}100101function AddressTable({ rows, tot, caption }: { rows: readonly AddressRow[]; tot: Counts; caption: string }) {102  return (103    <div className="table-wrap">104      <table className="table cards-sm" data-testid="table-addresses">105        <caption className="sr-only">{caption}</caption>106        <thead>107          <tr>108            <th scope="col">{t("adm.infra.metrics.col.address")}</th>109            <CountsHead />110          </tr>111        </thead>112        <tbody>113          {rows.map((r) => (114            <tr key={r.address} data-address={r.address}>115              <th scope="row" className="adm-rowhead mono adm-break">116                {r.address}117              </th>118              <CountsCells c={r.counts} />119              <td data-label={t("adm.infra.metrics.total")} className="adm-num" data-total>120                {fmtNumber(r.total)}121              </td>122            </tr>123          ))}124        </tbody>125        <tfoot>126          <tr data-testid="table-addresses-total">127            <th scope="row" className="adm-rowhead">128              {t("adm.infra.metrics.periodTotal")}129            </th>130            <CountsCells c={tot} />131            <td data-label={t("adm.infra.metrics.total")} className="adm-num" data-total>132              <strong>{fmtNumber(sumCounts(tot))}</strong>133            </td>134          </tr>135        </tfoot>136      </table>137    </div>138  )139}140141function BacklogList({ items, prefix, empty, testId }: { items: readonly Backlog[]; prefix: "queue" | "hook"; empty: string; testId: string }) {142  if (items.length === 0) {143    return (144      <p className="muted" data-testid={testId}>145        {empty}146      </p>147    )148  }149  const label = (s: string): string => {150    if (prefix === "queue" && (s === "queued" || s === "scheduled" || s === "pending_approval" || s === "sent" || s === "deferred")) return t(`adm.infra.queue.${s}`)151    if (prefix === "hook" && (s === "pending" || s === "retrying" || s === "failed")) return t(`adm.infra.hook.${s}`)152    return s153  }154  return (155    <div className="table-wrap" data-testid={testId}>156      <table className="table cards-sm">157        <thead>158          <tr>159            <th scope="col">{t("adm.infra.metrics.col.state")}</th>160            <th scope="col" className="adm-num">161              {t("adm.infra.metrics.col.count")}162            </th>163            <th scope="col">{t("adm.infra.metrics.col.oldest")}</th>164          </tr>165        </thead>166        <tbody>167          {items.map((b) => (168            <tr key={b.status} data-status={b.status}>169              <th scope="row" className="adm-rowhead">170                {label(b.status)}171              </th>172              <td data-label={t("adm.infra.metrics.col.count")} className="adm-num">173                {fmtNumber(b.count)}174              </td>175              <td data-label={t("adm.infra.metrics.col.oldest")}>{b.oldest ? fmtWhen(b.oldest) : DASH}</td>176            </tr>177          ))}178        </tbody>179      </table>180    </div>181  )182}183184function Body({ m }: { m: Metrics }) {185  const [dayView, setDayView] = useState<View>("chart")186  const [addrView, setAddrView] = useState<View>("chart")187  const days = fillDays(m.byDay, m.days, new Date())188  const tot = totals(days)189  const total = sumCounts(tot)190  const addrTot = totals(m.byAddress)191  const queue = m.queueDepth.reduce((n, b) => n + b.count, 0)192  const hooks = m.webhookBacklog.reduce((n, b) => n + b.count, 0)193  const busiest = days.reduce<DayRow | null>((best, d) => (d.total > (best?.total ?? 0) ? d : best), null)194  const dayTitle = t("adm.infra.metrics.days.title", { n: m.days })195  const dayDesc = total === 0 ? t("adm.infra.metrics.noSend") : `${t("adm.infra.metrics.summary", { n: total })} ${countsSentence(tot)}.${busiest ? ` ${t("adm.infra.metrics.busiest", { day: dayLabel(busiest.day, true), n: busiest.total })}` : ""}`196  const addrTitle = t("adm.infra.metrics.addresses.title", { n: m.days })197  const top = m.byAddress[0]198  const addrDesc = top ? `${t("adm.infra.metrics.addresses.summary", { n: m.byAddress.length })} ${t("adm.infra.metrics.addresses.top", { address: top.address, n: top.total, pct: percent(top.total, sumCounts(addrTot)) })}` : t("adm.infra.metrics.noSend")199  return (200    <>201      <div className="adm-stats" data-testid="metrics-stats">202        <Stat label={t("adm.infra.metrics.stat.total", { n: m.days })} value={fmtNumber(total)} testId="metrics-total" />203        <Stat label={t("adm.infra.metrics.stat.delivered")} value={total ? `${fmtNumber(percent(tot.delivered, total))} %` : DASH} testId="metrics-delivered-rate" />204        <Stat label={t("adm.infra.metrics.stat.queue")} value={fmtNumber(queue)} testId="metrics-queue" />205        <Stat label={t("adm.infra.metrics.stat.hooks")} value={fmtNumber(hooks)} testId="metrics-hooks" />206        <Stat label={t("adm.infra.metrics.stat.approvals")} value={fmtNumber(m.pendingApprovals)} testId="metrics-approvals" />207      </div>208209      {total === 0 ? (210        <div className="empty card" data-testid="metrics-empty">211          <Icon name="sent" />212          <p>{t("adm.infra.metrics.empty", { n: m.days })}</p>213        </div>214      ) : (215        <>216          <Section title={dayTitle} description={t("adm.infra.metrics.days.desc")} actions={<ViewToggle value={dayView} onChange={setDayView} label={t("adm.infra.view.label", { title: dayTitle })} />}>217            <div data-testid="metrics-days" className="stack">218              {dayView === "chart" ? (219                <>220                  <DayChart rows={days} title={dayTitle} desc={dayDesc} />221                  <Legend totals={tot} />222                  <p className="small muted" data-testid="metrics-days-summary">223                    {dayDesc}224                  </p>225                </>226              ) : (227                <DayTable rows={days} tot={tot} caption={dayTitle} />228              )}229              <p className="small muted">{t("adm.infra.metrics.other.note")}</p>230            </div>231          </Section>232          <Section title={addrTitle} description={t("adm.infra.metrics.addresses.desc")} actions={<ViewToggle value={addrView} onChange={setAddrView} label={t("adm.infra.view.label", { title: addrTitle })} />}>233            <div data-testid="metrics-addresses" className="stack">234              {addrView === "chart" ? (235                <>236                  <AddressChart rows={m.byAddress} title={addrTitle} desc={addrDesc} />237                  <Legend totals={addrTot} />238                  <p className="small muted">{addrDesc}</p>239                </>240              ) : (241                <AddressTable rows={m.byAddress} tot={addrTot} caption={addrTitle} />242              )}243            </div>244          </Section>245        </>246      )}247248      <Section title={t("adm.infra.metrics.queue.title")} description={t("adm.infra.metrics.queue.desc")}>249        <BacklogList items={m.queueDepth} prefix="queue" empty={t("adm.infra.metrics.queue.empty")} testId="metrics-queue-list" />250      </Section>251      <Section title={t("adm.infra.metrics.hooks.title")} description={t("adm.infra.metrics.hooks.desc")}>252        <BacklogList items={m.webhookBacklog} prefix="hook" empty={t("adm.infra.metrics.hooks.empty")} testId="metrics-hooks-list" />253      </Section>254      <Section title={t("adm.infra.metrics.approvals.title")}>255        <p data-testid="metrics-approvals-line">{m.pendingApprovals === 0 ? t("adm.infra.metrics.approvals.none") : t("adm.infra.metrics.approvals.count", { n: m.pendingApprovals })}</p>256      </Section>257    </>258  )259}260261export default function MetricsTab() {262  const [period, setPeriod] = useState<Period>(14)263  const load = useLoad(async (signal) => parseMetrics(await apiGet<unknown>(`/api/admin/metrics?days=${period}`, signal)))264  const first = useRef(true)265  useEffect(() => {266    if (first.current) first.current = false267    else load.reload()268    // eslint-disable-next-line react-hooks/exhaustive-deps269  }, [period])270  return (271    <Loadable272      load={load}273      toolbar={274        <div className="segmented" role="group" aria-label={t("adm.infra.metrics.period")}>275          {PERIODS.map((p) => (276            <button key={p} type="button" aria-pressed={period === p} onClick={() => setPeriod(p)} data-period={p}>277              {t("adm.infra.metrics.period.days", { n: p })}278            </button>279          ))}280        </div>281      }282    >283      {(m) => (284        <>285          <Body m={m} />286          <DeliveryTrendSection />287          <ProblemDeliveries />288        </>289      )}290    </Loadable>291  )292}293
Files main
Menu

Theme