Compare commits
9 Commits
de41d2566c
...
v0.24.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 9c23a720d1 | |||
| cc4afd2294 | |||
| 2d85b63775 | |||
| 36c31fa790 | |||
| c7ef3e9d27 | |||
| 50d8662904 | |||
| 5a4457d369 | |||
| 4cc005d309 | |||
| 9d22027f23 |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "acc-server-manager-web",
|
||||
"version": "0.20.2",
|
||||
"version": "0.24.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev --turbopack",
|
||||
|
||||
16
src/app/dashboard/activity-log/page.tsx
Normal file
16
src/app/dashboard/activity-log/page.tsx
Normal file
@@ -0,0 +1,16 @@
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { getServers } from '@/lib/api/server/servers';
|
||||
import { ActivityLogTable } from '@/components/activityLog/ActivityLogTable';
|
||||
|
||||
export default async function ActivityLogPage() {
|
||||
const session = await requireAuth();
|
||||
const servers = await getServers(session.token!);
|
||||
const serverOptions = servers.map((s) => ({ id: s.id, name: s.name }));
|
||||
|
||||
return (
|
||||
<main className="p-5">
|
||||
<h1 className="mb-5 text-lg font-semibold text-primary">Activity Log</h1>
|
||||
<ActivityLogTable servers={serverOptions} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -5,9 +5,17 @@ import { ServerCreationPopupContainer } from '@/components/server/ServerCreation
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { AppShell } from '@/components/ui/AppShell';
|
||||
import { hasPermission } from '@/lib/schemas';
|
||||
import { checkHealth } from '@/lib/api/server/health';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export default async function DashboardLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
||||
const session = await requireAuth();
|
||||
|
||||
const health = await checkHealth();
|
||||
if (!health.healthy) {
|
||||
redirect('/login');
|
||||
}
|
||||
|
||||
const showUsers = hasPermission(session.user!, 'membership.view');
|
||||
return (
|
||||
<WebSocketProvider openToken={session.openToken!}>
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import { Suspense } from 'react';
|
||||
import LoginForm from '@/components/login/LoginForm';
|
||||
import { checkHealth } from '@/lib/api/server/health';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export default function LoginPage({
|
||||
export default async function LoginPage({
|
||||
searchParams
|
||||
}: {
|
||||
searchParams: Promise<{ expired: boolean | undefined }>;
|
||||
}) {
|
||||
const health = await checkHealth();
|
||||
|
||||
return (
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
<LoginForm searchParams={searchParams} />
|
||||
<LoginForm searchParams={searchParams} health={health} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
256
src/components/activityLog/ActivityLogTable.tsx
Normal file
256
src/components/activityLog/ActivityLogTable.tsx
Normal file
@@ -0,0 +1,256 @@
|
||||
'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 ServerOption {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface ActivityLogTableProps {
|
||||
serverId?: string;
|
||||
servers?: ServerOption[];
|
||||
}
|
||||
|
||||
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, servers }: 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 [filterServerId, setFilterServerId] = useState('');
|
||||
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 };
|
||||
if (serverId) params.server_id = serverId;
|
||||
const result = await getActivityLogAction(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 (filterServerId) filter.server_id = filterServerId;
|
||||
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('');
|
||||
setFilterServerId('');
|
||||
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="border-border bg-canvas flex flex-wrap items-end gap-3 rounded-lg border p-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-subtle text-xs">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>
|
||||
{servers && servers.length > 0 && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-subtle text-xs">Server</label>
|
||||
<select
|
||||
value={filterServerId}
|
||||
onChange={(e) => setFilterServerId(e.target.value)}
|
||||
className="form-input w-48 text-sm"
|
||||
>
|
||||
<option value="">All servers</option>
|
||||
{servers.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-subtle text-xs">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-subtle text-xs">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-red text-sm">{error}</p>}
|
||||
|
||||
<div className="border-border bg-canvas overflow-hidden rounded-lg border">
|
||||
{logs.length === 0 && !isLoading ? (
|
||||
<div className="px-4 py-12 text-center">
|
||||
<div className="mb-3 text-4xl">📋</div>
|
||||
<p className="text-muted text-sm">No activity logged yet.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full">
|
||||
<thead>
|
||||
<tr className="border-border-muted bg-base border-b">
|
||||
<th className="text-subtle px-4 py-2 text-left text-xs font-medium tracking-wider uppercase">
|
||||
Time
|
||||
</th>
|
||||
<th className="text-subtle px-4 py-2 text-left text-xs font-medium tracking-wider uppercase">
|
||||
User
|
||||
</th>
|
||||
{!serverId && (
|
||||
<th className="text-subtle px-4 py-2 text-left text-xs font-medium tracking-wider uppercase">
|
||||
Server
|
||||
</th>
|
||||
)}
|
||||
<th className="text-subtle px-4 py-2 text-left text-xs font-medium tracking-wider uppercase">
|
||||
Action
|
||||
</th>
|
||||
<th className="text-subtle px-4 py-2 text-left text-xs font-medium tracking-wider uppercase">
|
||||
Details
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{logs.map((log) => (
|
||||
<tr
|
||||
key={log.id}
|
||||
className="border-border-muted hover:bg-hover border-b transition-colors last:border-0"
|
||||
>
|
||||
<td className="text-muted px-4 py-3 text-sm whitespace-nowrap">
|
||||
{formatDate(log.createdAt)}
|
||||
</td>
|
||||
<td className="text-secondary px-4 py-3 text-sm">{log.username}</td>
|
||||
{!serverId && (
|
||||
<td className="text-secondary px-4 py-3 text-sm">
|
||||
{log.server?.name ?? log.serverId}
|
||||
</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="text-muted px-4 py-3 text-sm">{parseDetails(log.details)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isLoading && <div className="text-muted px-4 py-4 text-center text-sm">Loading…</div>}
|
||||
|
||||
{hasMore && !isLoading && logs.length > 0 && (
|
||||
<div className="border-border-muted border-t px-4 py-3 text-center">
|
||||
<Button variant="ghost" size="sm" onClick={loadMore}>
|
||||
Load more
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { AssistRules } from '@/lib/schemas/config';
|
||||
import { updateAssistRulesAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface AssistRulesEditorProps {
|
||||
serverId: string;
|
||||
config: AssistRules;
|
||||
formData: AssistRules;
|
||||
disabled?: boolean;
|
||||
onFormDataChange: (data: AssistRules) => void;
|
||||
}
|
||||
|
||||
const assistFields = [
|
||||
@@ -57,42 +56,16 @@ const assistFields = [
|
||||
}
|
||||
];
|
||||
|
||||
export function AssistRulesEditor({ serverId, config }: AssistRulesEditorProps) {
|
||||
const [formData, setFormData] = useState<AssistRules>(config);
|
||||
const [restart, setRestart] = useState(true);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
|
||||
const formDataObj = new FormData();
|
||||
Object.entries(formData).forEach(([key, value]) => {
|
||||
formDataObj.append(key, value.toString());
|
||||
});
|
||||
if (restart) {
|
||||
formDataObj.append('restart', 'on');
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await updateAssistRulesAction(serverId, formDataObj);
|
||||
if (!result.success) {
|
||||
console.error('Failed to update assist rules:', result.message);
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
export function AssistRulesEditor({ formData, disabled, onFormDataChange }: AssistRulesEditorProps) {
|
||||
const handleInputChange = (key: keyof AssistRules, value: string | number) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
onFormDataChange({
|
||||
...formData,
|
||||
[key]: typeof value === 'string' ? parseInt(value) : value
|
||||
}));
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-3xl space-y-6">
|
||||
<div className="max-w-3xl space-y-6">
|
||||
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
|
||||
{assistFields.map(({ key, label, type }) => (
|
||||
<div key={key}>
|
||||
@@ -100,7 +73,7 @@ export function AssistRulesEditor({ serverId, config }: AssistRulesEditorProps)
|
||||
{type === 'number' ? (
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData[key]}
|
||||
onChange={(e) => handleInputChange(key, e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -109,7 +82,7 @@ export function AssistRulesEditor({ serverId, config }: AssistRulesEditorProps)
|
||||
/>
|
||||
) : (
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData[key]}
|
||||
onChange={(e) => handleInputChange(key, e.target.value)}
|
||||
className="form-select w-full"
|
||||
@@ -121,28 +94,6 @@ export function AssistRulesEditor({ serverId, config }: AssistRulesEditorProps)
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border pt-6">
|
||||
<label className="flex items-center gap-2 text-sm text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={restart}
|
||||
onChange={(e) => setRestart(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-border bg-overlay accent-green focus:ring-1 focus:ring-blue"
|
||||
/>
|
||||
Restart server after saving
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="rounded-md bg-btn-green border border-btn-green px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-btn-green-hover disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{isSubmitting ? 'Saving…' : 'Save Changes'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,56 +1,29 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { Configuration } from '@/lib/schemas/config';
|
||||
import { updateConfigurationAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface ConfigurationEditorProps {
|
||||
serverId: string;
|
||||
config: Configuration;
|
||||
formData: Configuration;
|
||||
disabled?: boolean;
|
||||
onFormDataChange: (data: Configuration) => void;
|
||||
}
|
||||
|
||||
export function ConfigurationEditor({ serverId, config }: ConfigurationEditorProps) {
|
||||
const [formData, setFormData] = useState<Configuration>(config);
|
||||
const [restart, setRestart] = useState(true);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
|
||||
const formDataObj = new FormData();
|
||||
Object.entries(formData).forEach(([key, value]) => {
|
||||
formDataObj.append(key, value.toString());
|
||||
});
|
||||
if (restart) {
|
||||
formDataObj.append('restart', 'on');
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await updateConfigurationAction(serverId, formDataObj);
|
||||
if (!result.success) {
|
||||
console.error('Failed to update configuration:', result.message);
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
export function ConfigurationEditor({ formData, disabled, onFormDataChange }: ConfigurationEditorProps) {
|
||||
const handleInputChange = (key: keyof Configuration, value: string | number) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
onFormDataChange({
|
||||
...formData,
|
||||
[key]: typeof value === 'string' ? parseInt(value) : value
|
||||
}));
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-3xl space-y-6">
|
||||
<div className="max-w-3xl space-y-6">
|
||||
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
|
||||
<div>
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">UDP Port</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.udpPort}
|
||||
onChange={(e) => handleInputChange('udpPort', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -61,7 +34,7 @@ export function ConfigurationEditor({ serverId, config }: ConfigurationEditorPro
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">TCP Port</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.tcpPort}
|
||||
onChange={(e) => handleInputChange('tcpPort', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -72,7 +45,7 @@ export function ConfigurationEditor({ serverId, config }: ConfigurationEditorPro
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">Max Connections</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.maxConnections}
|
||||
onChange={(e) => handleInputChange('maxConnections', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -82,7 +55,7 @@ export function ConfigurationEditor({ serverId, config }: ConfigurationEditorPro
|
||||
<div>
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">LAN Discovery</label>
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.lanDiscovery}
|
||||
onChange={(e) => handleInputChange('lanDiscovery', e.target.value)}
|
||||
className="form-select w-full"
|
||||
@@ -95,7 +68,7 @@ export function ConfigurationEditor({ serverId, config }: ConfigurationEditorPro
|
||||
<div>
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">Register To Lobby</label>
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.registerToLobby}
|
||||
onChange={(e) => handleInputChange('registerToLobby', e.target.value)}
|
||||
className="form-select w-full"
|
||||
@@ -105,28 +78,6 @@ export function ConfigurationEditor({ serverId, config }: ConfigurationEditorPro
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border pt-6">
|
||||
<label className="flex items-center gap-2 text-sm text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={restart}
|
||||
onChange={(e) => setRestart(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-border bg-overlay accent-green focus:ring-1 focus:ring-blue"
|
||||
/>
|
||||
Restart server after saving
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="rounded-md bg-btn-green border border-btn-green px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-btn-green-hover disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{isSubmitting ? 'Saving…' : 'Save Changes'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { EventConfig, Session } from '@/lib/schemas/config';
|
||||
import { updateEventConfigAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface EventConfigEditorProps {
|
||||
serverId: string;
|
||||
config: EventConfig;
|
||||
formData: EventConfig;
|
||||
disabled?: boolean;
|
||||
onFormDataChange: (data: EventConfig) => void;
|
||||
}
|
||||
|
||||
const sessionTypes = [
|
||||
@@ -15,49 +14,19 @@ const sessionTypes = [
|
||||
{ value: 'R', label: 'Race' }
|
||||
];
|
||||
|
||||
export function EventConfigEditor({ serverId, config }: EventConfigEditorProps) {
|
||||
const [formData, setFormData] = useState<EventConfig>(config);
|
||||
const [restart, setRestart] = useState(true);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
|
||||
const formDataObj = new FormData();
|
||||
Object.entries(formData).forEach(([key, value]) => {
|
||||
if (key === 'sessions') {
|
||||
formDataObj.append(key, JSON.stringify(value));
|
||||
} else {
|
||||
formDataObj.append(key, value.toString());
|
||||
}
|
||||
});
|
||||
if (restart) {
|
||||
formDataObj.append('restart', 'on');
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await updateEventConfigAction(serverId, formDataObj);
|
||||
if (!result.success) {
|
||||
console.error('Failed to update event config:', result.message);
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
export function EventConfigEditor({ formData, disabled, onFormDataChange }: EventConfigEditorProps) {
|
||||
const handleInputChange = (key: keyof EventConfig, value: string | number) => {
|
||||
if (key === 'sessions') return;
|
||||
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
onFormDataChange({
|
||||
...formData,
|
||||
[key]:
|
||||
typeof formData[key] === 'number'
|
||||
? typeof value === 'string'
|
||||
? parseFloat(value) || 0
|
||||
: value
|
||||
: value
|
||||
}));
|
||||
});
|
||||
};
|
||||
|
||||
const handleSessionChange = (index: number, field: keyof Session, value: string | number) => {
|
||||
@@ -67,11 +36,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
[field]:
|
||||
field === 'sessionType' ? value : typeof value === 'string' ? parseFloat(value) || 0 : value
|
||||
};
|
||||
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
sessions: newSessions
|
||||
}));
|
||||
onFormDataChange({ ...formData, sessions: newSessions });
|
||||
};
|
||||
|
||||
const addSession = () => {
|
||||
@@ -82,22 +47,15 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
sessionType: 'P',
|
||||
sessionDurationMinutes: 20
|
||||
};
|
||||
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
sessions: [...prev.sessions, newSession]
|
||||
}));
|
||||
onFormDataChange({ ...formData, sessions: [...formData.sessions, newSession] });
|
||||
};
|
||||
|
||||
const removeSession = (index: number) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
sessions: prev.sessions.filter((_, i) => i !== index)
|
||||
}));
|
||||
onFormDataChange({ ...formData, sessions: formData.sessions.filter((_, i) => i !== index) });
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-4xl space-y-8">
|
||||
<div className="max-w-4xl space-y-8">
|
||||
<div className="space-y-6">
|
||||
<h3 className="border-b border-border-muted pb-2 text-sm font-semibold text-primary">
|
||||
Basic Event Settings
|
||||
@@ -106,7 +64,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
<div>
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">Track</label>
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.track}
|
||||
onChange={(e) => handleInputChange('track', e.target.value)}
|
||||
className="form-select w-full"
|
||||
@@ -145,7 +103,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.preRaceWaitingTimeSeconds}
|
||||
onChange={(e) => handleInputChange('preRaceWaitingTimeSeconds', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -159,7 +117,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.sessionOverTimeSeconds}
|
||||
onChange={(e) => handleInputChange('sessionOverTimeSeconds', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -173,7 +131,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.postQualySeconds}
|
||||
onChange={(e) => handleInputChange('postQualySeconds', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -187,7 +145,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.postRaceSeconds}
|
||||
onChange={(e) => handleInputChange('postRaceSeconds', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -208,7 +166,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.ambientTemp}
|
||||
onChange={(e) => handleInputChange('ambientTemp', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -223,7 +181,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.cloudLevel}
|
||||
onChange={(e) => handleInputChange('cloudLevel', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -237,7 +195,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">Rain (0.0-1.0)</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.rain}
|
||||
onChange={(e) => handleInputChange('rain', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -253,7 +211,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.weatherRandomness}
|
||||
onChange={(e) => handleInputChange('weatherRandomness', e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -267,7 +225,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
Simracer Weather Conditions
|
||||
</label>
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.simracerWeatherConditions}
|
||||
onChange={(e) => handleInputChange('simracerWeatherConditions', e.target.value)}
|
||||
className="form-select w-full"
|
||||
@@ -282,7 +240,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
Fixed Condition Qualification
|
||||
</label>
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.isFixedConditionQualification}
|
||||
onChange={(e) => handleInputChange('isFixedConditionQualification', e.target.value)}
|
||||
className="form-select w-full"
|
||||
@@ -300,7 +258,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
<button
|
||||
type="button"
|
||||
onClick={addSession}
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
className="rounded-md border border-border bg-overlay px-3 py-1.5 text-xs font-medium text-secondary hover:bg-border disabled:opacity-40"
|
||||
>
|
||||
+ Add Session
|
||||
@@ -315,7 +273,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeSession(index)}
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
className="rounded px-2 py-1 text-xs text-red hover:bg-red-bg disabled:opacity-40"
|
||||
>
|
||||
Remove
|
||||
@@ -328,7 +286,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
Session Type
|
||||
</label>
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={session.sessionType}
|
||||
onChange={(e) => handleSessionChange(index, 'sessionType', e.target.value)}
|
||||
className="form-select w-full text-sm"
|
||||
@@ -347,7 +305,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={session.hourOfDay}
|
||||
onChange={(e) => handleSessionChange(index, 'hourOfDay', e.target.value)}
|
||||
className="form-input w-full text-sm"
|
||||
@@ -362,7 +320,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={session.dayOfWeekend}
|
||||
onChange={(e) => handleSessionChange(index, 'dayOfWeekend', e.target.value)}
|
||||
className="form-input w-full text-sm"
|
||||
@@ -377,7 +335,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={session.timeMultiplier}
|
||||
onChange={(e) => handleSessionChange(index, 'timeMultiplier', e.target.value)}
|
||||
className="form-input w-full text-sm"
|
||||
@@ -392,7 +350,7 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={session.sessionDurationMinutes}
|
||||
onChange={(e) =>
|
||||
handleSessionChange(index, 'sessionDurationMinutes', e.target.value)
|
||||
@@ -406,28 +364,6 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border pt-6">
|
||||
<label className="flex items-center gap-2 text-sm text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={restart}
|
||||
onChange={(e) => setRestart(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-border bg-overlay accent-green focus:ring-1 focus:ring-blue"
|
||||
/>
|
||||
Restart server after saving
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="rounded-md bg-btn-green border border-btn-green px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-btn-green-hover disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{isSubmitting ? 'Saving…' : 'Save Changes'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { EventRules } from '@/lib/schemas/config';
|
||||
import { updateEventRulesAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface EventRulesEditorProps {
|
||||
serverId: string;
|
||||
config: EventRules;
|
||||
formData: EventRules;
|
||||
disabled?: boolean;
|
||||
onFormDataChange: (data: EventRules) => void;
|
||||
}
|
||||
|
||||
const numberFields = [
|
||||
@@ -68,42 +67,13 @@ const booleanFields = [
|
||||
}
|
||||
];
|
||||
|
||||
export function EventRulesEditor({ serverId, config }: EventRulesEditorProps) {
|
||||
const [formData, setFormData] = useState<EventRules>(config);
|
||||
const [restart, setRestart] = useState(true);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
|
||||
const formDataObj = new FormData();
|
||||
Object.entries(formData).forEach(([key, value]) => {
|
||||
formDataObj.append(key, value.toString());
|
||||
});
|
||||
if (restart) {
|
||||
formDataObj.append('restart', 'on');
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await updateEventRulesAction(serverId, formDataObj);
|
||||
if (!result.success) {
|
||||
console.error('Failed to update event rules:', result.message);
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleInputChange = (key: keyof EventRules, value: string | number | boolean) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[key]: value
|
||||
}));
|
||||
export function EventRulesEditor({ formData, disabled, onFormDataChange }: EventRulesEditorProps) {
|
||||
const handleInputChange = (key: keyof EventRules, value: number) => {
|
||||
onFormDataChange({ ...formData, [key]: value });
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-4xl space-y-8">
|
||||
<div className="max-w-4xl space-y-8">
|
||||
<div className="space-y-6">
|
||||
<h3 className="border-b border-border-muted pb-2 text-sm font-semibold text-primary">Race Rules</h3>
|
||||
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
|
||||
@@ -112,7 +82,7 @@ export function EventRulesEditor({ serverId, config }: EventRulesEditorProps) {
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">{label}</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData[key] as number}
|
||||
onChange={(e) => handleInputChange(key, parseInt(e.target.value) || 0)}
|
||||
className="form-input w-full"
|
||||
@@ -133,9 +103,9 @@ export function EventRulesEditor({ serverId, config }: EventRulesEditorProps) {
|
||||
<div key={key}>
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">{label}</label>
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData[key] ? 'true' : 'false'}
|
||||
onChange={(e) => handleInputChange(key, e.target.value === 'true')}
|
||||
onChange={(e) => handleInputChange(key, e.target.value === 'true' ? 1 : 0)}
|
||||
className="form-select w-full"
|
||||
>
|
||||
<option value="false">No</option>
|
||||
@@ -145,28 +115,6 @@ export function EventRulesEditor({ serverId, config }: EventRulesEditorProps) {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border pt-6">
|
||||
<label className="flex items-center gap-2 text-sm text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={restart}
|
||||
onChange={(e) => setRestart(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-border bg-overlay accent-green focus:ring-1 focus:ring-blue"
|
||||
/>
|
||||
Restart server after saving
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="rounded-md bg-btn-green border border-btn-green px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-btn-green-hover disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{isSubmitting ? 'Saving…' : 'Save Changes'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { ServerSettings } from '@/lib/schemas/config';
|
||||
import { updateServerSettingsAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface ServerSettingsEditorProps {
|
||||
serverId: string;
|
||||
config: ServerSettings;
|
||||
formData: ServerSettings;
|
||||
disabled?: boolean;
|
||||
onFormDataChange: (data: ServerSettings) => void;
|
||||
}
|
||||
|
||||
const textFields = [
|
||||
@@ -87,42 +86,13 @@ const selectFields = [
|
||||
}
|
||||
];
|
||||
|
||||
export function ServerSettingsEditor({ serverId, config }: ServerSettingsEditorProps) {
|
||||
const [formData, setFormData] = useState<ServerSettings>(config);
|
||||
const [restart, setRestart] = useState(true);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
|
||||
const formDataObj = new FormData();
|
||||
Object.entries(formData).forEach(([key, value]) => {
|
||||
formDataObj.append(key, value?.toString() ?? '');
|
||||
});
|
||||
if (restart) {
|
||||
formDataObj.append('restart', 'on');
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await updateServerSettingsAction(serverId, formDataObj);
|
||||
if (!result.success) {
|
||||
console.error('Failed to update server settings:', result.message);
|
||||
}
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
export function ServerSettingsEditor({ formData, disabled, onFormDataChange }: ServerSettingsEditorProps) {
|
||||
const handleInputChange = (key: keyof ServerSettings, value: string | number) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
[key]: value
|
||||
}));
|
||||
onFormDataChange({ ...formData, [key]: value });
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-4xl space-y-8">
|
||||
<div className="max-w-4xl space-y-8">
|
||||
<div className="space-y-6">
|
||||
<h3 className="border-b border-border-muted pb-2 text-sm font-semibold text-primary">
|
||||
Basic Settings
|
||||
@@ -133,7 +103,7 @@ export function ServerSettingsEditor({ serverId, config }: ServerSettingsEditorP
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">{label}</label>
|
||||
<input
|
||||
type={type}
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData[key] as string}
|
||||
onChange={(e) => handleInputChange(key, e.target.value)}
|
||||
className="form-input w-full"
|
||||
@@ -144,7 +114,7 @@ export function ServerSettingsEditor({ serverId, config }: ServerSettingsEditorP
|
||||
<div>
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">Car Group</label>
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.carGroup}
|
||||
onChange={(e) => handleInputChange('carGroup', e.target.value)}
|
||||
className="form-select w-full"
|
||||
@@ -169,7 +139,7 @@ export function ServerSettingsEditor({ serverId, config }: ServerSettingsEditorP
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">{label}</label>
|
||||
<input
|
||||
type="number"
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData[key] as number}
|
||||
onChange={(e) => handleInputChange(key, parseInt(e.target.value) || 0)}
|
||||
className="form-input w-full"
|
||||
@@ -190,7 +160,7 @@ export function ServerSettingsEditor({ serverId, config }: ServerSettingsEditorP
|
||||
<div key={key}>
|
||||
<label className="mb-1.5 block text-sm font-medium text-secondary">{label}</label>
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData[key] as number}
|
||||
onChange={(e) => handleInputChange(key, parseInt(e.target.value))}
|
||||
className="form-select w-full"
|
||||
@@ -206,7 +176,7 @@ export function ServerSettingsEditor({ serverId, config }: ServerSettingsEditorP
|
||||
Formation Lap Type
|
||||
</label>
|
||||
<select
|
||||
disabled={isSubmitting}
|
||||
disabled={disabled}
|
||||
value={formData.formationLapType}
|
||||
onChange={(e) => handleInputChange('formationLapType', parseInt(e.target.value))}
|
||||
className="form-select w-full"
|
||||
@@ -220,28 +190,6 @@ export function ServerSettingsEditor({ serverId, config }: ServerSettingsEditorP
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t border-border pt-6">
|
||||
<label className="flex items-center gap-2 text-sm text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={restart}
|
||||
onChange={(e) => setRestart(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-border bg-overlay accent-green focus:ring-1 focus:ring-blue"
|
||||
/>
|
||||
Restart server after saving
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting}
|
||||
className="rounded-md bg-btn-green border border-btn-green px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-btn-green-hover disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{isSubmitting ? 'Saving…' : 'Save Changes'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import { clearExpiredSessionAction, loginAction, LoginResult } from '@/lib/actions/auth';
|
||||
import { use, useActionState, useEffect } from 'react';
|
||||
import type { HealthStatus } from '@/lib/api/server/health';
|
||||
import { Badge } from '@/components/ui/Badge';
|
||||
|
||||
const initialState: LoginResult = {
|
||||
message: '',
|
||||
@@ -9,9 +11,11 @@ const initialState: LoginResult = {
|
||||
};
|
||||
|
||||
export default function LoginForm({
|
||||
searchParams
|
||||
searchParams,
|
||||
health
|
||||
}: {
|
||||
searchParams: Promise<{ expired: boolean | undefined }>;
|
||||
health: HealthStatus;
|
||||
}) {
|
||||
const params = use(searchParams);
|
||||
const expired = params.expired;
|
||||
@@ -28,6 +32,13 @@ export default function LoginForm({
|
||||
<div className="text-center">
|
||||
<h1 className="text-xl font-bold text-primary">ACC Server Manager</h1>
|
||||
<p className="mt-1 text-sm text-muted">Sign in to manage your servers</p>
|
||||
<div className="mt-2 flex justify-center">
|
||||
{health.healthy ? (
|
||||
<Badge variant="green">API v{health.version}</Badge>
|
||||
) : (
|
||||
<Badge variant="red">API unreachable</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{expired && (
|
||||
<div className="rounded-md border border-yellow/30 bg-yellow-bg px-3 py-2 text-sm text-yellow">
|
||||
|
||||
@@ -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,9 +8,12 @@ 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 { ServerLogViewer } from '@/components/server/ServerLogViewer';
|
||||
import { useState } from 'react';
|
||||
import { StateHistoryStats } from '@/lib/schemas';
|
||||
import { Leaderboard } from '@/lib/schemas/leaderboard';
|
||||
import { bulkUpdateConfigurationsAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface ServerConfigurationTabsProps {
|
||||
serverId: string;
|
||||
@@ -25,9 +28,19 @@ 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: '📋' },
|
||||
{ id: ServerTab.logs, name: 'Logs', icon: '📄' }
|
||||
];
|
||||
|
||||
const configTabs = new Set([
|
||||
ServerTab.configuration,
|
||||
ServerTab.assistRules,
|
||||
ServerTab.event,
|
||||
ServerTab.eventRules,
|
||||
ServerTab.settings
|
||||
]);
|
||||
|
||||
export function ServerConfigurationTabs({
|
||||
serverId,
|
||||
configurations,
|
||||
@@ -36,29 +49,105 @@ export function ServerConfigurationTabs({
|
||||
}: ServerConfigurationTabsProps) {
|
||||
const [currentTab, setCurrentTab] = useState(ServerTab.statistics);
|
||||
|
||||
const [configData, setConfigData] = useState(configurations.configuration);
|
||||
const [assistData, setAssistData] = useState(configurations.assistRules);
|
||||
const [eventData, setEventData] = useState(configurations.event);
|
||||
const [eventRulesData, setEventRulesData] = useState(configurations.eventRules);
|
||||
const [settingsData, setSettingsData] = useState(configurations.settings);
|
||||
|
||||
const [restart, setRestart] = useState(true);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const [saveSuccess, setSaveSuccess] = useState(false);
|
||||
|
||||
const handleSaveAll = async () => {
|
||||
setIsSubmitting(true);
|
||||
setSaveError(null);
|
||||
setSaveSuccess(false);
|
||||
|
||||
const result = await bulkUpdateConfigurationsAction(
|
||||
serverId,
|
||||
{
|
||||
configuration: configData,
|
||||
assistRules: assistData,
|
||||
event: eventData,
|
||||
eventRules: eventRulesData,
|
||||
settings: settingsData
|
||||
},
|
||||
restart
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
setSaveSuccess(true);
|
||||
setTimeout(() => setSaveSuccess(false), 3000);
|
||||
} else {
|
||||
setSaveError(result.message);
|
||||
}
|
||||
|
||||
setIsSubmitting(false);
|
||||
};
|
||||
|
||||
const isConfigTab = configTabs.has(currentTab);
|
||||
|
||||
const renderTabContent = () => {
|
||||
switch (currentTab) {
|
||||
case ServerTab.statistics:
|
||||
return <StatisticsDashboard stats={statistics} />;
|
||||
|
||||
case ServerTab.configuration:
|
||||
return <ConfigurationEditor serverId={serverId} config={configurations.configuration} />;
|
||||
return (
|
||||
<ConfigurationEditor
|
||||
formData={configData}
|
||||
disabled={isSubmitting}
|
||||
onFormDataChange={setConfigData}
|
||||
/>
|
||||
);
|
||||
|
||||
case ServerTab.assistRules:
|
||||
return <AssistRulesEditor serverId={serverId} config={configurations.assistRules} />;
|
||||
return (
|
||||
<AssistRulesEditor
|
||||
formData={assistData}
|
||||
disabled={isSubmitting}
|
||||
onFormDataChange={setAssistData}
|
||||
/>
|
||||
);
|
||||
|
||||
case ServerTab.event:
|
||||
return <EventConfigEditor serverId={serverId} config={configurations.event} />;
|
||||
return (
|
||||
<EventConfigEditor
|
||||
formData={eventData}
|
||||
disabled={isSubmitting}
|
||||
onFormDataChange={setEventData}
|
||||
/>
|
||||
);
|
||||
|
||||
case ServerTab.eventRules:
|
||||
return <EventRulesEditor serverId={serverId} config={configurations.eventRules} />;
|
||||
return (
|
||||
<EventRulesEditor
|
||||
formData={eventRulesData}
|
||||
disabled={isSubmitting}
|
||||
onFormDataChange={setEventRulesData}
|
||||
/>
|
||||
);
|
||||
|
||||
case ServerTab.settings:
|
||||
return <ServerSettingsEditor serverId={serverId} config={configurations.settings} />;
|
||||
return (
|
||||
<ServerSettingsEditor
|
||||
formData={settingsData}
|
||||
disabled={isSubmitting}
|
||||
onFormDataChange={setSettingsData}
|
||||
/>
|
||||
);
|
||||
|
||||
case ServerTab.leaderboard:
|
||||
return <LeaderboardManager serverId={serverId} initialData={leaderboard} />;
|
||||
|
||||
case ServerTab.activityLog:
|
||||
return <ActivityLogTable serverId={serverId} />;
|
||||
|
||||
case ServerTab.logs:
|
||||
return <ServerLogViewer serverId={serverId} />;
|
||||
|
||||
default:
|
||||
return (
|
||||
<div className="py-12 text-center">
|
||||
@@ -92,6 +181,37 @@ export function ServerConfigurationTabs({
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{isConfigTab && (
|
||||
<div className="flex items-center justify-between border-b border-border-muted bg-overlay px-5 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
{saveError && (
|
||||
<p className="text-sm text-red">{saveError}</p>
|
||||
)}
|
||||
{saveSuccess && (
|
||||
<p className="text-sm text-green">All configurations saved.</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<label className="flex items-center gap-2 text-sm text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={restart}
|
||||
onChange={(e) => setRestart(e.target.checked)}
|
||||
className="h-4 w-4 rounded border-border bg-overlay accent-green focus:ring-1 focus:ring-blue"
|
||||
/>
|
||||
Restart after saving
|
||||
</label>
|
||||
<button
|
||||
onClick={handleSaveAll}
|
||||
disabled={isSubmitting}
|
||||
className="rounded-md bg-btn-green border border-btn-green px-5 py-2 text-sm font-medium text-white transition-colors hover:bg-btn-green-hover disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{isSubmitting ? 'Saving…' : 'Save All'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1 overflow-y-auto p-5">{renderTabContent()}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
153
src/components/server/ServerLogViewer.tsx
Normal file
153
src/components/server/ServerLogViewer.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useWebSocket } from '@/lib/websocket/context';
|
||||
import type { WebSocketMessage } from '@/lib/schemas/websocket';
|
||||
import { getServerLogAction } from '@/lib/actions/serverLog';
|
||||
|
||||
const MAX_BUFFER = 5000;
|
||||
const LINE_OPTIONS = [100, 500, 1000, 5000] as const;
|
||||
|
||||
interface ServerLogViewerProps {
|
||||
serverId: string;
|
||||
}
|
||||
|
||||
export function ServerLogViewer({ serverId }: ServerLogViewerProps) {
|
||||
const [lines, setLines] = useState<string[]>([]);
|
||||
const [initialLines, setInitialLines] = useState<number>(100);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isPaused, setIsPaused] = useState(false);
|
||||
|
||||
const { associateWithServer, addMessageHandler, removeMessageHandler } = useWebSocket();
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const isPausedRef = useRef(false);
|
||||
|
||||
const appendLines = useCallback((newLines: string[]) => {
|
||||
setLines((prev) => {
|
||||
const combined = [...prev, ...newLines];
|
||||
return combined.length > MAX_BUFFER ? combined.slice(combined.length - MAX_BUFFER) : combined;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const fetchInitial = useCallback(
|
||||
async (count: number) => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
const result = await getServerLogAction(serverId, count);
|
||||
setIsLoading(false);
|
||||
if (!result.success) {
|
||||
setError(result.message);
|
||||
return;
|
||||
}
|
||||
setLines(result.lines);
|
||||
},
|
||||
[serverId]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
associateWithServer(serverId);
|
||||
fetchInitial(initialLines);
|
||||
}, [serverId, associateWithServer, fetchInitial, initialLines]);
|
||||
|
||||
const handleMessage = useCallback(
|
||||
(message: WebSocketMessage) => {
|
||||
if (message.type !== 'log_line') return;
|
||||
if (message.server_id !== serverId) return;
|
||||
appendLines([message.data.line]);
|
||||
},
|
||||
[serverId, appendLines]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
addMessageHandler(handleMessage);
|
||||
return () => {
|
||||
removeMessageHandler(handleMessage);
|
||||
};
|
||||
}, [addMessageHandler, removeMessageHandler, handleMessage]);
|
||||
|
||||
// Auto-scroll to bottom when new lines arrive, unless paused
|
||||
useEffect(() => {
|
||||
if (!isPausedRef.current && scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
}
|
||||
}, [lines]);
|
||||
|
||||
const handleScroll = () => {
|
||||
if (!scrollRef.current) return;
|
||||
const { scrollTop, scrollHeight, clientHeight } = scrollRef.current;
|
||||
const isAtBottom = scrollHeight - scrollTop - clientHeight < 40;
|
||||
const shouldPause = !isAtBottom;
|
||||
isPausedRef.current = shouldPause;
|
||||
setIsPaused(shouldPause);
|
||||
};
|
||||
|
||||
const jumpToBottom = () => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||
}
|
||||
isPausedRef.current = false;
|
||||
setIsPaused(false);
|
||||
};
|
||||
|
||||
const handleLineLimitChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
|
||||
const count = Number(e.target.value);
|
||||
setInitialLines(count);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<label className="text-xs text-subtle">Initial lines</label>
|
||||
<select
|
||||
value={initialLines}
|
||||
onChange={handleLineLimitChange}
|
||||
className="form-input w-28 text-sm"
|
||||
>
|
||||
{LINE_OPTIONS.map((n) => (
|
||||
<option key={n} value={n}>
|
||||
{n}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="ml-auto text-xs text-subtle">{lines.length} lines buffered</span>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-red">{error}</p>}
|
||||
|
||||
<div className="relative">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
onScroll={handleScroll}
|
||||
className="h-[calc(100vh-280px)] min-h-64 overflow-y-auto rounded-lg border border-border bg-base p-3 font-mono text-xs text-secondary"
|
||||
>
|
||||
{isLoading ? (
|
||||
<span className="text-muted">Loading…</span>
|
||||
) : lines.length === 0 ? (
|
||||
<span className="text-muted">No log output yet.</span>
|
||||
) : (
|
||||
lines.map((line, i) => (
|
||||
<div key={i} className="leading-5 whitespace-pre-wrap break-all">
|
||||
{line}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isPaused && (
|
||||
<div className="absolute bottom-3 left-1/2 flex -translate-x-1/2 items-center gap-2">
|
||||
<div className="flex items-center gap-2 rounded-full border border-border bg-overlay px-3 py-1.5 shadow-lg">
|
||||
<span className="text-xs text-muted">Paused</span>
|
||||
<button
|
||||
onClick={jumpToBottom}
|
||||
className="text-xs font-medium text-blue hover:underline"
|
||||
>
|
||||
Jump to bottom
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
? [
|
||||
{
|
||||
|
||||
20
src/lib/actions/activityLog.ts
Normal file
20
src/lib/actions/activityLog.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
'use server';
|
||||
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { getActivityLog } from '@/lib/api/server/activityLog';
|
||||
import type { ActivityLog, ActivityLogFilter } from '@/lib/schemas/activityLog';
|
||||
|
||||
export async function getActivityLogAction(
|
||||
filter?: ActivityLogFilter
|
||||
): Promise<{ success: true; data: ActivityLog[] } | { success: false; message: string }> {
|
||||
try {
|
||||
const session = await requireAuth();
|
||||
const data = await getActivityLog(session.token!, filter);
|
||||
return { success: true, data };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Failed to fetch activity log'
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { updateServerConfiguration } from '@/lib/api/server/configuration';
|
||||
import { updateServerConfiguration, bulkUpdateServerConfigurations } from '@/lib/api/server/configuration';
|
||||
import {
|
||||
assistRulesSchema,
|
||||
ConfigFile,
|
||||
configurationsSchema,
|
||||
eventConfigSchema,
|
||||
eventRulesSchema,
|
||||
serverSettingsSchema
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
import type {
|
||||
Configuration,
|
||||
AssistRules,
|
||||
Configurations,
|
||||
EventConfig,
|
||||
EventRules,
|
||||
ServerSettings
|
||||
@@ -232,3 +234,28 @@ export async function updateEventRulesAction(serverId: string, formData: FormDat
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function bulkUpdateConfigurationsAction(
|
||||
serverId: string,
|
||||
configs: Configurations,
|
||||
restart: boolean
|
||||
) {
|
||||
try {
|
||||
const session = await requireAuth();
|
||||
|
||||
const validated = configurationsSchema.safeParse(configs);
|
||||
if (!validated.success) {
|
||||
return { success: false, message: validated.error.message };
|
||||
}
|
||||
|
||||
await bulkUpdateServerConfigurations(session.token!, serverId, validated.data, restart);
|
||||
revalidatePath(`/dashboard/server/${serverId}`);
|
||||
|
||||
return { success: true, message: 'All configurations updated successfully' };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Failed to update configurations'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
20
src/lib/actions/serverLog.ts
Normal file
20
src/lib/actions/serverLog.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
'use server';
|
||||
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { getServerLog } from '@/lib/api/server/serverLog';
|
||||
|
||||
export async function getServerLogAction(
|
||||
serverId: string,
|
||||
lines: number = 100
|
||||
): Promise<{ success: true; lines: string[] } | { success: false; message: string }> {
|
||||
try {
|
||||
const session = await requireAuth();
|
||||
const data = await getServerLog(session.token!, serverId, lines);
|
||||
return { success: true, lines: data };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Failed to fetch server log'
|
||||
};
|
||||
}
|
||||
}
|
||||
31
src/lib/api/server/activityLog.ts
Normal file
31
src/lib/api/server/activityLog.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
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.server_id) params.set('server_id', filter.server_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,
|
||||
filter?: ActivityLogFilter
|
||||
): Promise<ActivityLog[]> {
|
||||
const query = buildQuery(filter);
|
||||
const response = await fetchServerAPI<ActivityLog[]>(`/activity-log${query}`, token);
|
||||
return activityLogSchema.array().parse(response.data);
|
||||
}
|
||||
@@ -8,14 +8,23 @@ import {
|
||||
} from '@/lib/schemas/config';
|
||||
import * as z from 'zod';
|
||||
|
||||
export type ConfigAuditRecord = {
|
||||
id: string;
|
||||
serverId: string;
|
||||
configFile: string;
|
||||
oldConfig: string;
|
||||
newConfig: string;
|
||||
changedAt: string;
|
||||
};
|
||||
|
||||
const serverRoute = '/server';
|
||||
|
||||
export async function getServerConfigurations(
|
||||
token: string,
|
||||
serverId: string
|
||||
): Promise<Configurations> {
|
||||
const response = await fetchServerAPI<Configurations>(`${serverRoute}/${serverId}/config`, token);
|
||||
return configurationsSchema.parse(response.data);
|
||||
const response = await fetchServerAPI<Configurations>(`${serverRoute}/${serverId}/config`, token);
|
||||
return configurationsSchema.parse(response.data);
|
||||
}
|
||||
|
||||
export function validateConfig(
|
||||
@@ -45,8 +54,26 @@ export async function updateServerConfiguration(
|
||||
config: Config,
|
||||
restart = false
|
||||
): Promise<void> {
|
||||
await fetchServerAPI(`${serverRoute}/${serverId}/config/${configType}?override=true`, token, 'PUT', {
|
||||
...validateConfig(configType, config),
|
||||
restart
|
||||
});
|
||||
await fetchServerAPI(
|
||||
`${serverRoute}/${serverId}/config/${configType}?override=true&restart=${restart}`,
|
||||
token,
|
||||
'PUT',
|
||||
{
|
||||
...validateConfig(configType, config)
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export async function bulkUpdateServerConfigurations(
|
||||
token: string,
|
||||
serverId: string,
|
||||
configs: Configurations,
|
||||
restart = false
|
||||
): Promise<void> {
|
||||
await fetchServerAPI<ConfigAuditRecord[]>(
|
||||
`${serverRoute}/${serverId}/config?override=true&restart=${restart}`,
|
||||
token,
|
||||
'PATCH',
|
||||
configs
|
||||
);
|
||||
}
|
||||
|
||||
17
src/lib/api/server/health.ts
Normal file
17
src/lib/api/server/health.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
const BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080';
|
||||
|
||||
export type HealthStatus = { healthy: true; version: string } | { healthy: false; version: null };
|
||||
|
||||
export async function checkHealth(): Promise<HealthStatus> {
|
||||
try {
|
||||
const response = await fetch(`${BASE_URL}/system/health`, {
|
||||
method: 'GET',
|
||||
next: { revalidate: 0 }
|
||||
});
|
||||
if (!response.ok) return { healthy: false, version: null };
|
||||
const version = await response.text();
|
||||
return { healthy: true, version: version.trim() || 'unknown' };
|
||||
} catch {
|
||||
return { healthy: false, version: null };
|
||||
}
|
||||
}
|
||||
13
src/lib/api/server/serverLog.ts
Normal file
13
src/lib/api/server/serverLog.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
|
||||
export async function getServerLog(
|
||||
token: string,
|
||||
serverId: string,
|
||||
lines: number = 100
|
||||
): Promise<string[]> {
|
||||
const response = await fetchServerAPI<{ lines: string[] }>(
|
||||
`/server/${serverId}/log?lines=${lines}`,
|
||||
token
|
||||
);
|
||||
return response.data?.lines ?? [];
|
||||
}
|
||||
62
src/lib/schemas/activityLog.ts
Normal file
62
src/lib/schemas/activityLog.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
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>;
|
||||
|
||||
// Minimal server shape embedded in activity log responses (avoids circular import with server.ts)
|
||||
const embeddedServerSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string()
|
||||
}).passthrough();
|
||||
|
||||
export type EmbeddedServer = z.infer<typeof embeddedServerSchema>;
|
||||
|
||||
export const activityLogSchema = z.object({
|
||||
id: z.string(),
|
||||
serverId: z.string(),
|
||||
server: embeddedServerSchema.optional(),
|
||||
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(),
|
||||
server_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,9 @@ export enum ServerTab {
|
||||
event = 'event',
|
||||
eventRules = 'eventRules',
|
||||
settings = 'settings',
|
||||
leaderboard = 'leaderboard'
|
||||
leaderboard = 'leaderboard',
|
||||
activityLog = 'activityLog',
|
||||
logs = 'logs'
|
||||
}
|
||||
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>;
|
||||
|
||||
@@ -44,6 +44,13 @@ export const completeDataSchema = z.object({
|
||||
|
||||
export type CompleteData = z.infer<typeof completeDataSchema>;
|
||||
|
||||
// Log line data schema
|
||||
export const logLineDataSchema = z.object({
|
||||
line: z.string()
|
||||
});
|
||||
|
||||
export type LogLineData = z.infer<typeof logLineDataSchema>;
|
||||
|
||||
// WebSocket message schema using discriminated union
|
||||
export const webSocketMessageSchema = z.discriminatedUnion('type', [
|
||||
z.object({
|
||||
@@ -69,6 +76,12 @@ export const webSocketMessageSchema = z.discriminatedUnion('type', [
|
||||
server_id: z.string(),
|
||||
timestamp: z.number(),
|
||||
data: completeDataSchema
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal('log_line'),
|
||||
server_id: z.string(),
|
||||
timestamp: z.number(),
|
||||
data: logLineDataSchema
|
||||
})
|
||||
]);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user