SPB Git

Repository Public

AuditLog.tsx 7.4 KB 60 lines tsx

1"use client";2import { useState } from "react";3import { api, fmtDate, useLoad } from "./client";4import { Dialog, Loading, PageTitle } from "./ui";56interface Entry { id: number; at: string; actor: string; action: string; target: string | null; before_ref: string | null; after_ref: string | null; detail: string | null; ip: string | null }7const GROUPS: [string, string][] = [["", "Toutes les actions"], ["publication", "Publications des séances"], ["plan", "Plan public"], ["session", "Séances"], ["section", "Sections"], ["capsule", "Capsules"], ["resource", "Ressources"], ["course", "Cours"], ["import", "Importations"], ["upload", "Téléversements"], ["job", "Traitements"], ["auth", "Connexions et clés"], ["editor", "Éditeurs"], ["tools", "Outils"], ["studio", "Studio"]];8const ACTION: Record<string, string> = {9  "publication.published": "Séance publiée", "publication.scheduled": "Publication programmée", "publication.rolled_back": "Retour à une version", "publication.withdrawn": "Séance retirée du site", "publication.archived": "Séance archivée", "publication.schedule_cancelled": "Programmation annulée",10  "plan.published": "Plan publié", "plan.scheduled": "Plan programmé", "session.created": "Séance créée", "session.updated": "Fiche modifiée", "session.state": "État changé", "session.moved": "Séance déplacée",11  "section.created": "Section créée", "section.updated": "Section modifiée", "section.deleted": "Section supprimée", "capsule.created": "Capsule créée", "capsule.updated": "Capsule modifiée", "capsule.deleted": "Capsule supprimée", "capsule.reordered": "Capsules réordonnées",12  "capsule.master_attached": "Fichier maître attaché", "capsule.transcoded": "Vidéo encodée", "capsule.captions_attached": "Sous-titres attachés", "capsule.captions_removed": "Sous-titres retirés", "capsule.transcript_attached": "Transcription attachée", "capsule.chapters_saved": "Chapitres enregistrés",13  "resource.created": "Ressource créée", "resource.replaced": "Fichier remplacé", "resource.updated": "Ressource modifiée", "resource.version_restored": "Version rétablie", "resource.deleted": "Ressource supprimée", "course.updated": "Réglages du cours modifiés",14  "import.prepared": "Dépôt lu", "import.applied": "Importation appliquée", "import.discarded": "Importation abandonnée", "upload.completed": "Téléversement terminé", "upload.refused": "Téléversement refusé", "upload.aborted": "Téléversement abandonné",15  "job.cancel_requested": "Annulation demandée", "job.retried": "Traitement relancé", "auth.login.ok": "Connexion", "auth.login.failed": "Connexion refusée", "auth.logout": "Fermeture de session", "auth.passkey.enrolled.setup": "Clé d’accès enrôlée", "auth.passkey.enrolled.recovery": "Clés remplacées (récupération)",16  "auth.passkey.revoked": "Clé d’accès révoquée", "auth.sessions.revoked": "Sessions fermées", "auth.enroll_token.issued.setup": "Lien d’enrôlement émis", "auth.enroll_token.issued.recovery": "Lien de récupération émis", "editor.created": "Éditeur ajouté", "editor.updated": "Éditeur modifié", "editor.disabled": "Éditeur désactivé",17  "tools.search_index_rebuilt": "Index reconstruit", "tools.exported": "Exportation téléchargée", "studio.bootstrapped": "Studio initialisé",18};1920export function AuditLog() {21  const [action, setAction] = useState(""), [before, setBefore] = useState<number | null>(null), [open, setOpen] = useState<Entry | null>(null), [diff, setDiff] = useState<{ before: unknown; after: unknown } | null>(null);22  const { data, error } = useLoad<{ entries: Entry[]; editors: Record<string, string> }>(`audit?action=${encodeURIComponent(action)}${before ? `&before=${before}` : ""}`);23  const show = async (e: Entry) => { setOpen(e); setDiff(null); setDiff(await api<{ before: unknown; after: unknown }>(`audit/${e.id}`).catch(() => ({ before: null, after: null }))); };24  const who = (a: string) => data?.editors[a] ?? ({ system: "Système", worker: "Processus de traitement", cli: "Ligne de commande (serveur)" } as Record<string, string>)[a] ?? a;25  const text = (v: unknown) => (v === null || v === undefined ? "—" : typeof v === "string" ? v : JSON.stringify(v, null, 2));26  return (27    <div data-testid="audit-log">28      <PageTitle eyebrow="Studio" title="Journal"><p>Chaque changement est consigné : qui, quand, quoi, et l’état avant et après. Le journal ne se modifie pas et ne contient ni clé ni jeton.</p></PageTitle>29      <div className="mb-4 flex flex-wrap items-center gap-3"><label className="st-label !mb-0" htmlFor="audit-filter">Filtrer</label><select id="audit-filter" className="field !w-auto" value={action} onChange={(e) => { setAction(e.target.value); setBefore(null); }}>{GROUPS.map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select>{before && <button type="button" className="btn btn-ghost btn-sm" onClick={() => setBefore(null)}>Revenir aux plus récentes</button>}</div>30      {!data ? <Loading error={error} what="le journal" /> : (31        <>32          <div className="card st-scroll">33            <table className="st-table">34              <thead><tr><th scope="col">Quand</th><th scope="col">Qui</th><th scope="col">Quoi</th><th scope="col">Sur quoi</th><th scope="col"><span className="sr-only">Détail</span></th></tr></thead>35              <tbody>36                {data.entries.map((e) => <tr key={e.id} data-action={e.action}><td className="whitespace-nowrap text-sm">{fmtDate(e.at)}</td><td>{who(e.actor)}</td><td>{ACTION[e.action] ?? e.action}</td><td className="st-mono text-muted">{e.target ?? "—"}</td><td className="text-right">{(e.before_ref || e.after_ref || e.detail) && <button type="button" className="btn btn-ghost btn-sm" onClick={() => void show(e)}>Détail</button>}</td></tr>)}37                {!data.entries.length && <tr><td colSpan={5} className="text-muted">Aucune entrée.</td></tr>}38              </tbody>39            </table>40          </div>41          {data.entries.length === 100 && <button type="button" className="btn btn-ghost mt-3" onClick={() => setBefore(data.entries[data.entries.length - 1]!.id)}>Entrées plus anciennes</button>}42        </>43      )}44      <Dialog open={open !== null} onClose={() => setOpen(null)} title={open ? `${ACTION[open.action] ?? open.action} — ${fmtDate(open.at)}` : ""} wide testid="audit-detail">45        {open && (46          <div className="grid gap-3 text-[0.93rem]">47            <p>Par <strong>{who(open.actor)}</strong>{open.target ? <> sur <span className="st-mono">{open.target}</span></> : null}{open.ip ? <> · adresse {open.ip}</> : null}</p>48            {open.detail && <div><p className="st-label">Détail</p><pre className="st-pre">{text(JSON.parse(open.detail))}</pre></div>}49            <div className="st-split">50              <div><p className="st-label">Avant{open.before_ref ? <span className="st-mono ml-2 font-normal text-faint">{open.before_ref.slice(0, 12)}</span> : null}</p><pre className="st-pre">{diff ? text(diff.before) : "…"}</pre></div>51              <div><p className="st-label">Après{open.after_ref ? <span className="st-mono ml-2 font-normal text-faint">{open.after_ref.slice(0, 12)}</span> : null}</p><pre className="st-pre">{diff ? text(diff.after) : "…"}</pre></div>52            </div>53          </div>54        )}55        <div className="mt-5 flex justify-end"><button type="button" className="btn btn-ghost" onClick={() => setOpen(null)}>Fermer</button></div>56      </Dialog>57    </div>58  );59}60
Files main
Menu

Theme