Files
jobtrackingapp/job-tracker-ui/src/views/AdminAuditPage.tsx
T

184 lines
8.1 KiB
TypeScript

import React, { useEffect, useRef, useState } from "react";
import {
Box,
Button,
Chip,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Typography,
} from "@mui/material";
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;
type: string;
oldValue?: string | null;
newValue?: string | null;
note?: string | null;
at: string;
jobApplicationId: number;
jobTitle?: string | null;
companyName?: string | null;
ownerUserId?: string | null;
ownerEmail?: string | null;
ownerUserName?: string | null;
};
function canUndo(type: string) {
return ["StatusChanged", "FollowUpSet", "ResponseUpdated", "Deleted", "Restored"].includes(type);
}
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: fallback.current },
);
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 }>(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 (error) {
if (active()) toast(getApiErrorMessage(error, currentTranslation.current(action === "undo" ? "adminAuditUndoFailed" : "adminAuditRestoreFailed")), "error");
} finally {
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 (
<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={error}
title={t("adminAuditLoadFailed")}
description={t("adminAuditLoadFailedBody")}
onRetry={async () => { body.current?.focus(); await auditResource.reload(); }}
/>
{!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 sx={{ minWidth: 260 }}>{t("adminAuditJob")}</TableCell>
<TableCell sx={{ width: 220 }}>{t("adminAuditUser")}</TableCell>
<TableCell sx={{ minWidth: 220 }}>{t("adminAuditDetails")}</TableCell>
<TableCell sx={{ width: 170 }}>{t("adminAuditActions")}</TableCell>
</TableRow>
</TableHead>
<TableBody>
{auditResource.loading ? (
<TableRow>
<TableCell colSpan={6}>
<Typography sx={{ color: "text.secondary" }}>{t("loading")}</Typography>
</TableCell>
</TableRow>
) : rows.length === 0 ? (
<TableRow>
<TableCell colSpan={6}>
<Typography sx={{ color: "text.secondary" }}>{t("adminAuditNoEvents")}</Typography>
</TableCell>
</TableRow>
) : (
rows.map((e) => {
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 !== null;
const showRestore = e.type === "Deleted";
return (
<TableRow key={e.id} hover>
<TableCell>{e.at ? new Date(e.at).toLocaleString(language === "nb" ? "nb-NO" : "en-GB") : ""}</TableCell>
<TableCell>
<Chip label={e.type} size="small" variant="outlined" />
</TableCell>
<TableCell>
<Typography sx={{ fontWeight: 800, lineHeight: 1.25 }}>
{e.companyName ? `${e.companyName} - ` : ""}
{jobLabel}
</Typography>
<Typography variant="caption" sx={{ color: "text.secondary" }}>
jobId={e.jobApplicationId}
</Typography>
</TableCell>
<TableCell>
<Typography sx={{ fontWeight: 700 }}>{ownerLabel}</Typography>
</TableCell>
<TableCell>
<Typography sx={{ whiteSpace: "pre-wrap", color: "text.secondary" }}>
{details}
{e.note ? `${details ? "\n" : ""}${e.note}` : ""}
</Typography>
</TableCell>
<TableCell>
<Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
{canUndo(e.type) ? (
<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 mutate(e, "restore")}>
{t("adminAuditRestore")}
</Button>
) : null}
</Box>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</TableContainer> : null}
</Box>
</PageSection>
</Box>
);
}