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
@@ -0,0 +1,122 @@
import AxeBuilder from '@axe-core/playwright';
import { expect, test as base, type APIRequestContext, type APIResponse, type Locator, type Page, type TestInfo } from '@playwright/test';
import { translations } from '../src/i18n/translations';
const apiUrl = 'http://localhost:5302/api';
const password = 'E2ePassword123!';
type Language = 'en' | 'nb';
type Headers = Record<string, string>;
type Owner = { id: string; email: string; headers: Headers };
type RequestRecord = { channel: 'browser' | 'api'; method: string; path: string; query: string; status?: number };
type Session = { owner: Owner; admin: APIRequestContext; adminHeaders: Headers; requests: RequestRecord[] };
const boundary = 'Actual isolated API/Identity/CSRF administrators and ordinary owners exercise owned job soft-delete/Restore and authorized cross-owner Admin Audit Undo, persisted readback, unsupported400, foreign ordinary-Restore404 and non-admin403. No account deletion, provider/model/billing/probe/maintenance, production or Phase8 action occurs. The named Audit GET503 is controlled; read Retry does not replay writes. Google Fonts stylesheets are aborted and other nonlocal requests rejected. Named table horizontal scrolling is intentional and keyboard verified; human reader/device/zoom acceptance remains unverified.';
function copy(key: string, language: Language = 'en') { return (translations[language] as Record<string, string>)[key] ?? key; }
function browserRequests(session: Session, path: string, method?: string) { return session.requests.filter(value => value.channel === 'browser' && value.path === `/api${path}` && (!method || value.method === method)); }
async function call(records: RequestRecord[], api: APIRequestContext, method: 'GET' | 'POST' | 'PUT', path: string, headers?: Headers, data?: unknown) {
const result = await api.fetch(`${apiUrl}${path}`, { method, headers, data });
const url = new URL(result.url()); records.push({ channel: 'api', method, path: url.pathname, query: url.search, status: result.status() }); return result;
}
async function json<T>(response: Pick<APIResponse, 'status' | 'url' | 'json'>, status = 200): Promise<T> { expect(response.status(), response.url()).toBe(status); return response.json(); }
async function login(records: RequestRecord[], api: APIRequestContext, email: string): Promise<Owner> {
expect((await call(records, api, 'POST', '/auth/login', undefined, { email, password })).status()).toBe(200);
const me = await json<{ id: string; sessionContext: string }>(await call(records, api, 'GET', '/auth/me'));
const token = (await api.storageState()).cookies.find(value => value.name === 'XSRF-TOKEN'); expect(token).toBeDefined();
return { id: me.id, email, headers: { 'X-CSRF-TOKEN': token!.value, 'X-Session-Context': me.sessionContext } };
}
async function createOwner(records: RequestRecord[], admin: APIRequestContext, headers: Headers) {
const email = `p710-audit-${Date.now()}-${Math.random().toString(36).slice(2)}@example.test`;
expect((await call(records, admin, 'POST', '/users', headers, { email, password, roles: [] })).status()).toBe(200); return email;
}
const test = base.extend<{ session: Session }>({
session: async ({ page, context, playwright }, provide, info) => {
expect(process.env.PLAYWRIGHT_REUSE_SERVERS).not.toBe('true'); expect(info.config.metadata.isolatedDataRoot).toEqual(expect.any(String));
const records: RequestRecord[] = []; const forbidden: string[] = []; const fonts: string[] = []; const admin = await playwright.request.newContext();
context.on('request', request => { const url = new URL(request.url()); records.push({ channel: 'browser', method: request.method(), path: url.pathname, query: url.search }); });
context.on('response', result => { const url = new URL(result.url()); const record = [...records].reverse().find(value => value.channel === 'browser' && value.status === undefined && value.method === result.request().method() && value.path === url.pathname && value.query === url.search); if (record) record.status = result.status(); });
await context.route('**/*', route => {
const request = route.request(); const url = new URL(request.url());
if (url.protocol === 'https:' && url.hostname === 'fonts.googleapis.com' && url.port === '' && url.pathname === '/css2' && request.method() === 'GET' && request.resourceType() === 'stylesheet') { fonts.push(url.href); return route.abort(); }
const mailbox = /^\/api\/(gmail|microsoft-graph|imap)(?:\/|$)/.test(url.pathname);
const statusRead = request.method() === 'GET' && /^\/api\/(gmail|microsoft-graph|imap)\/status$/.test(url.pathname);
const ai = /^\/api\/ai(?:\/|$)/.test(url.pathname); const accountAiRead = request.method() === 'GET' && ['/api/ai/settings', '/api/ai/usage'].includes(url.pathname) || request.method() === 'PUT' && url.pathname === '/api/ai/settings';
if (mailbox && !statusRead || ai && !accountAiRead || /\/api\/(?:email\/send|billing\/(?:checkout|portal)|account-lifecycle\/delete|backup\/restore)(?:\/|$)/.test(url.pathname) || !['blob:', 'data:', 'about:'].includes(url.protocol) && (!['localhost', '127.0.0.1'].includes(url.hostname) || !['3300', '5302'].includes(url.port))) { forbidden.push(`${request.method()} ${url.origin}${url.pathname}`); return route.abort(); }
return route.continue();
});
await context.addInitScript(() => { if (!localStorage.getItem('uiLanguage')) localStorage.setItem('uiLanguage', 'en'); if (!localStorage.getItem('jobtracker.themeMode')) localStorage.setItem('jobtracker.themeMode', 'light'); });
try {
const administrator = await login(records, admin, 'e2e@example.test'); const email = await createOwner(records, admin, administrator.headers); const owner = await login(records, page.request, email);
expect((await json<{ entitlements: { ai: boolean } }>(await call(records, page.request, 'GET', '/auth/me'))).entitlements.ai).toBe(false);
await provide({ owner, admin, adminHeaders: administrator.headers, requests: records }); expect(forbidden).toEqual([]);
} finally { await info.attach('settings-preferences-boundary-and-requests', { body: JSON.stringify({ boundary, requests: records, forbiddenRequests: forbidden, abortedFontStylesheets: fonts }), contentType: 'application/json' }); await admin.dispose(); }
},
});
async function start(page: Page, path = '/settings', width = 1440) { await page.setViewportSize({ width, height: width < 768 ? 844 : 900 }); await page.emulateMedia({ reducedMotion: 'reduce' }); await page.goto(path); await expect(page.getByRole('main').getByRole('heading', { level: 1 })).toBeVisible(); }
async function keyboard(control: Locator) { await expect(control).toBeVisible(); await expect(control).toBeEnabled(); await control.focus(); await expect(control).toBeFocused(); await control.press('Enter'); }
async function capture(page: Page, info: TestInfo, name: string) {
const geometry = await page.getByRole('main').evaluate(main => {
const bounds = main.getBoundingClientRect(); const targets = Array.from(main.querySelectorAll('h1,h2,h3,p,button,input,[role="combobox"],[role="status"],.MuiFormControlLabel-root'));
// MUI Switch uses a transparent 300%-wide native input; its painted label/control remains in the checked targets.
// The named Audit region intentionally scrolls its table; keyboard reachability is tested separately.
return { width: innerWidth, rootOverflow: document.documentElement.scrollWidth - document.documentElement.clientWidth, outside: targets.filter(node => !node.closest('table') && node.getClientRects().length && getComputedStyle(node).visibility !== 'hidden' && !(node instanceof HTMLInputElement && getComputedStyle(node).opacity === '0')).map(node => ({ text: node.textContent?.slice(0, 90), left: node.getBoundingClientRect().left, right: node.getBoundingClientRect().right })).filter(rect => rect.left < bounds.left - 1 || rect.right > Math.min(bounds.right, innerWidth) + 1) };
});
await info.attach(`${name}-reflow`, { body: JSON.stringify(geometry), contentType: 'application/json' }); expect(geometry.rootOverflow).toBeLessThanOrEqual(1); expect(geometry.outside).toEqual([]);
await info.attach(name, { body: await page.screenshot({ fullPage: true, animations: 'disabled' }), contentType: 'image/png' });
const axe = await new AxeBuilder({ page }).analyze(); await info.attach(`${name}-axe`, { body: JSON.stringify({ violations: axe.violations, incomplete: axe.incomplete, qualification: 'All enabled axe rules; raw incomplete contexts retained for root triage, not human screen-reader acceptance.' }), contentType: 'application/json' }); expect(axe.violations).toEqual([]);
}
function response(page: Page, method: string, path: string) { return page.waitForResponse(value => value.request().method()===method && new URL(value.url()).pathname===`/api${path}`); }
type Event = { id: number; type: string; jobApplicationId: number };
async function makeJob(api: APIRequestContext, owner: Owner, title: string) {
const company=await json<{ id: number }>(await api.post(`${apiUrl}/companies`, { headers: owner.headers, data: { name: title+' AS' } }), 201);
return json<{ id: number }>(await api.post(`${apiUrl}/jobapplications`, { headers: owner.headers, data: { companyId: company.id, jobTitle: title, status: 'Saved' } }), 201);
}
async function events(api: APIRequestContext) { return json<Event[]>(await api.get(`${apiUrl}/admin/audit?take=200`)); }
function deletedRow(page: Page, title: string, language: Language='en') { return page.getByRole('row').filter({ hasText: title }).filter({ has: page.getByRole('button', { name: copy('adminAuditRestore', language), exact: true }) }); }
test('[P7-10 Audit A02 E09] persisted authorized Undo differs from ordinary owner-filtered Restore; unsupported and ordinary-user requests stay denied', async ({ page, playwright, session }) => {
const foreignTitle=`Foreign audit fixture ${Date.now()}`; const foreign=await makeJob(page.request, session.owner, foreignTitle);
expect((await page.request.delete(`${apiUrl}/jobapplications/${foreign.id}`, { headers: session.owner.headers })).status()).toBe(204);
const administrator=await login(session.requests, page.request, 'e2e@example.test');
const ownTitle=`Owned audit fixture ${Date.now()}`; const own=await makeJob(page.request, administrator, ownTitle);
expect((await page.request.delete(`${apiUrl}/jobapplications/${own.id}`, { headers: administrator.headers })).status()).toBe(204);
const initial=await events(page.request); const foreignDelete=initial.find(value => value.jobApplicationId===foreign.id && value.type==='Deleted'); expect(foreignDelete).toBeDefined();
const unsupported=initial.find(value => value.jobApplicationId===own.id && value.type==='Created'); expect(unsupported).toBeDefined();
expect((await page.request.post(`${apiUrl}/admin/audit/${unsupported!.id}/undo`, { headers: administrator.headers, data: {} })).status()).toBe(400);
await start(page, '/admin/audit', 390);
const denied=response(page, 'POST', `/jobapplications/${foreign.id}/restore`); await keyboard(deletedRow(page, foreignTitle).getByRole('button', { name: copy('adminAuditRestore'), exact: true })); expect((await denied).status()).toBe(404);
const undone=response(page, 'POST', `/admin/audit/${foreignDelete!.id}/undo`); await keyboard(deletedRow(page, foreignTitle).getByRole('button', { name: copy('adminAuditUndo'), exact: true })); expect((await undone).status()).toBe(200);
const restored=response(page, 'POST', `/jobapplications/${own.id}/restore`); await keyboard(deletedRow(page, ownTitle).getByRole('button', { name: copy('adminAuditRestore'), exact: true })); expect((await restored).status()).toBe(204);
expect((await page.request.get(`${apiUrl}/jobapplications/${own.id}`)).status()).toBe(200);
await page.reload(); await expect(deletedRow(page, ownTitle)).toBeVisible();
const other=await playwright.request.newContext();
try { const owner=await login(session.requests, other, session.owner.email); expect((await other.get(`${apiUrl}/jobapplications/${foreign.id}`)).status()).toBe(200); expect((await other.get(`${apiUrl}/admin/audit?take=200`)).status()).toBe(403); expect((await other.post(`${apiUrl}/admin/audit/${foreignDelete!.id}/undo`, { headers: owner.headers, data: {} })).status()).toBe(403); }
finally { await other.dispose(); }
expect((await events(page.request)).some(value => value.type==='Undo' && value.jobApplicationId===foreign.id)).toBe(true);
});
test('[P7-10 Audit A02 E08] failed read Retry remains GET-only and preserves the named focus target', async ({ page, session }, info) => {
await login(session.requests, page.request, 'e2e@example.test'); let failed=false;
await page.route(`${apiUrl}/admin/audit?take=200`, route => { if (!failed) { failed=true; return route.fulfill({ status: 503, json: { title: 'Controlled Audit unavailable' } }); } return route.continue(); });
await start(page, '/admin/audit', 390); await expect(page.getByRole('alert').filter({ hasText: copy('adminAuditLoadFailed') })).toBeVisible();
await keyboard(page.getByRole('button', { name: copy('retry'), exact: true }));
await expect(page.getByRole('region', { name: copy('adminAuditTitle'), exact: true })).toBeFocused(); await expect(page.getByRole('table', { name: copy('adminAuditTitle'), exact: true })).toBeVisible();
expect(session.requests.filter(value => value.channel==='browser' && value.method!=='GET')).toEqual([]);
await capture(page, info, 'audit-actual-read-recovery-en-light-390');
});
test('[P7-10 Audit A02] finite bilingual theme widths retain long event identity and keyboard table scrolling', async ({ page, session }, info) => {
test.setTimeout(180_000); const administrator=await login(session.requests, page.request, 'e2e@example.test');
const title=`Long owned audit event Æ Ø Å ${Date.now()} `+'International collaboration '.repeat(4); const own=await makeJob(page.request, administrator, title);
expect((await page.request.delete(`${apiUrl}/jobapplications/${own.id}`, { headers: administrator.headers })).status()).toBe(204);
const samples=[{ width: 320, language: 'nb', mode: 'dark' }, { width: 390, language: 'en', mode: 'light' }, { width: 768, language: 'nb', mode: 'light' }, { width: 1024, language: 'en', mode: 'dark' }, { width: 1440, language: 'en', mode: 'light' }, { width: 1920, language: 'nb', mode: 'dark' }] as const;
for (const sample of samples) {
expect((await call(session.requests, page.request, 'PUT', '/auth/preferences/language', administrator.headers, { language: sample.language==='nb' ? 'nb-NO' : 'en' })).status()).toBe(204);
await page.addInitScript(value => { localStorage.setItem('uiLanguage', value.language); localStorage.setItem('jobtracker.themeMode', value.mode); }, sample); await start(page, '/admin/audit', sample.width);
const region=page.getByRole('region', { name: copy('adminAuditTitle', sample.language), exact: true }); await region.focus(); await expect(region).toBeFocused();
const jobColumn=await region.getByRole('columnheader', { name: copy('adminAuditJob', sample.language), exact: true }).boundingBox(); expect(jobColumn).not.toBeNull(); expect(jobColumn!.width).toBeGreaterThanOrEqual(240);
const before=await region.evaluate(node => node.scrollLeft); await region.press('ArrowRight'); if (sample.width<1024) await expect.poll(() => region.evaluate(node => node.scrollLeft)).toBeGreaterThan(before);
await expect(deletedRow(page, title, sample.language)).toBeVisible(); await capture(page, info, `audit-long-event-${sample.width}-${sample.language}-${sample.mode}`);
}
expect(session.requests.filter(value => value.channel==='browser' && value.method!=='GET')).toEqual([]);
});
+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>
);
}