SPB Git

Repository Public

revisions.tsx 16.5 KB 220 lines tsx

1"use client";2import Link from "next/link";3import { useEffect, useState } from "react";4import { useLocale } from "@/i18n/client";5import { dict, fill, formatDateTime } from "@/i18n/dict";6import { api, ApiClientError } from "@/lib/client-api";7import { Dialog, Notice, PageHeader, Spinner, StatusPill, useApi } from "@/components/admin/ui";8import type { listAudit } from "@/server/misc";9import type { getRevision, listRevisions, listSheets, SaveResult } from "@/server/sheets";10import { apiMessage, Loading, Pager, Segments, SheetPreview, useDebounced } from "./common";1112type SheetList = Awaited<ReturnType<typeof listSheets>>;13type Revision = Awaited<ReturnType<typeof listRevisions>>[number];14type RevisionDetail = Awaited<ReturnType<typeof getRevision>>;15type Audit = Awaited<ReturnType<typeof listAudit>>;16type Tab = "revisions" | "audit";1718const T = dict({19  title: ["Historique et audit", "History & audit"], lead: ["Chaque enregistrement crée une révision ; rien n’est jamais effacé. Le journal d’audit trace les actions du studio.", "Every save creates a revision; nothing is ever erased. The audit log records what happens in the studio."],20  tabs: ["Vue", "View"], revisions: ["Révisions", "Revisions"], audit: ["Journal d’audit", "Audit log"], loading: ["Chargement…", "Loading…"], retry: ["Réessayer", "Retry"],21  search: ["Rechercher une fiche", "Search sheets"], searchPh: ["Titre ou adresse…", "Title or slug…"], sheet: ["Fiche", "Sheet"], choose: ["Choisir une fiche…", "Choose a sheet…"], noSheet: ["Aucune fiche ne correspond.", "No sheet matches."],22  more: ["{n} fiches correspondent ; les 100 plus récentes sont listées. Précisez la recherche.", "{n} sheets match; the 100 most recent are listed. Narrow the search."], pick: ["Choisissez une fiche pour voir ses révisions.", "Choose a sheet to see its revisions."],23  edit: ["Ouvrir dans l’éditeur", "Open in the editor"], rev: ["Révision {n}", "Revision {n}"], current: ["Version actuelle", "Current version"], wasPublished: ["A été publiée", "Was published"], noSummary: ["Sans description", "No description"],24  manual: ["Modification manuelle", "Manual edit"], ai_generation: ["Génération par IA", "AI generation"], ai_edit: ["Modification par IA", "AI edit"], revert: ["Restauration", "Revert"], import: ["Import", "Import"], template: ["Modèle", "Template"], source_check: ["Vérification des sources", "Source check"],25  open: ["Aperçu", "Preview"], limit: ["Les 200 révisions les plus récentes sont listées.", "The 200 most recent revisions are listed."],26  restore: ["Restaurer cette révision", "Restore this revision"], restoreHelp: ["La restauration crée une nouvelle révision identique à celle-ci. La version publiée ne change pas tant que vous ne republiez pas.", "Restoring writes a new revision identical to this one. The published version does not change until you publish again."],27  restoreSure: ["Confirmer la restauration", "Confirm the restore"], cancel: ["Annuler", "Cancel"], restored: ["Révision {a} restaurée : c’est maintenant la révision {b} de la fiche.", "Revision {a} restored: it is now revision {b} of the sheet."],28  same: ["La fiche est déjà identique à la révision {a} : rien n’a changé.", "The sheet is already identical to revision {a}: nothing changed."], conflict: ["La fiche a été modifiée ailleurs pendant l’opération ; rien n’a été restauré. Réessayez.", "The sheet was changed elsewhere during the operation; nothing was restored. Try again."],29  isCurrent: ["C’est la version actuelle de la fiche.", "This is the current version of the sheet."],30  filter: ["Filtrer par action (préfixe)", "Filter by action (prefix)"], filterPh: ["ex. sheet. ou asset.uploaded", "e.g. sheet. or asset.uploaded"], quick: ["Filtres rapides", "Quick filters"], all: ["Tout", "All"],31  noEvents: ["Aucun événement.", "No event."], actor: ["Acteur", "Actor"], entity: ["Objet", "Entity"], ip: ["Adresse IP", "IP address"], meta: ["Détails", "Details"],32});33type Tr = ReturnType<typeof T>;3435function RevisionDialog({ t, sheetId, rev, isCurrent, onRestored }: { t: Tr; sheetId: string; rev: Revision; isCurrent: boolean; onRestored: (message: string) => void }) {36  const locale = useLocale(), fr = locale === "fr";37  const { data, error, loading, reload } = useApi<RevisionDetail>(`/api/admin/sheets/${sheetId}/revisions/${rev.id}`);38  const [asking, setAsking] = useState(false), [busy, setBusy] = useState(false), [failure, setFailure] = useState<string | null>(null);39  const restore = async () => {40    setBusy(true); setFailure(null);41    try {42      // The optimistic lock needs the version of the working copy as it is right now.43      const { version } = await api<{ version: number }>(`/api/admin/sheets/${sheetId}`);44      const r = await api<SaveResult>(`/api/admin/sheets/${sheetId}/revert`, { body: { revisionId: rev.id, expectedVersion: version } });45      onRestored(fill(r.changed ? t.restored : t.same, { a: rev.number, b: r.revisionNumber }));46    } catch (e) { setFailure(e instanceof ApiClientError && e.status === 409 ? t.conflict : apiMessage(e, fr)); setBusy(false); }47  };48  return (49    <>50      <p className="text-sm text-muted">{t[rev.origin]} · {formatDateTime(rev.createdAt, locale)}{rev.summary ? ` · ${rev.summary}` : ""}</p>51      <div className="mt-3" aria-live="polite">52        {loading && !data && <Loading label={t.loading} />}53        {error && <Notice tone="bad">{error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void reload(); }}>{t.retry}</button></Notice>}54        {data && <SheetPreview doc={data.doc} locale={data.doc.metadata.locale} />}55      </div>56      <div className="mt-4 grid gap-3">57        {isCurrent ? <Notice>{t.isCurrent}</Notice> : <p className="text-sm text-muted">{t.restoreHelp}</p>}58        <div aria-live="assertive">{failure && <Notice tone="bad">{failure}</Notice>}</div>59        {!isCurrent && (60          <div className="flex flex-wrap justify-end gap-2">61            {asking && <button type="button" className="btn" onClick={() => setAsking(false)} disabled={busy}>{t.cancel}</button>}62            {asking63              ? <button type="button" className="btn btn-danger" onClick={() => { void restore(); }} disabled={busy}>{busy && <Spinner />}{t.restoreSure}</button>64              : <button type="button" className="btn btn-primary" onClick={() => setAsking(true)} disabled={!data}>{t.restore}</button>}65          </div>66        )}67      </div>68    </>69  );70}7172function RevisionsTab({ t }: { t: Tr }) {73  const locale = useLocale(), fr = locale === "fr";74  const [q, setQ] = useState(""), dq = useDebounced(q.trim());75  const [sheetId, setSheetId] = useState("");76  // A link such as /admin/revisions?sheet=<id> opens directly on that sheet.77  useEffect(() => { const id = new URLSearchParams(window.location.search).get("sheet"); if (id && /^[0-9a-f-]{36}$/.test(id)) setSheetId(id); }, []);78  const sheets = useApi<SheetList>(`/api/admin/sheets?limit=100${dq ? `&q=${encodeURIComponent(dq)}` : ""}`);79  const revs = useApi<{ revisions: Revision[] }>(sheetId ? `/api/admin/sheets/${sheetId}/revisions` : null);80  const [openRev, setOpenRev] = useState<Revision | null>(null), [flash, setFlash] = useState<string | null>(null);81  const items = sheets.data?.items ?? [], found = items.find((s) => s.id === sheetId);82  // The chosen sheet stays named when a later search no longer lists it.83  const [kept, setKept] = useState<SheetList["items"][number] | null>(null);84  useEffect(() => { if (found) setKept(found); }, [found]);85  const picked = found ?? (kept?.id === sheetId ? kept : undefined);86  const list = sheetId ? revs.data?.revisions : undefined;87  const newest = list?.[0]?.id;8889  return (90    <>91      <div className="grid gap-3 sm:grid-cols-2">92        <label className="grid gap-1 text-sm font-medium" htmlFor="rv-q">{t.search}93          <input id="rv-q" type="search" inputMode="search" enterKeyHint="search" autoComplete="off" className="field" placeholder={t.searchPh} value={q} maxLength={120} onChange={(e) => setQ(e.target.value)} /></label>94        <label className="grid gap-1 text-sm font-medium" htmlFor="rv-sheet">{t.sheet} {sheets.loading && <span className="sr-only">{t.loading}</span>}95          <select id="rv-sheet" className="field" value={sheetId} onChange={(e) => { setSheetId(e.target.value); setFlash(null); }}>96            <option value="">{t.choose}</option>97            {sheetId && !found && <option value={sheetId}>{picked ? `${picked.title} (${picked.locale.toUpperCase()})` : sheetId}</option>}98            {items.map((s) => <option key={s.id} value={s.id}>{s.title} ({s.locale.toUpperCase()})</option>)}99          </select></label>100      </div>101      <div aria-live="polite" className="mt-2 grid gap-2">102        {sheets.error && <Notice tone="bad">{sheets.error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void sheets.reload(); }}>{t.retry}</button></Notice>}103        {sheets.data && items.length === 0 && <p className="text-sm text-muted">{t.noSheet}</p>}104        {sheets.data && sheets.data.total > items.length && <p className="text-sm text-muted">{fill(t.more, { n: sheets.data.total })}</p>}105      </div>106107      <div className="mt-5" aria-live="polite" aria-busy={revs.loading}>108        {!sheetId && <p className="text-muted">{t.pick}</p>}109        {sheetId && (110          <div className="mb-3 flex flex-wrap items-center justify-between gap-3">111            <div className="flex min-w-0 flex-wrap items-center gap-2">{picked && <><p className="min-w-0 break-words font-display text-xl font-semibold">{picked.title}</p><StatusPill status={picked.status} fr={fr} /></>}</div>112            <Link href={`/admin/sheets/${sheetId}/edit`} className="btn">{t.edit}</Link>113          </div>114        )}115        {flash && <div className="mb-3"><Notice tone="ok">{flash}</Notice></div>}116        {sheetId && revs.error && <Notice tone="bad">{revs.error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void revs.reload(); }}>{t.retry}</button></Notice>}117        {sheetId && revs.loading && !list && <Loading label={t.loading} />}118        {list && (119          <ol className={`grid gap-3 ${revs.loading ? "opacity-60" : ""}`}>120            {list.map((r) => (121              <li key={r.id} className="card p-4">122                <div className="flex flex-wrap items-start justify-between gap-3">123                  <div className="min-w-0">124                    <h3 className="flex flex-wrap items-center gap-2 font-semibold">125                      {fill(t.rev, { n: r.number })}126                      <span className="rounded-full border border-line px-2.5 py-0.5 text-xs font-semibold text-muted">{t[r.origin]}</span>127                      {r.id === newest && <span className="rounded-full border border-accent/50 px-2.5 py-0.5 text-xs font-semibold text-accent">{t.current}</span>}128                      {r.wasPublished && <span className="rounded-full border border-ok/40 px-2.5 py-0.5 text-xs font-semibold text-ok">{t.wasPublished}</span>}129                    </h3>130                    <p className={`mt-1 break-words text-[0.9375rem] ${r.summary ? "" : "text-faint"}`}>{r.summary || t.noSummary}</p>131                    <p className="mt-0.5 text-sm text-faint">{formatDateTime(r.createdAt, locale)}</p>132                  </div>133                  <button type="button" className="btn" onClick={() => setOpenRev(r)}>{t.open}</button>134                </div>135              </li>136            ))}137          </ol>138        )}139        {list && list.length >= 200 && <p className="mt-3 text-sm text-muted">{t.limit}</p>}140      </div>141142      <Dialog open={!!openRev} onClose={() => setOpenRev(null)} title={openRev ? fill(t.rev, { n: openRev.number }) : ""} wide>143        {openRev && sheetId && <RevisionDialog key={openRev.id} t={t} sheetId={sheetId} rev={openRev} isCurrent={openRev.id === newest}144          onRestored={(message) => { setOpenRev(null); setFlash(message); void revs.reload(); void sheets.reload(); }} />}145      </Dialog>146    </>147  );148}149150const AUDIT_PAGE = 50;151const QUICK = ["sheet.", "asset.", "job.", "passkey.", "session.", "settings.", "login"] as const;152153function AuditTab({ t }: { t: Tr }) {154  const locale = useLocale(), fr = locale === "fr";155  const [action, setAction] = useState(""), [offset, setOffset] = useState(0);156  const da = useDebounced(action.trim());157  const { data, error, loading, reload } = useApi<Audit>(`/api/admin/audit?limit=${AUDIT_PAGE}&offset=${offset}${da ? `&action=${encodeURIComponent(da)}` : ""}`);158  const quick: (readonly [string, string])[] = [["", t.all], ...QUICK.map((p) => [p, p] as const)];159  const compact = (meta: unknown) => { if (meta === null || meta === undefined) return ""; const s = JSON.stringify(meta); return s === "{}" ? "" : s; };160  return (161    <>162      <label className="grid gap-1 text-sm font-medium" htmlFor="au-action">{t.filter}163        <input id="au-action" type="search" className="field font-mono" autoComplete="off" autoCapitalize="none" spellCheck={false} placeholder={t.filterPh} value={action} maxLength={60} onChange={(e) => { setAction(e.target.value); setOffset(0); }} /></label>164      <div className="mt-2"><Segments label={t.quick} options={quick} value={QUICK.some((p) => p === action) || action === "" ? action : "\u0000"} onChange={(v) => { setAction(v); setOffset(0); }} /></div>165      <div className="mt-3" aria-live="polite" aria-busy={loading}>166        {error && <Notice tone="bad">{error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void reload(); }}>{t.retry}</button></Notice>}167        {loading && !data && <Loading label={t.loading} />}168        {data && data.items.length === 0 && <p className="py-6 text-muted">{t.noEvents}</p>}169        {data && data.items.length > 0 && (170          <ol className={`grid gap-2 ${loading ? "opacity-60" : ""}`}>171            {data.items.map((e) => {172              const meta = compact(e.meta);173              return (174                <li key={e.id} className="card px-4 py-3">175                  <div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">176                    <h3 className="break-all font-mono text-sm font-semibold">{e.action}</h3>177                    <time dateTime={e.at} className="text-sm text-muted">{formatDateTime(e.at, locale)}</time>178                  </div>179                  <dl className="mt-1.5 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-sm">180                    <dt className="text-faint">{t.actor}</dt><dd>{e.actor}</dd>181                    {(e.entity || e.entityId) && <><dt className="text-faint">{t.entity}</dt><dd className="break-all">{e.entity}{e.entityId ? <> <span className="font-mono text-xs">{e.entityId}</span></> : null}</dd></>}182                    <dt className="text-faint">{t.ip}</dt><dd className="break-all font-mono text-xs leading-5">{e.ip ?? "—"}</dd>183                    {meta && <><dt className="text-faint">{t.meta}</dt><dd className="min-w-0"><code className="block max-h-24 overflow-auto break-all rounded-lg bg-raised px-2 py-1 font-mono text-xs">{meta}</code></dd></>}184                  </dl>185                </li>186              );187            })}188          </ol>189        )}190        {data && <Pager total={data.total} limit={AUDIT_PAGE} offset={offset} onChange={setOffset} fr={fr} />}191      </div>192    </>193  );194}195196export function RevisionsPage() {197  const locale = useLocale(), t = T(locale);198  const [tab, setTab] = useState<Tab>("revisions");199  useEffect(() => { if (window.location.hash === "#audit") setTab("audit"); }, []);200  const tabs = [["revisions", t.revisions], ["audit", t.audit]] as const;201  return (202    <>203      <PageHeader title={t.title} lead={t.lead} />204      <div role="tablist" aria-label={t.tabs} className="mb-5 flex gap-1 border-b border-line">205        {tabs.map(([id, label]) => (206          <button key={id} type="button" role="tab" id={`tab-${id}`} aria-selected={tab === id} aria-controls={`panel-${id}`} tabIndex={tab === id ? 0 : -1} onClick={() => setTab(id)}207            onKeyDown={(e) => { if (e.key === "ArrowRight" || e.key === "ArrowLeft") { const next = id === "revisions" ? "audit" : "revisions"; setTab(next); document.getElementById(`tab-${next}`)?.focus(); } }}208            className={`-mb-px min-h-11 border-b-2 px-4 text-[0.9375rem] font-semibold ${tab === id ? "border-accent text-ink" : "border-transparent text-muted"}`}>209            {label}210          </button>211        ))}212      </div>213      <div role="tabpanel" id={`panel-${tab}`} aria-labelledby={`tab-${tab}`}>214        <h2 className="sr-only">{tab === "revisions" ? t.revisions : t.audit}</h2>215        {tab === "revisions" ? <RevisionsTab t={t} /> : <AuditTab t={t} />}216      </div>217    </>218  );219}220
Files main
Menu

Theme