feat(admin): migrate audit presentation and protect pending actions

This commit is contained in:
cesnimda
2026-10-20 15:26:49 +02:00
parent 4760fd102c
commit f9e1d06bf7
12 changed files with 636 additions and 48 deletions
+79 -2
View File
@@ -1,11 +1,17 @@
import React from "react";
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { api } from "./api";
import { api, getApiErrorMessage } from "./api";
import { I18nProvider } from "./i18n/I18nProvider";
import { ToastProvider } from "./toast";
import AdminAuditPage from "./views/AdminAuditPage";
import { translations } from "./i18n/translations";
const mockToast = jest.fn();
let mockSession = "one";
jest.mock("./sessionBoundary", () => ({ checkSessionCookie: jest.fn(), getSessionContext: () => mockSession, isSessionInvalidated: () => false }));
jest.mock("./toast", () => ({ ...jest.requireActual("./toast"), useToast: () => ({ toast: mockToast }) }));
jest.mock("./api", () => ({
api: { get: jest.fn(), post: jest.fn() },
@@ -21,6 +27,77 @@ function renderPage() {
beforeEach(() => {
jest.clearAllMocks();
window.localStorage.clear();
mockSession = "one";
});
const row = { id: 7, type: "Deleted", at: "2026-10-20T12:00:00Z", jobApplicationId: 42, note: "Owner authored text" };
function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>(done => { resolve = done; }); return { promise, resolve }; }
test("[P7-10 audit] retains shared heading hierarchy and a named keyboard scroll region", async () => {
mockedApi.get.mockResolvedValue({ data: [row] } as any);
renderPage();
await screen.findByRole("button", { name: "Undo" });
expect(screen.getByRole("heading", { name: "Audit log", level: 2 })).toBeInTheDocument();
expect(screen.getByRole("heading", { name: translations.en.adminAuditEvents, level: 3 })).toBeInTheDocument();
const region = screen.getByRole("region", { name: "Audit log" });
expect(region).toHaveAttribute("tabindex", "0");
expect(within(region).getByRole("table")).toHaveAccessibleName("Audit log");
});
test("[P7-10 audit] exact Undo allowlist and deleted-only Restore retain endpoint contracts", async () => {
const types = ["StatusChanged", "FollowUpSet", "ResponseUpdated", "Deleted", "Restored", "Created", "NoteAdded"];
mockedApi.get.mockResolvedValue({ data: types.map((type, index) => ({ ...row, type, id: index + 1 })) } as any);
renderPage();
expect(await screen.findAllByRole("button", { name: "Undo" })).toHaveLength(5);
expect(screen.getAllByRole("button", { name: "Restore" })).toHaveLength(1);
});
test("[P7-10 audit] Undo and Restore serialize across rows, retaining focus on pending table", async () => {
const held = deferred<any>();
mockedApi.get.mockResolvedValue({ data: [row, { ...row, id: 8 }] } as any);
mockedApi.post.mockReturnValue(held.promise);
renderPage();
const undo = (await screen.findAllByRole("button", { name: "Undo" }))[0];
act(() => undo.focus());
act(() => { fireEvent.click(undo); fireEvent.click(undo); fireEvent.click(screen.getAllByRole("button", { name: "Restore" })[1]); });
expect(mockedApi.post).toHaveBeenCalledTimes(1);
expect(mockedApi.post).toHaveBeenCalledWith("/admin/audit/7/undo", {});
expect(screen.getByRole("region", { name: "Audit log" })).toHaveFocus();
expect(screen.getByRole("region", { name: "Audit log" })).toHaveAttribute("aria-busy", "true");
expect(screen.getAllByRole("button", { name: "Undo" })[1]).toBeDisabled();
await act(async () => held.resolve({ data: { ok: true } }));
});
test("[P7-10 audit] a committed Restore with failed refresh recovers through GET only", async () => {
mockedApi.get.mockResolvedValueOnce({ data: [row] } as any).mockRejectedValueOnce(new Error("offline")).mockResolvedValue({ data: [] } as any);
mockedApi.post.mockResolvedValue({ data: {} } as any);
renderPage();
fireEvent.click(await screen.findByRole("button", { name: "Restore" }));
expect(await screen.findByText(translations.en.adminAuditLoadFailed)).toBeInTheDocument();
expect(mockedApi.post).toHaveBeenCalledWith("/jobapplications/42/restore", {});
const retry = screen.getByRole("button", { name: "Retry" }); act(() => retry.focus()); fireEvent.click(retry);
expect(await screen.findByText("No events.")).toBeInTheDocument();
expect(screen.getByRole("region", { name: "Audit log" })).toHaveFocus();
expect(mockedApi.post).toHaveBeenCalledTimes(1); expect(mockedApi.get).toHaveBeenCalledTimes(3);
});
test.each(["unmount", "session"])("[P7-10 audit] late Undo after %s cannot notify or refresh", async boundary => {
const held = deferred<any>(); mockedApi.post.mockReturnValue(held.promise); mockedApi.get.mockResolvedValue({ data: [row] } as any);
const view = renderPage(); fireEvent.click(await screen.findByRole("button", { name: "Undo" }));
if (boundary === "unmount") view.unmount(); else mockSession = "two";
await act(async () => held.resolve({ data: { message: "Undone" } }));
expect(mockToast).not.toHaveBeenCalled(); expect(mockedApi.get).toHaveBeenCalledTimes(1);
});
test("[P7-10 audit] pending failure uses safe current-language feedback without a locale GET", async () => {
const held = deferred<any>(); mockedApi.post.mockReturnValue(held.promise); mockedApi.get.mockResolvedValue({ data: [row] } as any);
renderPage(); fireEvent.click(await screen.findByRole("button", { name: "Undo" }));
act(() => window.dispatchEvent(new StorageEvent("storage", { key: "uiLanguage", newValue: "nb" })));
const error = { response: { data: { title: "<html>proxy error</html>" } } };
await act(async () => held.resolve(Promise.reject(error)));
await waitFor(() => expect(mockToast).toHaveBeenCalledWith(translations.nb.adminAuditUndoFailed, "error"));
expect(getApiErrorMessage).toHaveBeenCalledWith(error, translations.nb.adminAuditUndoFailed);
expect(mockedApi.get).toHaveBeenCalledTimes(1);
});
test("distinguishes an unavailable audit log from an empty audit log and retries", async () => {
+2
View File
@@ -2158,6 +2158,7 @@ export const translations = {
adminAuditUndone: "Undone.",
adminAuditUndoFailed: "Undo failed.",
adminAuditLoadFailed: "Unable to load audit events",
adminAuditEvents: "Events",
adminAuditLoadFailedBody: "The audit log cannot reach the API right now.",
adminAuditJobFallback: "Job #{id}",
adminAuditTitle: "Audit log",
@@ -4931,6 +4932,7 @@ export const translations = {
adminAuditUndone: "Angret.",
adminAuditUndoFailed: "Kunne ikke angre.",
adminAuditLoadFailed: "Kunne ikke laste revisjonshendelser",
adminAuditEvents: "Hendelser",
adminAuditLoadFailedBody: "Revisjonsloggen fikk ikke kontakt med API-et akkurat nå.",
adminAuditJobFallback: "Jobb #{id}",
adminAuditTitle: "Revisjonslogg",
+43 -43
View File
@@ -1,10 +1,9 @@
import React, { useState } from "react";
import React, { useEffect, useRef, useState } from "react";
import {
Box,
Button,
Chip,
Paper,
Table,
TableBody,
TableCell,
@@ -14,11 +13,13 @@ import {
Typography,
} from "@mui/material";
import { api } from "../api";
import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";
import { useViewResource } from "../hooks/useViewResource";
import ViewStateNotice from "../components/ViewStateNotice";
import { PageHeader, PageSection } from "../layout/PageLayout";
import { checkSessionCookie, getSessionContext, isSessionInvalidated } from "../sessionBoundary";
type AuditItem = {
id: number;
@@ -43,72 +44,69 @@ export default function AdminAuditPage() {
const { toast } = useToast();
const { language, t } = useI18n();
const [busyId, setBusyId] = useState<number | null>(null);
const body=useRef<HTMLDivElement>(null);
const owner=useRef({ mounted: true, generation: 0, busy: false });
const currentTranslation=useRef(t);
const fallback=useRef(t("adminAuditLoadFailed"));
useEffect(() => { currentTranslation.current=t; }, [t]);
useEffect(() => { const lifetime=owner.current; lifetime.mounted=true; lifetime.generation+=1; return () => { lifetime.mounted=false; lifetime.generation+=1; }; }, []);
const auditResource = useViewResource(
async () => {
const r = await api.get<AuditItem[]>("/admin/audit?take=200");
return r.data ?? [];
},
{ initialData: [], errorMessage: t("adminAuditLoadFailed"), deps: [t] },
{ initialData: [], errorMessage: fallback.current },
);
const undo = async (e: AuditItem) => {
if (!canUndo(e.type)) return;
const mutate = async (e: AuditItem, action: "undo" | "restore") => {
if (action === "undo" ? !canUndo(e.type) : e.type !== "Deleted") return;
checkSessionCookie(); const lifetime=owner.current;
if (!lifetime.mounted || lifetime.busy || isSessionInvalidated()) return;
lifetime.busy=true;
const generation=lifetime.generation; const context=getSessionContext();
const active=() => { checkSessionCookie(); return lifetime.mounted && lifetime.generation===generation && !isSessionInvalidated() && getSessionContext()===context; };
if (body.current?.contains(document.activeElement)) body.current.focus();
setBusyId(e.id);
try {
const res = await api.post<{ ok: boolean; message: string }>(`/admin/audit/${e.id}/undo`, {});
toast(res.data?.message || t("adminAuditUndone"), "success");
const res=await api.post<{ ok: boolean; message?: string }>(action === "undo" ? `/admin/audit/${e.id}/undo` : `/jobapplications/${e.jobApplicationId}/restore`, {});
if (!active()) return;
toast(action === "undo" && res.data?.message || currentTranslation.current(action === "undo" ? "adminAuditUndone" : "adminAuditRestored"), "success");
await auditResource.reload();
} catch (err: any) {
const msg = err?.response?.data?.message || err?.response?.data || err?.message || t("adminAuditUndoFailed");
toast(String(msg), "error");
} catch (error) {
if (active()) toast(getApiErrorMessage(error, currentTranslation.current(action === "undo" ? "adminAuditUndoFailed" : "adminAuditRestoreFailed")), "error");
} finally {
setBusyId(null);
}
};
const restore = async (e: AuditItem) => {
setBusyId(e.id);
try {
await api.post(`/jobapplications/${e.jobApplicationId}/restore`, {});
toast(t("adminAuditRestored"), "success");
await auditResource.reload();
} catch (err: any) {
const msg = err?.response?.data || err?.message || t("adminAuditRestoreFailed");
toast(String(msg), "error");
} finally {
setBusyId(null);
lifetime.busy=false;
if (active()) setBusyId(null);
}
};
const rows = auditResource.data;
const error=auditResource.error?.message===fallback.current ? { ...auditResource.error, message: t("adminAuditLoadFailed") } : auditResource.error;
return (
<Paper sx={{ mt: 0, p: 2 }}>
<Typography component="h2" variant="h5" sx={{ fontWeight: 900, mb: 1 }}>
{t("adminAuditTitle")}
</Typography>
<Typography sx={{ color: "text.secondary", mb: 2 }}>
{t("adminAuditSubtitle")}
</Typography>
<Box sx={{ display: "grid", gap: "var(--app-section-gap)", minWidth: 0 }}>
<PageHeader level="h2" title={t("adminAuditTitle")} description={t("adminAuditSubtitle")} />
<PageSection level="h3" surface title={t("adminAuditEvents")}>
<Box ref={body} role="region" aria-label={t("adminAuditTitle")} tabIndex={0} aria-busy={busyId!==null || auditResource.loading || auditResource.refreshing} sx={{ minWidth: 0, overflow: "auto" }}>
<ViewStateNotice
loading={auditResource.loading}
error={auditResource.error}
error={error}
title={t("adminAuditLoadFailed")}
description={t("adminAuditLoadFailedBody")}
onRetry={auditResource.reload}
onRetry={async () => { body.current?.focus(); await auditResource.reload(); }}
/>
{!auditResource.error ? <TableContainer sx={{ borderRadius: 2, border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
<Table size="small">
{!auditResource.error ? <TableContainer sx={{ overflow: "visible" }}>
<Table size="small" aria-label={t("adminAuditTitle")} sx={{ minWidth: 900, "& th, & td": { overflowWrap: "anywhere" }, "& button": { whiteSpace: "normal", "@media (pointer: coarse)": { minHeight: 44 } } }}>
<TableHead>
<TableRow>
<TableCell sx={{ width: 165 }}>{t("adminAuditAt")}</TableCell>
<TableCell sx={{ width: 160 }}>{t("adminAuditType")}</TableCell>
<TableCell>{t("adminAuditJob")}</TableCell>
<TableCell sx={{ minWidth: 260 }}>{t("adminAuditJob")}</TableCell>
<TableCell sx={{ width: 220 }}>{t("adminAuditUser")}</TableCell>
<TableCell>{t("adminAuditDetails")}</TableCell>
<TableCell sx={{ minWidth: 220 }}>{t("adminAuditDetails")}</TableCell>
<TableCell sx={{ width: 170 }}>{t("adminAuditActions")}</TableCell>
</TableRow>
</TableHead>
@@ -130,7 +128,7 @@ export default function AdminAuditPage() {
const jobLabel = e.jobTitle || t("adminAuditJobFallback", { id: e.jobApplicationId });
const ownerLabel = e.ownerEmail || e.ownerUserName || e.ownerUserId || "-";
const details = e.oldValue || e.newValue ? `${e.oldValue ?? ""} -> ${e.newValue ?? ""}` : "";
const disabled = busyId === e.id;
const disabled = busyId !== null;
const showRestore = e.type === "Deleted";
return (
@@ -160,12 +158,12 @@ export default function AdminAuditPage() {
<TableCell>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
{canUndo(e.type) ? (
<Button size="small" variant="outlined" disabled={disabled} onClick={() => void undo(e)}>
<Button size="small" variant="outlined" disabled={disabled} onClick={() => void mutate(e, "undo")}>
{t("adminAuditUndo")}
</Button>
) : null}
{showRestore ? (
<Button size="small" variant="contained" disabled={disabled} onClick={() => void restore(e)}>
<Button size="small" variant="contained" disabled={disabled} onClick={() => void mutate(e, "restore")}>
{t("adminAuditRestore")}
</Button>
) : null}
@@ -178,6 +176,8 @@ export default function AdminAuditPage() {
</TableBody>
</Table>
</TableContainer> : null}
</Paper>
</Box>
</PageSection>
</Box>
);
}