feat: Activity History system — full audit coverage, UI, AI tools
Infrastructure (Phase 1): - AuditLog schema: add source, entityName, summary fields + index - createAuditEntry() helper: auto-diff, auto-summary, fire-and-forget - auditLog query router: list, getByEntity, getTimeline, getActivitySummary Audit Coverage (Phase 2 — 14 routers, 50+ mutations): - vacation: create, approve, reject, cancel, batch ops (8 mutations) - user: create, updateRole, setPermissions, resetPermissions (5 mutations) - entitlement: set, bulkSet (3 mutations) - client: create, update, delete, batchUpdateSortOrder - org-unit: create, update, deactivate - country: create, update, createCity, updateCity, deleteCity - management-level: createGroup, updateGroup, createLevel, updateLevel, deleteLevel - settings: updateSystemSettings (sensitive fields sanitized), testSmtp - blueprint: create, update, updateRolePresets, delete, batchDelete, setGlobal - rate-card: create, update, deactivate, addLine, updateLine, deleteLine, replaceLines - calculation-rules: create, update, delete - effort-rule: create, update, delete - experience-multiplier: create, update, delete - utilization-category: create, update Admin UI (Phase 3): - /admin/activity-log page with global searchable timeline - Filters: entity type, action, user, date range, text search - Expandable before/after diff view per entry - Summary cards showing top entity types by change count - EntityHistory reusable component for entity detail pages - Sidebar nav link with clock icon AI Assistant (Phase 4): - query_change_history tool: "Who changed project X?" - get_entity_timeline tool: "What happened to resource Y?" Regression: 283 engine + 37 staffing tests pass. TypeScript clean. Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
import { ActivityLogClient } from "~/components/admin/ActivityLogClient.js";
|
||||
|
||||
export default function ActivityLogPage() {
|
||||
return <ActivityLogClient />;
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useMemo, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import type { Route } from "next";
|
||||
import { trpc } from "~/lib/trpc/client.js";
|
||||
|
||||
// ─── Constants ──────────────────────────────────────────────────────────────
|
||||
|
||||
const ACTION_BADGES: Record<string, { label: string; className: string }> = {
|
||||
CREATE: { label: "Create", className: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-400" },
|
||||
UPDATE: { label: "Update", className: "bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-400" },
|
||||
DELETE: { label: "Delete", className: "bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-400" },
|
||||
SHIFT: { label: "Shift", className: "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400" },
|
||||
IMPORT: { label: "Import", className: "bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-400" },
|
||||
};
|
||||
|
||||
const ENTITY_TYPE_OPTIONS = [
|
||||
"Project",
|
||||
"Resource",
|
||||
"Allocation",
|
||||
"Blueprint",
|
||||
"Vacation",
|
||||
"Role",
|
||||
"Estimate",
|
||||
"EstimateVersion",
|
||||
"ScopeItem",
|
||||
"DemandLine",
|
||||
"Comment",
|
||||
];
|
||||
|
||||
const ACTION_OPTIONS = ["CREATE", "UPDATE", "DELETE", "SHIFT", "IMPORT"];
|
||||
|
||||
const ENTITY_LINKS: Record<string, (id: string) => string> = {
|
||||
Project: (id) => `/projects/${id}`,
|
||||
Resource: (id) => `/resources/${id}`,
|
||||
Allocation: (id) => `/allocations?allocationId=${id}`,
|
||||
Blueprint: (_id) => `/admin/blueprints`,
|
||||
Vacation: (_id) => `/vacations`,
|
||||
Role: (_id) => `/roles`,
|
||||
Estimate: (id) => `/estimates/${id}`,
|
||||
};
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
function relativeTime(date: Date): string {
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - new Date(date).getTime();
|
||||
const diffSec = Math.floor(diffMs / 1000);
|
||||
const diffMin = Math.floor(diffSec / 60);
|
||||
const diffHr = Math.floor(diffMin / 60);
|
||||
const diffDays = Math.floor(diffHr / 24);
|
||||
|
||||
if (diffSec < 60) return "just now";
|
||||
if (diffMin < 60) return `${diffMin}m ago`;
|
||||
if (diffHr < 24) return `${diffHr}h ago`;
|
||||
if (diffDays < 7) return `${diffDays}d ago`;
|
||||
return new Date(date).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric" });
|
||||
}
|
||||
|
||||
function userInitials(name: string | null | undefined, email: string): string {
|
||||
if (name) {
|
||||
const parts = name.trim().split(/\s+/);
|
||||
if (parts.length >= 2) return (parts[0]![0]! + parts[parts.length - 1]![0]!).toUpperCase();
|
||||
return name.slice(0, 2).toUpperCase();
|
||||
}
|
||||
return email.slice(0, 2).toUpperCase();
|
||||
}
|
||||
|
||||
type DiffEntry = { old: unknown; new: unknown };
|
||||
type Changes = {
|
||||
before?: Record<string, unknown>;
|
||||
after?: Record<string, unknown>;
|
||||
diff?: Record<string, DiffEntry>;
|
||||
metadata?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
function parseChanges(changes: unknown): Changes {
|
||||
if (!changes || typeof changes !== "object") return {};
|
||||
return changes as Changes;
|
||||
}
|
||||
|
||||
function formatValue(val: unknown): string {
|
||||
if (val === null || val === undefined) return "(empty)";
|
||||
if (typeof val === "boolean") return val ? "Yes" : "No";
|
||||
if (typeof val === "object") return JSON.stringify(val);
|
||||
return String(val);
|
||||
}
|
||||
|
||||
// ─── Sub-components ─────────────────────────────────────────────────────────
|
||||
|
||||
function ActionBadge({ action }: { action: string }) {
|
||||
const badge = ACTION_BADGES[action] ?? { label: action, className: "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400" };
|
||||
return (
|
||||
<span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${badge.className}`}>
|
||||
{badge.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function DiffView({ changes }: { changes: Changes }) {
|
||||
const diff = changes.diff;
|
||||
if (!diff || Object.keys(diff).length === 0) {
|
||||
return <p className="text-sm text-gray-500 dark:text-gray-400">No field-level diff available.</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
{Object.entries(diff).map(([field, { old: oldVal, new: newVal }]) => (
|
||||
<div key={field} className="flex items-start gap-2 text-sm">
|
||||
<span className="min-w-[120px] shrink-0 font-medium text-gray-700 dark:text-gray-300">{field}</span>
|
||||
<span className="rounded bg-red-50 px-1.5 py-0.5 text-red-700 line-through dark:bg-red-900/20 dark:text-red-400">
|
||||
{formatValue(oldVal)}
|
||||
</span>
|
||||
<span className="text-gray-400">→</span>
|
||||
<span className="rounded bg-emerald-50 px-1.5 py-0.5 text-emerald-700 dark:bg-emerald-900/20 dark:text-emerald-400">
|
||||
{formatValue(newVal)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SummaryCards({ summary }: { summary: { byEntityType: Record<string, number>; total: number } }) {
|
||||
const sorted = useMemo(() => {
|
||||
return Object.entries(summary.byEntityType)
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.slice(0, 5);
|
||||
}, [summary.byEntityType]);
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-800">
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">Total (7d)</p>
|
||||
<p className="mt-1 text-2xl font-bold text-gray-900 dark:text-white">{summary.total}</p>
|
||||
</div>
|
||||
{sorted.map(([type, count]) => (
|
||||
<div key={type} className="rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-800">
|
||||
<p className="text-xs font-medium uppercase tracking-wide text-gray-500 dark:text-gray-400">{type}</p>
|
||||
<p className="mt-1 text-2xl font-bold text-gray-900 dark:text-white">{count}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Main Component ─────────────────────────────────────────────────────────
|
||||
|
||||
export function ActivityLogClient() {
|
||||
// Filters
|
||||
const [entityType, setEntityType] = useState("");
|
||||
const [action, setAction] = useState("");
|
||||
const [userId, setUserId] = useState("");
|
||||
const [search, setSearch] = useState("");
|
||||
const [startDate, setStartDate] = useState("");
|
||||
const [endDate, setEndDate] = useState("");
|
||||
|
||||
// Expanded entry
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
|
||||
// Summary (last 7 days)
|
||||
const sevenDaysAgo = useMemo(() => {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - 7);
|
||||
return d;
|
||||
}, []);
|
||||
|
||||
const { data: summary } = trpc.auditLog.getActivitySummary.useQuery(
|
||||
{ startDate: sevenDaysAgo },
|
||||
{ staleTime: 60_000 },
|
||||
);
|
||||
|
||||
// Users for filter dropdown
|
||||
type UserListItem = { id: string; name: string | null; email: string };
|
||||
const { data: users = [] } = trpc.user.list.useQuery(undefined, { staleTime: 300_000 }) as { data: UserListItem[] };
|
||||
|
||||
// Build query input
|
||||
const queryInput = useMemo(() => {
|
||||
const input: Record<string, unknown> = { limit: 50 };
|
||||
if (entityType) input.entityType = entityType;
|
||||
if (action) input.action = action;
|
||||
if (userId) input.userId = userId;
|
||||
if (search) input.search = search;
|
||||
if (startDate) input.startDate = new Date(startDate);
|
||||
if (endDate) input.endDate = new Date(endDate + "T23:59:59");
|
||||
return input;
|
||||
}, [entityType, action, userId, search, startDate, endDate]);
|
||||
|
||||
type AuditListPage = { items: Array<{
|
||||
id: string;
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
action: string;
|
||||
changes: unknown;
|
||||
createdAt: Date;
|
||||
source: string | null;
|
||||
entityName: string | null;
|
||||
summary: string | null;
|
||||
user: { id: string; name: string | null; email: string } | null;
|
||||
}>; nextCursor?: string };
|
||||
|
||||
const {
|
||||
data,
|
||||
isLoading,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
// Keep as any to avoid tRPC TS depth limits with useInfiniteQuery
|
||||
} = (trpc.auditLog.list.useInfiniteQuery as any)(
|
||||
queryInput,
|
||||
{
|
||||
getNextPageParam: (lastPage: AuditListPage) => lastPage.nextCursor ?? undefined,
|
||||
initialCursor: undefined,
|
||||
staleTime: 30_000,
|
||||
},
|
||||
) as {
|
||||
data: { pages: AuditListPage[] } | undefined;
|
||||
isLoading: boolean;
|
||||
fetchNextPage: () => void;
|
||||
hasNextPage: boolean;
|
||||
isFetchingNextPage: boolean;
|
||||
};
|
||||
|
||||
const allEntries = useMemo(() => {
|
||||
if (!data) return [];
|
||||
return data.pages.flatMap((page) => page.items);
|
||||
}, [data]);
|
||||
|
||||
const toggleExpand = useCallback((id: string) => {
|
||||
setExpandedId((prev) => (prev === id ? null : id));
|
||||
}, []);
|
||||
|
||||
const totalCount = summary?.total ?? 0;
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl space-y-6 p-4 sm:p-6">
|
||||
{/* Header */}
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Activity Log</h1>
|
||||
<p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
|
||||
{totalCount.toLocaleString()} changes recorded in the last 7 days
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Summary Cards */}
|
||||
{summary && <SummaryCards summary={summary} />}
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="flex flex-wrap items-end gap-3 rounded-xl border border-gray-200 bg-white p-4 shadow-sm dark:border-slate-700 dark:bg-slate-800">
|
||||
<div className="min-w-[140px]">
|
||||
<label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">Entity Type</label>
|
||||
<select
|
||||
value={entityType}
|
||||
onChange={(e) => setEntityType(e.target.value)}
|
||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
|
||||
>
|
||||
<option value="">All</option>
|
||||
{ENTITY_TYPE_OPTIONS.map((t) => (
|
||||
<option key={t} value={t}>{t}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="min-w-[120px]">
|
||||
<label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">Action</label>
|
||||
<select
|
||||
value={action}
|
||||
onChange={(e) => setAction(e.target.value)}
|
||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
|
||||
>
|
||||
<option value="">All</option>
|
||||
{ACTION_OPTIONS.map((a) => (
|
||||
<option key={a} value={a}>{a}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="min-w-[160px]">
|
||||
<label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">User</label>
|
||||
<select
|
||||
value={userId}
|
||||
onChange={(e) => setUserId(e.target.value)}
|
||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
|
||||
>
|
||||
<option value="">All</option>
|
||||
{users.map((u) => (
|
||||
<option key={u.id} value={u.id}>{u.name ?? u.email}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="min-w-[130px]">
|
||||
<label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">From</label>
|
||||
<input
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="min-w-[130px]">
|
||||
<label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">To</label>
|
||||
<input
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="min-w-[200px] flex-1">
|
||||
<label className="mb-1 block text-xs font-medium text-gray-600 dark:text-gray-400">Search</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search entity name or summary..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-700 dark:text-gray-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
setEntityType("");
|
||||
setAction("");
|
||||
setUserId("");
|
||||
setSearch("");
|
||||
setStartDate("");
|
||||
setEndDate("");
|
||||
}}
|
||||
className="rounded-lg border border-gray-300 px-3 py-2 text-sm text-gray-600 hover:bg-gray-50 dark:border-slate-600 dark:text-gray-400 dark:hover:bg-slate-700"
|
||||
>
|
||||
Reset
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Timeline List */}
|
||||
<div className="space-y-2">
|
||||
{isLoading && (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<div className="h-6 w-6 animate-spin rounded-full border-2 border-gray-300 border-t-blue-600" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && allEntries.length === 0 && (
|
||||
<div className="rounded-xl border border-dashed border-gray-300 bg-white py-16 text-center dark:border-slate-600 dark:bg-slate-800">
|
||||
<svg className="mx-auto h-10 w-10 text-gray-400 dark:text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<p className="mt-3 text-sm font-medium text-gray-600 dark:text-gray-400">No activity found</p>
|
||||
<p className="mt-1 text-xs text-gray-500 dark:text-gray-500">Try adjusting your filters or date range.</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{allEntries.map((entry) => {
|
||||
const changes = parseChanges(entry.changes);
|
||||
const isExpanded = expandedId === entry.id;
|
||||
const entityLink = ENTITY_LINKS[entry.entityType]?.(entry.entityId);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="rounded-xl border border-gray-200 bg-white shadow-sm transition-shadow hover:shadow-md dark:border-slate-700 dark:bg-slate-800"
|
||||
>
|
||||
<button
|
||||
onClick={() => toggleExpand(entry.id)}
|
||||
className="flex w-full items-start gap-3 p-4 text-left"
|
||||
>
|
||||
{/* User Avatar */}
|
||||
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-gray-200 text-xs font-semibold text-gray-700 dark:bg-slate-600 dark:text-gray-200">
|
||||
{entry.user ? userInitials(entry.user.name, entry.user.email) : "SY"}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{entry.user?.name ?? entry.user?.email ?? "System"}
|
||||
</span>
|
||||
<ActionBadge action={entry.action} />
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{entry.entityType}
|
||||
</span>
|
||||
{entry.entityName && (
|
||||
<>
|
||||
<span className="text-gray-400">·</span>
|
||||
{entityLink ? (
|
||||
<Link
|
||||
href={entityLink as Route}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="text-sm font-medium text-blue-600 hover:underline dark:text-blue-400"
|
||||
>
|
||||
{entry.entityName}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300">{entry.entityName}</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{entry.summary && (
|
||||
<p className="mt-0.5 text-sm text-gray-600 dark:text-gray-400">{entry.summary}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Timestamp */}
|
||||
<div className="shrink-0 text-right">
|
||||
<span
|
||||
className="text-xs text-gray-500 dark:text-gray-400"
|
||||
title={new Date(entry.createdAt).toLocaleString("de-DE")}
|
||||
>
|
||||
{relativeTime(entry.createdAt)}
|
||||
</span>
|
||||
{entry.source && (
|
||||
<p className="mt-0.5 text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-500">
|
||||
{entry.source}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Expand indicator */}
|
||||
<svg
|
||||
className={`h-4 w-4 shrink-0 text-gray-400 transition-transform ${isExpanded ? "rotate-180" : ""}`}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{/* Expanded Diff */}
|
||||
{isExpanded && (
|
||||
<div className="border-t border-gray-100 px-4 py-3 dark:border-slate-700">
|
||||
<DiffView changes={changes} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Load More */}
|
||||
{hasNextPage && (
|
||||
<div className="flex justify-center pt-4">
|
||||
<button
|
||||
onClick={() => fetchNextPage()}
|
||||
disabled={isFetchingNextPage}
|
||||
className="rounded-lg border border-gray-300 bg-white px-6 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50 dark:border-slate-600 dark:bg-slate-800 dark:text-gray-300 dark:hover:bg-slate-700"
|
||||
>
|
||||
{isFetchingNextPage ? "Loading..." : "Load more"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -76,6 +76,9 @@ function NotificationsIcon() {
|
||||
function BroadcastIcon() {
|
||||
return <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M11 5.882V19.24a1.76 1.76 0 01-3.417.592l-2.147-6.15M18 13a3 3 0 100-6M5.436 13.683A4.001 4.001 0 017 6h1.832c4.1 0 7.625-1.234 9.168-3v14c-1.543-1.766-5.067-3-9.168-3H7a3.988 3.988 0 01-1.564-.317z" /></svg>;
|
||||
}
|
||||
function ActivityLogIcon() {
|
||||
return <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>;
|
||||
}
|
||||
function AdminIcon() {
|
||||
return <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M12 8a4 4 0 100 8 4 4 0 000-8zm8 4l-2.1.7a7.9 7.9 0 01-.6 1.5l1 2-2.1 2.1-2-1a7.9 7.9 0 01-1.5.6L12 20l-1.7-2.1a7.9 7.9 0 01-1.5-.6l-2 1-2.1-2.1 1-2a7.9 7.9 0 01-.6-1.5L4 12l2.1-1.7a7.9 7.9 0 01.6-1.5l-1-2 2.1-2.1 2 1a7.9 7.9 0 011.5-.6L12 4l1.7 2.1a7.9 7.9 0 011.5.6l2-1 2.1 2.1-1 2a7.9 7.9 0 01.6 1.5L20 12z" /></svg>;
|
||||
}
|
||||
@@ -189,6 +192,7 @@ const adminNavEntries: AdminEntry[] = [
|
||||
{ href: "/admin/notifications", label: "Broadcasts", icon: <BroadcastIcon /> },
|
||||
{ href: "/admin/webhooks", label: "Webhooks", icon: <AdminIcon /> },
|
||||
{ href: "/admin/dispo-imports", label: "Dispo Import", icon: <AdminIcon /> },
|
||||
{ href: "/admin/activity-log", label: "Activity Log", icon: <ActivityLogIcon /> },
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback } from "react";
|
||||
import Link from "next/link";
|
||||
import type { Route } from "next";
|
||||
import { trpc } from "~/lib/trpc/client.js";
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
const ACTION_BADGES: Record<string, { label: string; className: string }> = {
|
||||
CREATE: { label: "Create", className: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-400" },
|
||||
UPDATE: { label: "Update", className: "bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-400" },
|
||||
DELETE: { label: "Delete", className: "bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-400" },
|
||||
SHIFT: { label: "Shift", className: "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-400" },
|
||||
IMPORT: { label: "Import", className: "bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-400" },
|
||||
};
|
||||
|
||||
function relativeTime(date: Date | string): string {
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - new Date(date).getTime();
|
||||
const diffSec = Math.floor(diffMs / 1000);
|
||||
const diffMin = Math.floor(diffSec / 60);
|
||||
const diffHr = Math.floor(diffMin / 60);
|
||||
const diffDays = Math.floor(diffHr / 24);
|
||||
|
||||
if (diffSec < 60) return "just now";
|
||||
if (diffMin < 60) return `${diffMin}m ago`;
|
||||
if (diffHr < 24) return `${diffHr}h ago`;
|
||||
if (diffDays < 7) return `${diffDays}d ago`;
|
||||
return new Date(date).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric" });
|
||||
}
|
||||
|
||||
function formatValue(val: unknown): string {
|
||||
if (val === null || val === undefined) return "(empty)";
|
||||
if (typeof val === "boolean") return val ? "Yes" : "No";
|
||||
if (typeof val === "object") return JSON.stringify(val);
|
||||
return String(val);
|
||||
}
|
||||
|
||||
type DiffEntry = { old: unknown; new: unknown };
|
||||
type Changes = {
|
||||
before?: Record<string, unknown>;
|
||||
after?: Record<string, unknown>;
|
||||
diff?: Record<string, DiffEntry>;
|
||||
};
|
||||
|
||||
function parseChanges(changes: unknown): Changes {
|
||||
if (!changes || typeof changes !== "object") return {};
|
||||
return changes as Changes;
|
||||
}
|
||||
|
||||
// ─── Component ──────────────────────────────────────────────────────────────
|
||||
|
||||
interface EntityHistoryProps {
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
type AuditEntry = {
|
||||
id: string;
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
action: string;
|
||||
changes: unknown;
|
||||
createdAt: Date | string;
|
||||
source: string | null;
|
||||
entityName: string | null;
|
||||
summary: string | null;
|
||||
user: { id: string; name: string | null; email: string } | null;
|
||||
};
|
||||
|
||||
export function EntityHistory({ entityType, entityId, limit = 10 }: EntityHistoryProps) {
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
|
||||
const { data: entries = [], isLoading } = trpc.auditLog.getByEntity.useQuery(
|
||||
{ entityType, entityId, limit },
|
||||
{ staleTime: 30_000 },
|
||||
) as { data: AuditEntry[]; isLoading: boolean };
|
||||
|
||||
const toggleExpand = useCallback((id: string) => {
|
||||
setExpandedId((prev) => (prev === id ? null : id));
|
||||
}, []);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-6">
|
||||
<div className="h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-blue-600" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (entries.length === 0) {
|
||||
return (
|
||||
<div className="py-6 text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
No history recorded yet.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<h3 className="mb-3 text-sm font-semibold text-gray-700 dark:text-gray-300">Change History</h3>
|
||||
|
||||
{/* Timeline */}
|
||||
<div className="relative space-y-0">
|
||||
{/* Vertical line */}
|
||||
<div className="absolute left-3 top-2 bottom-2 w-px bg-gray-200 dark:bg-slate-600" />
|
||||
|
||||
{entries.map((entry) => {
|
||||
const changes = parseChanges(entry.changes);
|
||||
const isExpanded = expandedId === entry.id;
|
||||
const badge = ACTION_BADGES[entry.action] ?? { label: entry.action, className: "bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400" };
|
||||
|
||||
return (
|
||||
<div key={entry.id} className="relative pl-8">
|
||||
{/* Dot */}
|
||||
<div className="absolute left-1.5 top-2.5 h-3 w-3 rounded-full border-2 border-white bg-gray-400 dark:border-slate-800 dark:bg-slate-500" />
|
||||
|
||||
<button
|
||||
onClick={() => toggleExpand(entry.id)}
|
||||
className="w-full rounded-lg p-2 text-left transition-colors hover:bg-gray-50 dark:hover:bg-slate-700/50"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className={`inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium ${badge.className}`}>
|
||||
{badge.label}
|
||||
</span>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{entry.user?.name ?? entry.user?.email ?? "System"}
|
||||
</span>
|
||||
<span
|
||||
className="ml-auto text-[10px] text-gray-400 dark:text-gray-500"
|
||||
title={new Date(entry.createdAt).toLocaleString("de-DE")}
|
||||
>
|
||||
{relativeTime(entry.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
{entry.summary && (
|
||||
<p className="mt-0.5 text-xs text-gray-600 dark:text-gray-400">{entry.summary}</p>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Expanded diff */}
|
||||
{isExpanded && changes.diff && Object.keys(changes.diff).length > 0 && (
|
||||
<div className="mb-2 ml-2 rounded-lg border border-gray-100 bg-gray-50 p-2 dark:border-slate-700 dark:bg-slate-800/50">
|
||||
{Object.entries(changes.diff).map(([field, { old: oldVal, new: newVal }]) => (
|
||||
<div key={field} className="flex items-start gap-2 text-xs">
|
||||
<span className="min-w-[80px] shrink-0 font-medium text-gray-600 dark:text-gray-400">{field}</span>
|
||||
<span className="rounded bg-red-50 px-1 text-red-600 line-through dark:bg-red-900/20 dark:text-red-400">
|
||||
{formatValue(oldVal)}
|
||||
</span>
|
||||
<span className="text-gray-400">→</span>
|
||||
<span className="rounded bg-emerald-50 px-1 text-emerald-600 dark:bg-emerald-900/20 dark:text-emerald-400">
|
||||
{formatValue(newVal)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Link to full log */}
|
||||
<div className="pt-2 text-center">
|
||||
<Link
|
||||
href={`/admin/activity-log?entityType=${encodeURIComponent(entityType)}&search=${encodeURIComponent(entityId)}` as Route}
|
||||
className="text-xs font-medium text-blue-600 hover:underline dark:text-blue-400"
|
||||
>
|
||||
View all in Activity Log
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user