Files
poona-ams/frontend/src/pages/AuditLogsPage.tsx
T

461 lines
16 KiB
TypeScript

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 (
<span
className={cn(
"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border whitespace-nowrap capitalize",
cls
)}
>
{action.replace(/_/g, " ")}
</span>
);
}
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<string, unknown>)[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<AuditLogItem | null>(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<ColumnDef<AuditLogItem, unknown>[]>(
() => [
{
accessorKey: "at",
header: "Timestamp",
cell: ({ getValue }) => (
<span className="whitespace-nowrap text-xs text-gray-700">
{formatDateTime(getValue() as string)}
</span>
),
},
{
id: "user",
accessorFn: (r) => r.by_user_name ?? `User #${r.by_user_id ?? "System"}`,
header: "User",
cell: ({ row }) => (
<span className="text-sm font-medium text-gray-900">
{row.original.by_user_name ||
(row.original.by_user_id != null
? `User #${row.original.by_user_id}`
: "System")}
</span>
),
},
{
accessorKey: "entity_type",
header: "Entity Type",
cell: ({ getValue }) => (
<span className="inline-flex items-center px-2 py-0.5 rounded bg-gray-100 text-gray-700 font-mono text-xs">
{String(getValue() ?? "")}
</span>
),
},
{
accessorKey: "entity_id",
header: "Entity ID",
cell: ({ getValue }) => (
<span className="font-mono text-xs text-gray-700">
#{String(getValue() ?? "")}
</span>
),
},
{
accessorKey: "action",
header: "Action",
cell: ({ getValue }) => <ActionBadge action={String(getValue() ?? "")} />,
},
{
id: "changes",
accessorFn: (r) => r.changes_json ?? "",
header: "Changes",
cell: ({ row }) => {
const summary = summarizeChanges(row.original.changes_json);
return (
<div className="flex items-center justify-between gap-2 max-w-md">
<span className="text-xs text-gray-600 truncate" title={summary}>
{summary}
</span>
{row.original.changes_json && (
<button
type="button"
onClick={(e) => {
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"
>
<Eye className="h-3 w-3" />
JSON
</button>
)}
</div>
);
},
},
],
[]
);
const items = logsQuery.data?.items ?? [];
const total = logsQuery.data?.total ?? items.length;
const users = usersQuery.data?.items ?? [];
return (
<div className="space-y-5">
{/* Header */}
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<div className="flex items-center gap-2">
<History className="h-6 w-6 text-[#1e3a8a]" />
<h1 className="text-2xl font-bold text-gray-900">Audit Log</h1>
<span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-[#1e3a8a] border border-blue-200">
{total} {total === 1 ? "entry" : "entries"}
</span>
</div>
<p className="text-sm text-gray-500 mt-0.5">
Track system-wide creations, updates, status transitions, and deletions.
</p>
</div>
</div>
{/* Filter Bar */}
<div className="bg-white border border-gray-200 rounded-lg p-3.5 shadow-sm">
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-2.5 items-end">
<div className="lg:col-span-2">
<label
htmlFor="audit-search"
className="block text-xs font-medium text-gray-600 mb-1"
>
Search
</label>
<div className="relative">
<Search className="h-3.5 w-3.5 text-gray-400 absolute left-2.5 top-1/2 -translate-y-1/2" />
<input
id="audit-search"
type="text"
aria-label="Search audit logs"
value={q}
onChange={(e) => 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"
/>
</div>
</div>
<div>
<label
htmlFor="audit-entity-type"
className="block text-xs font-medium text-gray-600 mb-1"
>
Entity Type
</label>
<select
id="audit-entity-type"
aria-label="Filter by Entity Type"
value={entityType}
onChange={(e) => 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) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
<div>
<label
htmlFor="audit-user"
className="block text-xs font-medium text-gray-600 mb-1"
>
User
</label>
<select
id="audit-user"
aria-label="Filter by User"
value={byUserId}
onChange={(e) => 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"
>
<option value="">All Users</option>
{users.map((u) => (
<option key={u.id} value={String(u.id)}>
{u.name}
</option>
))}
</select>
</div>
<div>
<label
htmlFor="audit-action"
className="block text-xs font-medium text-gray-600 mb-1"
>
Action
</label>
<select
id="audit-action"
aria-label="Filter by Action"
value={action}
onChange={(e) => 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) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
<div className="flex items-end gap-1.5">
<div className="flex-1 min-w-0">
<label
htmlFor="audit-date-from"
className="block text-xs font-medium text-gray-600 mb-1"
>
From
</label>
<input
id="audit-date-from"
type="date"
aria-label="Date from"
value={dateFrom}
onChange={(e) => 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"
/>
</div>
<div className="flex-1 min-w-0">
<label
htmlFor="audit-date-to"
className="block text-xs font-medium text-gray-600 mb-1"
>
To
</label>
<input
id="audit-date-to"
type="date"
aria-label="Date to"
value={dateTo}
onChange={(e) => 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"
/>
</div>
</div>
</div>
{hasFilters && (
<div className="mt-2.5 flex justify-end">
<Button
type="button"
variant="ghost"
size="sm"
onClick={handleReset}
className="text-xs h-7 px-2.5"
>
<RotateCcw className="h-3.5 w-3.5 mr-1" />
Reset filters
</Button>
</div>
)}
</div>
{/* Table */}
<DataTable
data={items}
columns={columns}
loading={logsQuery.isLoading}
globalFilterPlaceholder="Quick filter loaded audit entries..."
exportFilename="audit-logs"
emptyMessage="No audit log entries match your selected filters."
/>
{/* JSON Diff Modal */}
<Modal
open={Boolean(selectedEntry)}
onOpenChange={(o) => !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 && (
<div className="space-y-3">
<pre className="rounded-md bg-gray-900 text-gray-100 p-4 text-xs overflow-x-auto max-h-96 font-mono leading-relaxed">
{formatJsonPretty(selectedEntry.changes_json)}
</pre>
<div className="flex justify-end">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setSelectedEntry(null)}
>
Close
</Button>
</div>
</div>
)}
</Modal>
</div>
);
}