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

230 lines
11 KiB
TypeScript

import React, { useEffect, useRef, useState } from "react";
import {
Box,
Button,
Chip,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
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 { 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 [search, setSearch] = useState("");
const [eventType, setEventType] = useState("");
const [fromDate, setFromDate] = useState("");
const [throughDate, setThroughDate] = useState("");
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 query = search.trim().toLowerCase();
const eventTypes = [...new Set(auditResource.data.map(event => event.type))].sort();
if (eventType && !eventTypes.includes(eventType)) eventTypes.push(eventType);
const fromTime = fromDate ? new Date(`${fromDate}T00:00:00`).getTime() : -Infinity;
const throughTime = throughDate ? new Date(`${throughDate}T23:59:59.999`).getTime() : Infinity;
const invalidRange = Boolean(fromDate && throughDate && fromDate > throughDate);
const filtering = Boolean(query || eventType || fromDate || throughDate);
const rows = filtering ? auditResource.data.filter(e => {
if (eventType && e.type !== eventType) return false;
if (fromDate || throughDate) {
const time = Date.parse(e.at);
if (!(time >= fromTime && time <= throughTime)) return false;
}
return !query || String(e.jobApplicationId) === query ||
[e.type, e.jobTitle, e.companyName, e.ownerUserId, e.ownerEmail, e.ownerUserName]
.some(value => value?.toLowerCase().includes(query));
}) : 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 }}>
<PageSection title={t("adminAuditEvents")}>
{!auditResource.error && auditResource.data.length > 0 && (
<Box sx={{ display: "grid", gap: 1.5, mb: 2 }}>
<TextField
type="search"
size="small"
label={t("adminAuditSearch")}
helperText={t("adminAuditSearchScope")}
value={search}
onChange={event => setSearch(event.target.value)}
sx={{ width: "100%", maxWidth: 480 }}
/>
<Box sx={{ display: "grid", gridTemplateColumns: { xs: "1fr", sm: "repeat(3, minmax(0, 1fr))" }, gap: 1.5 }}>
<TextField select size="small" label={t("adminAuditEventType")} value={eventType} onChange={event => setEventType(event.target.value)} slotProps={{ select: { native: true }, inputLabel: { shrink: true } }}>
<option value="">{t("adminAuditAllEventTypes")}</option>
{eventTypes.map(type => <option key={type} value={type}>{type}</option>)}
</TextField>
<TextField type="date" size="small" label={t("adminAuditFromDate")} value={fromDate} onChange={event => setFromDate(event.target.value)} slotProps={{ inputLabel: { shrink: true } }} />
<TextField type="date" size="small" label={t("adminAuditThroughDate")} value={throughDate} onChange={event => setThroughDate(event.target.value)} slotProps={{ inputLabel: { shrink: true } }} error={invalidRange} helperText={invalidRange ? t("adminAuditInvalidRange") : undefined} />
</Box>
</Box>
)}
<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 && filtering && auditResource.data.length > 0 && rows.length === 0 ? (
!invalidRange && <Typography role="status" sx={{ color: "text.secondary" }}>{t("adminAuditNoMatches")}</Typography>
) : !auditResource.error ? <TableContainer sx={{ overflow: "visible" }}>
<Table size="small" aria-label={t("adminAuditTitle")} sx={{ minWidth: 1200, "& th, & td": { overflowWrap: "anywhere" }, "& button": { whiteSpace: "normal", "@media (pointer: coarse)": { minHeight: 44 } } }}>
<TableHead>
<TableRow>
<TableCell sx={{ width: 165, minWidth: 136 }}>{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 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>
{e.oldValue || e.newValue || e.note ? (
<Box component="details" sx={{ color: "text.secondary" }}>
<Box component="summary" sx={{ cursor: "pointer", py: 0.75, "@media (pointer: coarse)": { minHeight: 44 } }}>{t("adminAuditEventDetails")}</Box>
{e.oldValue && <Typography variant="body2"><strong>{t("adminAuditPreviousValue")}</strong> {e.oldValue}</Typography>}
{e.newValue && <Typography variant="body2"><strong>{t("adminAuditNewValue")}</strong> {e.newValue}</Typography>}
{e.note && <Typography variant="body2" sx={{ whiteSpace: "pre-wrap" }}>{e.note}</Typography>}
</Box>
) : "—"}
</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>
);
}