feat: activity log system
This commit is contained in:
13
src/app/dashboard/activity-log/page.tsx
Normal file
13
src/app/dashboard/activity-log/page.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { ActivityLogTable } from '@/components/activityLog/ActivityLogTable';
|
||||
|
||||
export default async function ActivityLogPage() {
|
||||
await requireAuth();
|
||||
|
||||
return (
|
||||
<main className="p-5">
|
||||
<h1 className="mb-5 text-lg font-semibold text-primary">Activity Log</h1>
|
||||
<ActivityLogTable />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
229
src/components/activityLog/ActivityLogTable.tsx
Normal file
229
src/components/activityLog/ActivityLogTable.tsx
Normal file
@@ -0,0 +1,229 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { getActivityLogAction, getGlobalActivityLogAction } from '@/lib/actions/activityLog';
|
||||
import type { ActivityLog, ActivityLogFilter, ActionType } from '@/lib/schemas/activityLog';
|
||||
import { ACTION_TYPE_LABELS, actionTypeSchema } from '@/lib/schemas/activityLog';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
interface ActivityLogTableProps {
|
||||
serverId?: string;
|
||||
}
|
||||
|
||||
function formatDate(iso: string): string {
|
||||
return new Date(iso).toLocaleString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
function parseDetails(raw: string): string {
|
||||
try {
|
||||
const obj = JSON.parse(raw) as Record<string, unknown>;
|
||||
if (obj.file && Array.isArray(obj.changed_keys)) {
|
||||
return `Updated ${obj.file} — changed: ${(obj.changed_keys as string[]).join(', ')}`;
|
||||
}
|
||||
if (obj.service) {
|
||||
return `Service: ${obj.service}`;
|
||||
}
|
||||
if (obj.driver_count !== undefined && obj.race_count !== undefined) {
|
||||
return `${obj.driver_count} drivers, ${obj.race_count} races`;
|
||||
}
|
||||
return raw;
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
const ACTION_BADGE: Record<ActionType, string> = {
|
||||
config_update: 'bg-blue-bg text-blue',
|
||||
server_start: 'bg-green-bg text-green',
|
||||
server_stop: 'bg-red-bg text-red',
|
||||
server_restart: 'bg-yellow-bg text-yellow',
|
||||
leaderboard_update: 'bg-overlay text-muted'
|
||||
};
|
||||
|
||||
export function ActivityLogTable({ serverId }: ActivityLogTableProps) {
|
||||
const [logs, setLogs] = useState<ActivityLog[]>([]);
|
||||
const [page, setPage] = useState(1);
|
||||
const [hasMore, setHasMore] = useState(true);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [filterAction, setFilterAction] = useState<ActionType | ''>('');
|
||||
const [filterStartDate, setFilterStartDate] = useState('');
|
||||
const [filterEndDate, setFilterEndDate] = useState('');
|
||||
|
||||
const [appliedFilter, setAppliedFilter] = useState<ActivityLogFilter>({});
|
||||
|
||||
const fetchLogs = useCallback(
|
||||
async (currentPage: number, filter: ActivityLogFilter, reset: boolean) => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const params = { ...filter, page: currentPage, page_size: PAGE_SIZE };
|
||||
const result = serverId
|
||||
? await getActivityLogAction(serverId, params)
|
||||
: await getGlobalActivityLogAction(params);
|
||||
setIsLoading(false);
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
setHasMore(result.data.length === PAGE_SIZE);
|
||||
setLogs((prev) => (reset ? result.data : [...prev, ...result.data]));
|
||||
},
|
||||
[serverId]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchLogs(1, {}, true);
|
||||
}, [fetchLogs]);
|
||||
|
||||
const applyFilters = () => {
|
||||
const filter: ActivityLogFilter = {};
|
||||
if (filterAction) filter.action = filterAction as ActionType;
|
||||
if (filterStartDate) filter.start_date = new Date(filterStartDate).toISOString();
|
||||
if (filterEndDate) filter.end_date = new Date(filterEndDate).toISOString();
|
||||
setAppliedFilter(filter);
|
||||
setPage(1);
|
||||
setLogs([]);
|
||||
fetchLogs(1, filter, true);
|
||||
};
|
||||
|
||||
const clearFilters = () => {
|
||||
setFilterAction('');
|
||||
setFilterStartDate('');
|
||||
setFilterEndDate('');
|
||||
setAppliedFilter({});
|
||||
setPage(1);
|
||||
setLogs([]);
|
||||
fetchLogs(1, {}, true);
|
||||
};
|
||||
|
||||
const loadMore = () => {
|
||||
const next = page + 1;
|
||||
setPage(next);
|
||||
fetchLogs(next, appliedFilter, false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap items-end gap-3 rounded-lg border border-border bg-canvas p-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-subtle">Action type</label>
|
||||
<select
|
||||
value={filterAction}
|
||||
onChange={(e) => setFilterAction(e.target.value as ActionType | '')}
|
||||
className="form-input w-44 text-sm"
|
||||
>
|
||||
<option value="">All actions</option>
|
||||
{actionTypeSchema.options.map((opt) => (
|
||||
<option key={opt} value={opt}>
|
||||
{ACTION_TYPE_LABELS[opt]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-subtle">From</label>
|
||||
<input
|
||||
type="date"
|
||||
value={filterStartDate}
|
||||
onChange={(e) => setFilterStartDate(e.target.value)}
|
||||
className="form-input w-36 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-subtle">To</label>
|
||||
<input
|
||||
type="date"
|
||||
value={filterEndDate}
|
||||
onChange={(e) => setFilterEndDate(e.target.value)}
|
||||
className="form-input w-36 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<Button variant="primary" size="sm" onClick={applyFilters}>
|
||||
Apply
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={clearFilters}>
|
||||
Clear
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red">{error}</p>
|
||||
)}
|
||||
|
||||
<div className="overflow-hidden rounded-lg border border-border bg-canvas">
|
||||
{logs.length === 0 && !isLoading ? (
|
||||
<div className="px-4 py-12 text-center">
|
||||
<div className="mb-3 text-4xl">📋</div>
|
||||
<p className="text-sm text-muted">No activity logged yet.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full">
|
||||
<thead>
|
||||
<tr className="border-b border-border-muted bg-base">
|
||||
<th className="px-4 py-2 text-left text-xs font-medium uppercase tracking-wider text-subtle">
|
||||
Time
|
||||
</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium uppercase tracking-wider text-subtle">
|
||||
User
|
||||
</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium uppercase tracking-wider text-subtle">
|
||||
Action
|
||||
</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium uppercase tracking-wider text-subtle">
|
||||
Details
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{logs.map((log) => (
|
||||
<tr
|
||||
key={log.id}
|
||||
className="border-b border-border-muted transition-colors hover:bg-hover last:border-0"
|
||||
>
|
||||
<td className="whitespace-nowrap px-4 py-3 text-sm text-muted">
|
||||
{formatDate(log.createdAt)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-secondary">
|
||||
{log.username}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${ACTION_BADGE[log.action] ?? 'bg-canvas text-muted'}`}
|
||||
>
|
||||
{ACTION_TYPE_LABELS[log.action] ?? log.action}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-sm text-muted">
|
||||
{parseDetails(log.details)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading && (
|
||||
<div className="px-4 py-4 text-center text-sm text-muted">Loading…</div>
|
||||
)}
|
||||
|
||||
{hasMore && !isLoading && logs.length > 0 && (
|
||||
<div className="border-t border-border-muted px-4 py-3 text-center">
|
||||
<Button variant="ghost" size="sm" onClick={loadMore}>
|
||||
Load more
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -77,10 +77,15 @@ export function ServerCard({ server }: ServerCardProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-3">
|
||||
<div className="mt-3 flex items-center justify-between gap-2">
|
||||
<Badge variant={statusBadgeVariant(server.status)}>
|
||||
{serviceStatusToString(server.status)}
|
||||
</Badge>
|
||||
{server.lastActivity && (
|
||||
<span className="truncate text-xs text-subtle">
|
||||
by {server.lastActivity.username}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { EventRulesEditor } from '@/components/configuration/EventRulesEditor';
|
||||
import { ServerSettingsEditor } from '@/components/configuration/ServerSettingsEditor';
|
||||
import { StatisticsDashboard } from '@/components/statistics/StatisticsDashboard';
|
||||
import { LeaderboardManager } from '@/components/leaderboard/LeaderboardManager';
|
||||
import { ActivityLogTable } from '@/components/activityLog/ActivityLogTable';
|
||||
import { useState } from 'react';
|
||||
import { StateHistoryStats } from '@/lib/schemas';
|
||||
import { Leaderboard } from '@/lib/schemas/leaderboard';
|
||||
@@ -26,7 +27,8 @@ const tabs = [
|
||||
{ id: ServerTab.event, name: 'Event Config', icon: '🏁' },
|
||||
{ id: ServerTab.eventRules, name: 'Event Rules', icon: '📋' },
|
||||
{ id: ServerTab.settings, name: 'Server Settings', icon: '🔧' },
|
||||
{ id: ServerTab.leaderboard, name: 'Leaderboard', icon: '🏆' }
|
||||
{ id: ServerTab.leaderboard, name: 'Leaderboard', icon: '🏆' },
|
||||
{ id: ServerTab.activityLog, name: 'History', icon: '📋' }
|
||||
];
|
||||
|
||||
const configTabs = new Set([
|
||||
@@ -138,6 +140,9 @@ export function ServerConfigurationTabs({
|
||||
case ServerTab.leaderboard:
|
||||
return <LeaderboardManager serverId={serverId} initialData={leaderboard} />;
|
||||
|
||||
case ServerTab.activityLog:
|
||||
return <ActivityLogTable serverId={serverId} />;
|
||||
|
||||
default:
|
||||
return (
|
||||
<div className="py-12 text-center">
|
||||
|
||||
@@ -44,10 +44,25 @@ function UsersIcon({ active }: { active: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function ActivityLogIcon({ active }: { active: boolean }) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
className={cn('h-5 w-5', active ? 'text-blue' : 'text-subtle')}
|
||||
>
|
||||
<path d="M9 12h6M9 16h6M9 8h6M5 4h14a1 1 0 011 1v14a1 1 0 01-1 1H5a1 1 0 01-1-1V5a1 1 0 011-1z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function Sidebar({ showUsers }: SidebarProps) {
|
||||
const pathname = usePathname();
|
||||
const isServers = pathname === '/dashboard' || pathname.startsWith('/dashboard/server');
|
||||
const isUsers = pathname.startsWith('/dashboard/membership');
|
||||
const isActivityLog = pathname.startsWith('/dashboard/activity-log');
|
||||
|
||||
const navItems = [
|
||||
{
|
||||
@@ -56,6 +71,12 @@ export function Sidebar({ showUsers }: SidebarProps) {
|
||||
active: isServers,
|
||||
icon: <ServerIcon active={isServers} />
|
||||
},
|
||||
{
|
||||
href: '/dashboard/activity-log',
|
||||
label: 'Activity Log',
|
||||
active: isActivityLog,
|
||||
icon: <ActivityLogIcon active={isActivityLog} />
|
||||
},
|
||||
...(showUsers
|
||||
? [
|
||||
{
|
||||
|
||||
36
src/lib/actions/activityLog.ts
Normal file
36
src/lib/actions/activityLog.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
'use server';
|
||||
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { getActivityLog, getGlobalActivityLog } from '@/lib/api/server/activityLog';
|
||||
import type { ActivityLog, ActivityLogFilter } from '@/lib/schemas/activityLog';
|
||||
|
||||
export async function getActivityLogAction(
|
||||
serverId: string,
|
||||
filter?: ActivityLogFilter
|
||||
): Promise<{ success: true; data: ActivityLog[] } | { success: false; message: string }> {
|
||||
try {
|
||||
const session = await requireAuth();
|
||||
const data = await getActivityLog(session.token!, serverId, filter);
|
||||
return { success: true, data };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Failed to fetch activity log'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function getGlobalActivityLogAction(
|
||||
filter?: ActivityLogFilter
|
||||
): Promise<{ success: true; data: ActivityLog[] } | { success: false; message: string }> {
|
||||
try {
|
||||
const session = await requireAuth();
|
||||
const data = await getGlobalActivityLog(session.token!, filter);
|
||||
return { success: true, data };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Failed to fetch activity log'
|
||||
};
|
||||
}
|
||||
}
|
||||
39
src/lib/api/server/activityLog.ts
Normal file
39
src/lib/api/server/activityLog.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import { activityLogSchema, type ActivityLog, type ActivityLogFilter } from '@/lib/schemas/activityLog';
|
||||
|
||||
function buildQuery(filter?: ActivityLogFilter): string {
|
||||
if (!filter) return '';
|
||||
const params = new URLSearchParams();
|
||||
if (filter.page !== undefined) params.set('page', String(filter.page));
|
||||
if (filter.page_size !== undefined) params.set('page_size', String(filter.page_size));
|
||||
if (filter.sort_by) params.set('sort_by', filter.sort_by);
|
||||
if (filter.sort_desc !== undefined) params.set('sort_desc', String(filter.sort_desc));
|
||||
if (filter.user_id) params.set('user_id', filter.user_id);
|
||||
if (filter.action) params.set('action', filter.action);
|
||||
if (filter.start_date) params.set('start_date', filter.start_date);
|
||||
if (filter.end_date) params.set('end_date', filter.end_date);
|
||||
const str = params.toString();
|
||||
return str ? `?${str}` : '';
|
||||
}
|
||||
|
||||
export async function getActivityLog(
|
||||
token: string,
|
||||
serverId: string,
|
||||
filter?: ActivityLogFilter
|
||||
): Promise<ActivityLog[]> {
|
||||
const query = buildQuery(filter);
|
||||
const response = await fetchServerAPI<ActivityLog[]>(
|
||||
`/server/${serverId}/activity-log${query}`,
|
||||
token
|
||||
);
|
||||
return activityLogSchema.array().parse(response.data);
|
||||
}
|
||||
|
||||
export async function getGlobalActivityLog(
|
||||
token: string,
|
||||
filter?: ActivityLogFilter
|
||||
): Promise<ActivityLog[]> {
|
||||
const query = buildQuery(filter);
|
||||
const response = await fetchServerAPI<ActivityLog[]>(`/activity-log${query}`, token);
|
||||
return activityLogSchema.array().parse(response.data);
|
||||
}
|
||||
52
src/lib/schemas/activityLog.ts
Normal file
52
src/lib/schemas/activityLog.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import * as z from 'zod';
|
||||
|
||||
export const actionTypeSchema = z.enum([
|
||||
'config_update',
|
||||
'server_start',
|
||||
'server_stop',
|
||||
'server_restart',
|
||||
'leaderboard_update'
|
||||
]);
|
||||
|
||||
export type ActionType = z.infer<typeof actionTypeSchema>;
|
||||
|
||||
export const activityLogSchema = z.object({
|
||||
id: z.string(),
|
||||
serverId: z.string(),
|
||||
userId: z.string(),
|
||||
username: z.string(),
|
||||
action: actionTypeSchema,
|
||||
details: z.string(),
|
||||
createdAt: z.string()
|
||||
});
|
||||
|
||||
export type ActivityLog = z.infer<typeof activityLogSchema>;
|
||||
|
||||
export const lastActivityInfoSchema = z.object({
|
||||
updatedAt: z.string(),
|
||||
username: z.string(),
|
||||
action: actionTypeSchema
|
||||
});
|
||||
|
||||
export type LastActivityInfo = z.infer<typeof lastActivityInfoSchema>;
|
||||
|
||||
export const activityLogFilterSchema = z.object({
|
||||
page: z.number().optional(),
|
||||
page_size: z.number().optional(),
|
||||
sort_by: z.string().optional(),
|
||||
sort_desc: z.boolean().optional(),
|
||||
user_id: z.string().optional(),
|
||||
action: actionTypeSchema.optional(),
|
||||
start_date: z.string().optional(),
|
||||
end_date: z.string().optional()
|
||||
});
|
||||
|
||||
export type ActivityLogFilter = z.infer<typeof activityLogFilterSchema>;
|
||||
|
||||
export const ACTION_TYPE_LABELS: Record<ActionType, string> = {
|
||||
config_update: 'Config Update',
|
||||
server_start: 'Server Start',
|
||||
server_stop: 'Server Stop',
|
||||
server_restart: 'Server Restart',
|
||||
leaderboard_update: 'Leaderboard Update'
|
||||
};
|
||||
@@ -16,7 +16,8 @@ export enum ServerTab {
|
||||
event = 'event',
|
||||
eventRules = 'eventRules',
|
||||
settings = 'settings',
|
||||
leaderboard = 'leaderboard'
|
||||
leaderboard = 'leaderboard',
|
||||
activityLog = 'activityLog'
|
||||
}
|
||||
export const serverTabSchema = z.enum(ServerTab);
|
||||
|
||||
|
||||
@@ -4,3 +4,4 @@ export * from './config';
|
||||
export * from './statistics';
|
||||
export * from './lookups';
|
||||
export * from './leaderboard';
|
||||
export * from './activityLog';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as z from 'zod';
|
||||
import { lastActivityInfoSchema } from './activityLog';
|
||||
|
||||
export enum ServiceStatus {
|
||||
Unknown,
|
||||
@@ -57,7 +58,8 @@ export const serverSchema = z.object({
|
||||
id: z.uuid(),
|
||||
name: z.string().min(1),
|
||||
status: z.enum(ServiceStatus),
|
||||
state: stateSchema.optional().nullable()
|
||||
state: stateSchema.optional().nullable(),
|
||||
lastActivity: lastActivityInfoSchema.optional().nullable()
|
||||
});
|
||||
|
||||
export type Server = z.infer<typeof serverSchema>;
|
||||
|
||||
Reference in New Issue
Block a user