import { useMemo, useState } from "react"; import { useQuery } from "@tanstack/react-query"; import type { ColumnDef } from "@tanstack/react-table"; import { History, Search, RotateCcw, Eye } from "lucide-react"; import { auditApi, type AuditLogItem } from "@/api/audit"; import { usersApi } from "@/api/masters"; import { formatDateTime } from "@/lib/format"; import { cn } from "@/lib/utils"; import { DataTable } from "@/components/DataTable"; import { Button } from "@/components/ui/button"; import { Modal } from "@/components/ui/dialog"; const ENTITY_TYPES = [ { value: "", label: "All Entity Types" }, { value: "asset", label: "Asset" }, { value: "complaint", label: "Complaint" }, { value: "pm_schedule", label: "PM Schedule" }, { value: "pm_record", label: "PM Record" }, { value: "calibration_plan", label: "Calibration Plan" }, { value: "calibration_record", label: "Calibration Record" }, { value: "contract", label: "Contract" }, { value: "warranty", label: "Warranty" }, { value: "insurance_policy", label: "Insurance Policy" }, { value: "demo_equipment", label: "Demo Equipment" }, { value: "department_visit", label: "Department Visit" }, { value: "attachment", label: "Attachment" }, { value: "setting", label: "Setting" }, { value: "user", label: "User" }, { value: "department", label: "Department" }, { value: "location", label: "Location" }, { value: "category", label: "Category" }, { value: "vendor", label: "Vendor" }, ]; const ACTIONS = [ { value: "", label: "All Actions" }, { value: "create", label: "Create" }, { value: "update", label: "Update" }, { value: "delete", label: "Delete" }, { value: "status_change", label: "Status Change" }, { value: "complete", label: "Complete" }, { value: "reschedule", label: "Reschedule" }, { value: "renew", label: "Renew" }, { value: "return", label: "Return" }, { value: "login", label: "Login" }, ]; function ActionBadge({ action }: { action: string }) { const lower = action.toLowerCase(); let cls = "bg-slate-100 text-slate-700 border-slate-200"; if (lower.includes("create") || lower.includes("upload")) { cls = "bg-green-100 text-green-800 border-green-200"; } else if (lower.includes("delete") || lower.includes("deactivate") || lower.includes("remove")) { cls = "bg-red-100 text-red-800 border-red-200"; } else if ( lower.includes("update") || lower.includes("status") || lower.includes("reschedule") ) { cls = "bg-blue-100 text-blue-800 border-blue-200"; } else if ( lower.includes("complete") || lower.includes("renew") || lower.includes("return") || lower.includes("approve") ) { cls = "bg-emerald-100 text-emerald-800 border-emerald-200"; } return ( {action.replace(/_/g, " ")} ); } function summarizeChanges(changesJson: string | null): string { if (!changesJson) return "—"; try { const parsed = JSON.parse(changesJson); if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { const keys = Object.keys(parsed); if (keys.length === 0) return "—"; const preview = keys .slice(0, 3) .map((k) => { const val = (parsed as Record)[k]; if (val && typeof val === "object" && "old" in val && "new" in val) { const pair = val as { old: unknown; new: unknown }; return `${k}: ${String(pair.old ?? "∅")} → ${String(pair.new ?? "∅")}`; } const str = typeof val === "string" ? val : JSON.stringify(val); return `${k}: ${str}`; }) .join(", "); return keys.length > 3 ? `${preview} (+${keys.length - 3} more)` : preview; } return String(parsed); } catch { return changesJson.length > 90 ? `${changesJson.slice(0, 90)}…` : changesJson; } } function formatJsonPretty(changesJson: string | null): string { if (!changesJson) return "No payload recorded."; try { return JSON.stringify(JSON.parse(changesJson), null, 2); } catch { return changesJson; } } export function AuditLogsPage() { const [entityType, setEntityType] = useState(""); const [byUserId, setByUserId] = useState(""); const [action, setAction] = useState(""); const [dateFrom, setDateFrom] = useState(""); const [dateTo, setDateTo] = useState(""); const [q, setQ] = useState(""); const [selectedEntry, setSelectedEntry] = useState(null); const usersQuery = useQuery({ queryKey: ["users", "audit-filter"], queryFn: () => usersApi.list(true), }); const logsQuery = useQuery({ queryKey: [ "audit-logs", entityType, byUserId, action, dateFrom, dateTo, q, ], queryFn: () => auditApi.list({ entity_type: entityType || undefined, by_user_id: byUserId ? Number(byUserId) : undefined, action: action || undefined, date_from: dateFrom || undefined, date_to: dateTo || undefined, q: q.trim() || undefined, page_size: 200, }), }); const hasFilters = Boolean( entityType || byUserId || action || dateFrom || dateTo || q.trim() ); function handleReset() { setEntityType(""); setByUserId(""); setAction(""); setDateFrom(""); setDateTo(""); setQ(""); } const columns = useMemo[]>( () => [ { accessorKey: "at", header: "Timestamp", cell: ({ getValue }) => ( {formatDateTime(getValue() as string)} ), }, { id: "user", accessorFn: (r) => r.by_user_name ?? `User #${r.by_user_id ?? "System"}`, header: "User", cell: ({ row }) => ( {row.original.by_user_name || (row.original.by_user_id != null ? `User #${row.original.by_user_id}` : "System")} ), }, { accessorKey: "entity_type", header: "Entity Type", cell: ({ getValue }) => ( {String(getValue() ?? "")} ), }, { accessorKey: "entity_id", header: "Entity ID", cell: ({ getValue }) => ( #{String(getValue() ?? "")} ), }, { accessorKey: "action", header: "Action", cell: ({ getValue }) => , }, { id: "changes", accessorFn: (r) => r.changes_json ?? "", header: "Changes", cell: ({ row }) => { const summary = summarizeChanges(row.original.changes_json); return ( {summary} {row.original.changes_json && ( { e.stopPropagation(); setSelectedEntry(row.original); }} aria-label={`View JSON changes for audit entry ${row.original.id}`} className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium text-[#1e3a8a] hover:bg-blue-50 border border-blue-200 shrink-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500" > JSON )} ); }, }, ], [] ); const items = logsQuery.data?.items ?? []; const total = logsQuery.data?.total ?? items.length; const users = usersQuery.data?.items ?? []; return ( {/* Header */} Audit Log {total} {total === 1 ? "entry" : "entries"} Track system-wide creations, updates, status transitions, and deletions. {/* Filter Bar */} Search setQ(e.target.value)} placeholder="Search entity ID, action, changes..." className="w-full pl-8 pr-3 py-1.5 text-xs border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" /> Entity Type setEntityType(e.target.value)} className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500" > {ENTITY_TYPES.map((opt) => ( {opt.label} ))} User setByUserId(e.target.value)} className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500" > All Users {users.map((u) => ( {u.name} ))} Action setAction(e.target.value)} className="w-full px-2.5 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500" > {ACTIONS.map((opt) => ( {opt.label} ))} From setDateFrom(e.target.value)} className="w-full px-2 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500" /> To setDateTo(e.target.value)} className="w-full px-2 py-1.5 text-xs border border-gray-300 rounded-md bg-white focus:outline-none focus:ring-2 focus:ring-blue-500" /> {hasFilters && ( Reset filters )} {/* Table */} {/* JSON Diff Modal */} !o && setSelectedEntry(null)} title={ selectedEntry ? `Audit Entry #${selectedEntry.id} — ${selectedEntry.entity_type} #${selectedEntry.entity_id}` : "Audit Entry Details" } description={ selectedEntry ? `${selectedEntry.action.replace(/_/g, " ")} by ${ selectedEntry.by_user_name || "System" } at ${formatDateTime(selectedEntry.at)}` : undefined } className="max-w-2xl" > {selectedEntry && ( {formatJsonPretty(selectedEntry.changes_json)} setSelectedEntry(null)} > Close )} ); }
Track system-wide creations, updates, status transitions, and deletions.
{formatJsonPretty(selectedEntry.changes_json)}