Repository Public
1// Webhooks : journal des livraisons d'un webhook (état, tentatives, dernière réponse, prochaine tentative), filtre par état,2// pagination « Charger la suite », rejeu d'une livraison et envoi d'un événement d'essai.3import { useCallback, useEffect, useId, useRef, useState } from "react"4import { DELIVERY_STATUSES, deliveryTone, type Delivery, type DeliveryStatus, type Webhook } from "../../../admin/webhooks"5import { t } from "../../../i18n"6import { v1, type V1Page } from "../../../mail/v1"7import { toast } from "../../../state/app"8import { Icon, Spinner } from "../../kit"9import { toastFail } from "../kit"10import { DASH, errorText, fmtWhen } from "../shared"11import { TestOutcome, hookCodes, useFocusOnMount, type TestState } from "./common"1213const PAGE = 251415function StatusCell({ d }: { d: Delivery }) {16 const tone = deliveryTone(d.status)17 return (18 <span className={`badge ${tone}`} data-status={d.status}>19 <Icon name={d.status === "delivered" ? "check" : d.status === "failed" ? "close" : d.status === "retrying" ? "refresh" : "clock"} small />20 {t(`adm.webhooks.status.${d.status}`)}21 </span>22 )23}24function lastAnswer(d: Delivery): string {25 if (d.last_status === null && !d.last_error) return d.attempt > 0 ? DASH : t("adm.webhooks.deliveries.notTried")26 const parts: string[] = []27 if (d.last_status !== null) parts.push(`HTTP ${d.last_status}`)28 if (d.last_error && d.last_error !== `http_${d.last_status}`) parts.push(d.last_error === "redirect_not_followed" ? t("adm.webhooks.error.redirect") : d.last_error)29 return parts.join(" · ")30}3132export function Deliveries({ hook, test, onTest }: { hook: Webhook; test: TestState | undefined; onTest: () => Promise<void> }) {33 const id = useId()34 const title = useFocusOnMount<HTMLHeadingElement>()35 const [status, setStatus] = useState<DeliveryStatus | "">("")36 const [items, setItems] = useState<Delivery[] | null>(null)37 const [cursor, setCursor] = useState<string | null>(null)38 const [loading, setLoading] = useState(true)39 const [error, setError] = useState<unknown>(null)40 const [busy, setBusy] = useState<string | null>(null)41 const seq = useRef(0)42 const timer = useRef<number | null>(null)4344 const fetchPage = useCallback(45 async (after: string | null) => {46 const mine = ++seq.current47 setLoading(true)48 setError(null)49 try {50 const q = new URLSearchParams({ limit: String(PAGE) })51 if (status) q.set("status", status)52 if (after) q.set("cursor", after)53 const page = await v1<V1Page<Delivery>>(`/webhooks/${hook.id}/deliveries?${q}`)54 if (mine !== seq.current) return55 setItems((prev) => (after && prev ? [...prev, ...page.data.filter((d) => !prev.some((p) => p.id === d.id))] : page.data))56 setCursor(page.has_more ? page.next_cursor : null)57 } catch (e) {58 if (mine === seq.current) setError(e)59 } finally {60 if (mine === seq.current) setLoading(false)61 }62 },63 [hook.id, status],64 )65 useEffect(() => {66 void fetchPage(null)67 return () => {68 seq.current++69 }70 }, [fetchPage])71 useEffect(72 () => () => {73 if (timer.current !== null) window.clearTimeout(timer.current)74 },75 [],76 )77 /** Une livraison remise en file part au prochain passage du travailleur : une relecture unique, un peu plus tard. */78 const refreshSoon = () => {79 if (timer.current !== null) window.clearTimeout(timer.current)80 timer.current = window.setTimeout(() => void fetchPage(null), 3000)81 }8283 const replay = async (d: Delivery) => {84 setBusy(d.id)85 try {86 const fresh = await v1<Delivery>(`/webhook-deliveries/${d.id}/replay`, { method: "POST", json: {} })87 setItems((list) => (list ? list.map((x) => (x.id === fresh.id ? fresh : x)) : list))88 toast({ kind: "success", text: t("adm.webhooks.replay.done") })89 refreshSoon()90 } catch (e) {91 toastFail(e, hookCodes())92 } finally {93 setBusy(null)94 }95 }96 const runTest = async () => {97 await onTest()98 void fetchPage(null)99 }100101 return (102 <section className="card section" data-testid="webhook-deliveries">103 <h3 ref={title} tabIndex={-1}>104 {t("adm.webhooks.deliveries.title", { name: hook.name })}105 </h3>106 <p className="muted small section-desc">{t("adm.webhooks.deliveries.note")}</p>107 <div className="row wrap adm-toolbar">108 <div className="field">109 <label htmlFor={`${id}-status`}>{t("adm.webhooks.deliveries.filter")}</label>110 <select id={`${id}-status`} className="input" value={status} onChange={(e) => setStatus(e.target.value as DeliveryStatus | "")}>111 <option value="">{t("adm.webhooks.status.all")}</option>112 {DELIVERY_STATUSES.map((s) => (113 <option key={s} value={s}>114 {t(`adm.webhooks.status.${s}`)}115 </option>116 ))}117 </select>118 </div>119 <span className="spacer" />120 <button type="button" className="btn small" onClick={() => void runTest()} disabled={test?.pending === true}>121 <Icon name="send" small />122 <span>{t("adm.webhooks.test.send")}</span>123 </button>124 <button type="button" className="btn small" onClick={() => void fetchPage(null)} disabled={loading} data-testid="deliveries-refresh">125 <Icon name="refresh" small />126 <span>{t("adm.webhooks.deliveries.refresh")}</span>127 </button>128 </div>129 <TestOutcome test={test} />130 {error ? (131 <div className="banner danger" role="alert">132 <Icon name="warn" />133 <span className="adm-grow">{errorText(error, hookCodes())}</span>134 <button type="button" className="btn small" onClick={() => void fetchPage(null)}>135 {t("common.retry")}136 </button>137 </div>138 ) : null}139 {items === null ? (140 error ? null : (141 <Spinner label={t("common.loading")} />142 )143 ) : items.length === 0 ? (144 <div className="empty">145 <Icon name="list" />146 <p>{t(status ? "adm.webhooks.deliveries.emptyFiltered" : "adm.webhooks.deliveries.empty")}</p>147 </div>148 ) : (149 <div className="table-wrap">150 <table className="table cards-sm">151 <caption className="sr-only">{t("adm.webhooks.deliveries.title", { name: hook.name })}</caption>152 <thead>153 <tr>154 <th scope="col">{t("adm.webhooks.col.event")}</th>155 <th scope="col">{t("adm.webhooks.col.status")}</th>156 <th scope="col">{t("adm.webhooks.col.attempts")}</th>157 <th scope="col">{t("adm.webhooks.col.last")}</th>158 <th scope="col">{t("adm.webhooks.col.next")}</th>159 <th scope="col">{t("adm.webhooks.col.created")}</th>160 <th scope="col">161 <span className="sr-only">{t("admin.col.actions")}</span>162 </th>163 </tr>164 </thead>165 <tbody>166 {items.map((d) => (167 <tr key={d.id} data-testid="delivery-row" data-delivery-id={d.id} data-event-id={d.event_id} data-status={d.status}>168 <td data-label={t("adm.webhooks.col.event")}>169 <span className="mono">{d.event_type}</span>170 <span className="mono muted adm-block">{d.event_id}</span>171 </td>172 <td data-label={t("adm.webhooks.col.status")}>173 <StatusCell d={d} />174 </td>175 <td data-label={t("adm.webhooks.col.attempts")}>{d.attempt}</td>176 <td data-label={t("adm.webhooks.col.last")} className="adm-break">177 {lastAnswer(d)}178 </td>179 <td data-label={t("adm.webhooks.col.next")}>{d.next_attempt_at && d.status !== "delivered" && d.status !== "failed" ? fmtWhen(d.next_attempt_at) : DASH}</td>180 <td data-label={t("adm.webhooks.col.created")}>181 {fmtWhen(d.created_at)}182 {d.delivered_at ? <span className="muted adm-block">{t("adm.webhooks.deliveries.deliveredAt", { when: fmtWhen(d.delivered_at) })}</span> : null}183 </td>184 <td>185 <button type="button" className="btn small" onClick={() => void replay(d)} disabled={busy !== null}>186 <Icon name="refresh" small />187 <span>{t("adm.webhooks.replay.action")}</span>188 </button>189 </td>190 </tr>191 ))}192 </tbody>193 </table>194 </div>195 )}196 <div className="row wrap" aria-live="polite">197 {items && items.length > 0 ? <span className="muted small">{t("adm.webhooks.deliveries.count", { n: items.length })}</span> : null}198 <span className="spacer" />199 {loading && items !== null ? <Spinner /> : null}200 {cursor ? (201 <button type="button" className="btn" onClick={() => void fetchPage(cursor)} disabled={loading} data-testid="deliveries-more">202 {t("adm.webhooks.deliveries.more")}203 </button>204 ) : null}205 </div>206 </section>207 )208}209