Archived
Audit log: search (person, target, IP), role filter, every action in the filter, inclusive To date. Data requests: search and paging (was cut at 200). Webhook deliveries: status filter and Load older. Supervisor Payments loads only what it needs (unpaid registrations, recent/today/donation payments, a person's own for refunds) instead of everything. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
367 lines
16 KiB
TypeScript
367 lines
16 KiB
TypeScript
"use client";
|
||
|
||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||
import { useAuth } from "@/hooks/useAuth";
|
||
import { useRouter } from "next/navigation";
|
||
import { apiFetch } from "@/lib/api";
|
||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||
import { History } from "lucide-react";
|
||
import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell } from "@/components/ui/table";
|
||
import { errorMessage } from "@/lib/utils";
|
||
import { BackLink } from "@/components/shared/BackLink";
|
||
|
||
const ACTION_LABELS: Record<string, string> = {
|
||
refund_created: "Refund created",
|
||
donation_assigned: "Donation assigned",
|
||
donation_unassigned: "Donation unassigned",
|
||
registration_created_manual: "Manual registration created",
|
||
registration_cancelled: "Registration cancelled (staff)",
|
||
event_created: "Event created",
|
||
event_updated: "Event updated",
|
||
event_deleted: "Event deactivated",
|
||
settings_updated: "Settings updated",
|
||
coupon_created: "Coupon created",
|
||
coupon_updated: "Coupon edited",
|
||
coupon_disabled: "Coupon turned off",
|
||
coupon_applied_manual: "Coupon applied/removed by staff",
|
||
bundle_created: "Bundle deal created",
|
||
bundle_updated: "Bundle deal edited",
|
||
bundle_deleted: "Bundle deal deleted",
|
||
consent_override: "Consent overridden at check-in",
|
||
consent_rerequested: "Consent re-requested",
|
||
medical_list_viewed: "Medical list viewed",
|
||
scan_lock_acquired: "Offline scanning started",
|
||
scan_lock_released: "Offline scanning ended",
|
||
scan_lock_force_released: "Offline lock force-released",
|
||
offline_sync: "Offline scans synced",
|
||
ticket_transferred: "Ticket transferred",
|
||
impersonation_started: "Impersonation started",
|
||
impersonation_ended: "Impersonation ended",
|
||
yoco_config_updated: "Yoco settings changed",
|
||
yoco_webhook_registered: "Yoco webhook registered",
|
||
yoco_webhook_deleted: "Yoco webhook deleted",
|
||
data_request_completed: "Privacy request completed",
|
||
data_request_rejected: "Privacy request rejected/cancelled",
|
||
user_anonymised: "User's personal data deleted",
|
||
privacy_notice_published: "Privacy notice published",
|
||
operator_created: "Operator added",
|
||
operator_updated: "Operator changed",
|
||
operator_deleted: "Operator removed",
|
||
retention_policies_updated: "Retention periods changed",
|
||
retention_run: "Retention job deleted/anonymised data",
|
||
breach_recorded: "Security compromise recorded",
|
||
breach_updated: "Security compromise updated",
|
||
hub_connected: "Connected to the Cross Events Hub",
|
||
hub_update_requested: "Asked the Hub for an update",
|
||
hub_update_request_withdrawn: "Withdrew the update request",
|
||
hub_update_snoozed: "Put off an update (Not now)",
|
||
hub_update_unsnoozed: "Turned update reminders back on",
|
||
campuses_toggled: "Campuses turned on/off",
|
||
campus_created: "Campus added",
|
||
campus_updated: "Campus changed",
|
||
campus_archived: "Campus archived/restored",
|
||
campus_deleted: "Campus deleted",
|
||
event_campus_changed: "Event moved to another campus",
|
||
user_campus_scope_changed: "Staff member limited to campuses",
|
||
kids_settings_updated: "Kids check-in settings changed",
|
||
kids_checkout_override: "Child checked out without the pickup code",
|
||
kids_wrong_code: "Wrong pickup code entered",
|
||
kids_custody_notes_changed: "Child's custody notes changed",
|
||
kids_offline_sync: "Offline kids desk synced",
|
||
volunteer_settings_updated: "Volunteer ticket changed",
|
||
volunteer_roles_changed: "Serving role added, changed or deleted",
|
||
volunteer_assigned: "Volunteer put on a roster",
|
||
volunteer_removed: "Volunteer taken off a roster",
|
||
volunteer_checked_in_manual: "Volunteer checked in by hand",
|
||
series_created: "Event series created",
|
||
series_updated: "Event series changed",
|
||
series_deleted: "Event series deleted",
|
||
season_pass_changed: "Season pass created, changed or deleted",
|
||
registrations_bulk: "Bulk action on registrations",
|
||
attendance_marked: "Attendance marked",
|
||
attendance_unmarked: "Attendance unmarked",
|
||
certificate_issued: "Certificate issued",
|
||
certificate_revoked: "Certificate revoked",
|
||
event_sessions_changed: "Event sessions changed",
|
||
job_run_manual: "Background job run by hand",
|
||
payfast_config_updated: "PayFast settings changed",
|
||
payment_providers_updated: "Payment providers changed",
|
||
webhook_endpoint_changed: "Webhook added, changed or deleted",
|
||
};
|
||
|
||
// Every action that can be logged (keep in step with AdminAuditAction in schema.prisma),
|
||
// sorted by label for the filter.
|
||
const ACTION_OPTIONS = Object.entries(ACTION_LABELS).sort((x, y) => x[1].localeCompare(y[1]));
|
||
|
||
const ROLES = ["admin", "supervisor", "staff"] as const;
|
||
|
||
interface AuditLogEntry {
|
||
id: string;
|
||
actorId: string | null;
|
||
actorRole: string;
|
||
action: string;
|
||
targetType: string;
|
||
targetId: string | null;
|
||
metadata: Record<string, unknown> | null;
|
||
ip: string | null;
|
||
createdAt: string;
|
||
actor: { id: string; name: string; email: string } | null;
|
||
}
|
||
|
||
function formatMetadata(metadata: Record<string, unknown> | null): string {
|
||
if (!metadata) return "";
|
||
try {
|
||
return Object.entries(metadata)
|
||
.filter(([, v]) => v !== null && v !== undefined && v !== "")
|
||
.map(([k, v]) => `${k}: ${Array.isArray(v) ? v.join(", ") : String(v)}`)
|
||
.join(" · ");
|
||
} catch {
|
||
return "";
|
||
}
|
||
}
|
||
|
||
type ImpSession = {
|
||
id: string; reason: string; startedAt: string; expiresAt: string; endedAt: string | null; endedReason: string | null;
|
||
admin: { name: string; email: string }; target: { name: string; email: string };
|
||
requests: { method: string; path: string; blocked: boolean; createdAt: string }[];
|
||
};
|
||
|
||
/** "View as" sessions, each with the trail of pages and API calls made during it. */
|
||
function ImpersonationSessions({ token }: { token: string }) {
|
||
const [sessions, setSessions] = useState<ImpSession[]>([]);
|
||
const [open, setOpen] = useState<string | null>(null);
|
||
useEffect(() => {
|
||
apiFetch<ImpSession[]>("/api/admin/impersonation-sessions?limit=20", { authToken: token }).then(setSessions).catch(() => setSessions([]));
|
||
}, [token]);
|
||
if (sessions.length === 0) return null;
|
||
return (
|
||
<div className="border rounded-xl bg-white shadow-sm p-4 mb-4">
|
||
<div className="font-semibold mb-2">Impersonation sessions</div>
|
||
<ul className="divide-y text-sm">
|
||
{sessions.map(s => (
|
||
<li key={s.id} className="py-2">
|
||
<button className="w-full text-left flex flex-wrap items-baseline justify-between gap-2" onClick={() => setOpen(open === s.id ? null : s.id)}>
|
||
<span><strong>{s.admin.name}</strong> viewed as <strong>{s.target.name}</strong> — “{s.reason}”</span>
|
||
<span className="text-xs text-gray-500">
|
||
{new Date(s.startedAt).toLocaleString()} · {s.endedAt ? `${s.endedReason || "ended"} ${new Date(s.endedAt).toLocaleTimeString()}` : new Date(s.expiresAt) > new Date() ? "active" : "expired"} · {s.requests.length} request(s){s.requests.some(r => r.blocked) ? ` · ${s.requests.filter(r => r.blocked).length} blocked` : ""}
|
||
</span>
|
||
</button>
|
||
{open === s.id && (
|
||
<ul className="mt-2 text-xs font-mono bg-gray-50 rounded p-2 max-h-64 overflow-auto space-y-0.5">
|
||
{s.requests.map((r, i) => (
|
||
<li key={i} className={r.blocked ? "text-red-700" : "text-gray-700"}>
|
||
{new Date(r.createdAt).toLocaleTimeString()} {r.method} {r.path}{r.blocked ? " (blocked — read-only)" : ""}
|
||
</li>
|
||
))}
|
||
{s.requests.length === 0 && <li className="text-gray-500">No requests recorded.</li>}
|
||
</ul>
|
||
)}
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export default function AdminAuditLogPage() {
|
||
const { user, loading, token } = useAuth();
|
||
const router = useRouter();
|
||
|
||
const isAdmin = useMemo(() => user?.role === "admin", [user]);
|
||
|
||
useEffect(() => {
|
||
if (loading) return;
|
||
if (!user) router.replace("/login");
|
||
}, [user, loading, router]);
|
||
|
||
const [entries, setEntries] = useState<AuditLogEntry[]>([]);
|
||
const [fetching, setFetching] = useState(false);
|
||
const [error, setError] = useDismissingState<string | null>(null);
|
||
const [page, setPage] = useState(1);
|
||
const [total, setTotal] = useState(0);
|
||
const pageSize = 50;
|
||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||
|
||
const [actionFilter, setActionFilter] = useState<string>("");
|
||
const [roleFilter, setRoleFilter] = useState<string>("");
|
||
const [searchInput, setSearchInput] = useState<string>("");
|
||
const [search, setSearch] = useState<string>("");
|
||
const [fromFilter, setFromFilter] = useState<string>("");
|
||
const [toFilter, setToFilter] = useState<string>("");
|
||
|
||
const buildQuery = useCallback((p: number) => {
|
||
const qs = new URLSearchParams({ page: String(p), limit: String(pageSize) });
|
||
if (actionFilter) qs.set("action", actionFilter);
|
||
if (roleFilter) qs.set("role", roleFilter);
|
||
if (search) qs.set("search", search);
|
||
if (fromFilter) qs.set("from", fromFilter);
|
||
if (toFilter) qs.set("to", toFilter);
|
||
return `/api/admin/audit-log?${qs.toString()}`;
|
||
}, [actionFilter, roleFilter, search, fromFilter, toFilter]);
|
||
|
||
// Search as you type, once typing pauses.
|
||
useEffect(() => {
|
||
const t = setTimeout(() => setSearch(searchInput.trim()), 350);
|
||
return () => clearTimeout(t);
|
||
}, [searchInput]);
|
||
|
||
const filtered = !!(actionFilter || roleFilter || search || fromFilter || toFilter);
|
||
const clearFilters = () => {
|
||
setActionFilter(""); setRoleFilter(""); setSearchInput(""); setSearch(""); setFromFilter(""); setToFilter("");
|
||
};
|
||
|
||
const load = useCallback(async (p = 1) => {
|
||
if (!token) return;
|
||
setError(null);
|
||
setFetching(true);
|
||
try {
|
||
const res = await apiFetch<{ rows: AuditLogEntry[]; total: number; page: number }>(buildQuery(p), { authToken: token });
|
||
setEntries(res?.rows || []);
|
||
setTotal(res?.total ?? 0);
|
||
setPage(p);
|
||
} catch (e) {
|
||
setError(errorMessage(e) || "Failed to load audit log");
|
||
} finally {
|
||
setFetching(false);
|
||
}
|
||
}, [token, buildQuery, setError]);
|
||
|
||
// load changes whenever a filter does (via buildQuery), so this refetches page 1 on filter changes.
|
||
useEffect(() => { if (token) load(1); }, [token, load]);
|
||
|
||
return (
|
||
<div className="max-w-6xl mx-auto w-full p-6">
|
||
<div className="flex items-center gap-3 mb-4">
|
||
<div className="w-10 h-10 rounded-xl bg-brand-50 flex items-center justify-center shrink-0">
|
||
<History className="w-5 h-5 text-brand-600" />
|
||
</div>
|
||
<div>
|
||
<BackLink href="/dashboard/admin" />
|
||
<h1 className="text-2xl font-semibold text-gray-900 mt-0.5">Admin Audit Log</h1>
|
||
<p className="text-sm text-gray-500">{total} action{total !== 1 ? "s" : ""} {filtered ? "match the filters" : "recorded"}</p>
|
||
</div>
|
||
</div>
|
||
|
||
{!isAdmin && (
|
||
<div className="p-3 border rounded bg-yellow-50 text-yellow-800 text-sm mb-4">
|
||
You need admin access to view the audit log.
|
||
</div>
|
||
)}
|
||
{isAdmin && token && <ImpersonationSessions token={token} />}
|
||
|
||
{error && <div role="alert" className="mb-3 p-3 border rounded bg-red-50 text-red-800 text-sm">{error}</div>}
|
||
|
||
<div className="border rounded-xl p-4 bg-white shadow-sm">
|
||
<div className="flex flex-wrap items-end gap-3 mb-4">
|
||
<div className="flex-1 min-w-[14rem]">
|
||
<label htmlFor="audit-search" className="block text-xs text-gray-600 mb-1">Search</label>
|
||
<input
|
||
id="audit-search"
|
||
type="search"
|
||
className="w-full border rounded px-2 py-1.5 text-sm"
|
||
placeholder="Person, target (e.g. Event or #id) or IP"
|
||
value={searchInput}
|
||
onChange={e => setSearchInput(e.target.value)}
|
||
/>
|
||
</div>
|
||
<div>
|
||
<label htmlFor="audit-action" className="block text-xs text-gray-600 mb-1">Action</label>
|
||
<select id="audit-action" className="border rounded px-2 py-1.5 text-sm max-w-[16rem]" value={actionFilter} onChange={e => setActionFilter(e.target.value)}>
|
||
<option value="">All actions</option>
|
||
{ACTION_OPTIONS.map(([a, label]) => <option key={a} value={a}>{label}</option>)}
|
||
</select>
|
||
</div>
|
||
<div>
|
||
<label htmlFor="audit-role" className="block text-xs text-gray-600 mb-1">Role</label>
|
||
<select id="audit-role" className="border rounded px-2 py-1.5 text-sm" value={roleFilter} onChange={e => setRoleFilter(e.target.value)}>
|
||
<option value="">Any role</option>
|
||
{ROLES.map(r => <option key={r} value={r} className="capitalize">{r[0].toUpperCase() + r.slice(1)}</option>)}
|
||
</select>
|
||
</div>
|
||
<div>
|
||
<label htmlFor="audit-from" className="block text-xs text-gray-600 mb-1">From</label>
|
||
<input id="audit-from" type="date" className="border rounded px-2 py-1.5 text-sm" value={fromFilter} onChange={e => setFromFilter(e.target.value)} />
|
||
</div>
|
||
<div>
|
||
<label htmlFor="audit-to" className="block text-xs text-gray-600 mb-1">To</label>
|
||
<input id="audit-to" type="date" className="border rounded px-2 py-1.5 text-sm" value={toFilter} min={fromFilter || undefined} onChange={e => setToFilter(e.target.value)} />
|
||
</div>
|
||
{filtered && (
|
||
<button className="text-sm px-2 py-1.5 rounded text-brand-700 hover:bg-brand-50" onClick={clearFilters}>
|
||
Clear filters
|
||
</button>
|
||
)}
|
||
<button className="text-sm px-2 py-1.5 rounded bg-gray-100 hover:bg-gray-200" onClick={() => load(page)} disabled={fetching}>
|
||
{fetching ? "Refreshing…" : "Refresh"}
|
||
</button>
|
||
</div>
|
||
|
||
<Table>
|
||
<TableHeader>
|
||
<TableRow>
|
||
<TableHead>When</TableHead>
|
||
<TableHead>Actor</TableHead>
|
||
<TableHead>Action</TableHead>
|
||
<TableHead>Target</TableHead>
|
||
<TableHead>Details</TableHead>
|
||
</TableRow>
|
||
</TableHeader>
|
||
<TableBody>
|
||
{entries.map(e => (
|
||
<TableRow key={e.id}>
|
||
<TableCell className="whitespace-nowrap text-gray-600">{new Date(e.createdAt).toLocaleString()}</TableCell>
|
||
<TableCell>
|
||
{e.actor ? (
|
||
<>
|
||
<div className="font-medium">{e.actor.name}</div>
|
||
<div className="text-xs text-gray-500">{e.actor.email}</div>
|
||
</>
|
||
) : (
|
||
<span className="text-gray-500 italic">Deleted user</span>
|
||
)}
|
||
<div className="text-xs text-gray-500 capitalize">{e.actorRole}</div>
|
||
</TableCell>
|
||
<TableCell>{ACTION_LABELS[e.action] || e.action}</TableCell>
|
||
<TableCell className="text-xs text-gray-600">{e.targetType}{e.targetId ? ` #${e.targetId.slice(0, 8)}` : ""}</TableCell>
|
||
<TableCell className="text-xs text-gray-500 max-w-[280px] truncate" title={formatMetadata(e.metadata)}>{formatMetadata(e.metadata)}</TableCell>
|
||
</TableRow>
|
||
))}
|
||
{entries.length === 0 && !fetching && (
|
||
<TableRow>
|
||
<TableCell colSpan={5} className="text-gray-500">No matching audit entries.</TableCell>
|
||
</TableRow>
|
||
)}
|
||
{fetching && (
|
||
<TableRow>
|
||
<TableCell colSpan={5} className="text-gray-500">Loading…</TableCell>
|
||
</TableRow>
|
||
)}
|
||
</TableBody>
|
||
</Table>
|
||
|
||
{totalPages > 1 && (
|
||
<div className="flex items-center justify-between mt-4 text-sm">
|
||
<span className="text-gray-500">{(page - 1) * pageSize + 1}–{Math.min(page * pageSize, total)} of {total} · page {page} of {totalPages}</span>
|
||
<div className="flex gap-1">
|
||
<button
|
||
className="px-2 py-1 rounded bg-gray-100 hover:bg-gray-200 disabled:opacity-40"
|
||
disabled={page <= 1 || fetching}
|
||
onClick={() => load(page - 1)}
|
||
>
|
||
← Prev
|
||
</button>
|
||
<button
|
||
className="px-2 py-1 rounded bg-gray-100 hover:bg-gray-200 disabled:opacity-40"
|
||
disabled={page >= totalPages || fetching}
|
||
onClick={() => load(page + 1)}
|
||
>
|
||
Next →
|
||
</button>
|
||
</div>
|
||
</div>
|
||
)}
|
||
</div>
|
||
</div>
|
||
);
|
||
}
|