Compare commits
16 Commits
v0.21.2
...
61f0b69176
| Author | SHA1 | Date | |
|---|---|---|---|
| 61f0b69176 | |||
| 2976468c9f | |||
| d56a399e8e | |||
| 8dc8f98add | |||
| d8d008b5e8 | |||
| 51f45a806e | |||
| 5b8698cf81 | |||
| 69a3836f13 | |||
| 69d92a3fc9 | |||
| e8bf8498b8 | |||
|
|
f15a0175b8 | ||
|
|
996f1a1385 | ||
|
|
0cbc6935db | ||
|
|
6563396a83 | ||
|
|
c005090ab1 | ||
|
|
6aeb654abf |
13072
package-lock.json
generated
13072
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -29,7 +29,8 @@
|
||||
"react-dom": "19.1.0",
|
||||
"react-hook-form": "^7.62.0",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss": "^4.1.12"
|
||||
"tailwindcss": "^4.1.12",
|
||||
"zod": "^4.1.11"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3",
|
||||
|
||||
23
src/app/dashboard/layout.tsx
Normal file
23
src/app/dashboard/layout.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { WebSocketProvider } from '@/lib/websocket/context';
|
||||
import { SteamCMDProvider } from '@/lib/context/SteamCMDContext';
|
||||
import { ServerCreationPopupProvider } from '@/lib/context/ServerCreationPopupContext';
|
||||
import { ServerCreationPopupContainer } from '@/components/server/ServerCreationPopupContainer';
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
|
||||
export default async function DashboardLayout({
|
||||
children
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
const session = await requireAuth();
|
||||
return (
|
||||
<WebSocketProvider openToken={session.openToken!}>
|
||||
<SteamCMDProvider>
|
||||
<ServerCreationPopupProvider>
|
||||
{children}
|
||||
<ServerCreationPopupContainer />
|
||||
</ServerCreationPopupProvider>
|
||||
</SteamCMDProvider>
|
||||
</WebSocketProvider>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,10 @@
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { getServers } from '@/lib/api/server/servers';
|
||||
import { hasPermission } from '@/lib/types';
|
||||
import { ServerCard } from '@/components/server/ServerCard';
|
||||
import { logoutAction } from '@/lib/actions/auth';
|
||||
import RefreshButton from '@/components/ui/RefreshButton';
|
||||
import { hasPermission } from '@/lib/schemas';
|
||||
import Link from 'next/link';
|
||||
import { ServerListWithActions } from '@/components/server/ServerListWithActions';
|
||||
import { WebSocketInitializer } from '@/components/websocket/WebSocketInitializer';
|
||||
import { SteamCMDNotification } from '@/components/ui/SteamCMDNotification';
|
||||
import LogoutButton from '@/components/ui/LogoutButton';
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const session = await requireAuth();
|
||||
@@ -15,7 +12,6 @@ export default async function DashboardPage() {
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-900 text-white">
|
||||
<WebSocketInitializer openToken={session.openToken} />
|
||||
<header className="bg-gray-800 shadow-md">
|
||||
<div className="mx-auto flex max-w-[120rem] items-center justify-between px-4 py-4 sm:px-6 lg:px-8">
|
||||
<h1 className="text-2xl font-bold">ACC Server Manager</h1>
|
||||
@@ -42,25 +38,7 @@ export default async function DashboardPage() {
|
||||
<span className="ml-1 hidden sm:inline">Users</span>
|
||||
</Link>
|
||||
)}
|
||||
<form action={logoutAction}>
|
||||
<button type="submit" className="flex items-center text-gray-300 hover:text-white">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="h-6 w-6"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
|
||||
/>
|
||||
</svg>
|
||||
<span className="ml-1 hidden sm:inline">Logout</span>
|
||||
</button>
|
||||
</form>
|
||||
<LogoutButton />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { getServerConfigurations } from '@/lib/api/server/configuration';
|
||||
import { ServerConfigurationTabs } from '@/components/server/ServerConfigurationTabs';
|
||||
import { ServerHeader } from '@/components/server/ServerHeader';
|
||||
import { getServerStatistics } from '@/lib/api/server/statistics';
|
||||
import { getLeaderboard } from '@/lib/api/server/leaderboard';
|
||||
import { subDays, formatISO } from 'date-fns';
|
||||
import { UTCDate } from '@date-fns/utc';
|
||||
|
||||
@@ -19,22 +20,24 @@ export default async function ServerPage({ params }: ServerPageProps) {
|
||||
const endDate = formatISO(today);
|
||||
const startDate = formatISO(subDays(today, 30));
|
||||
|
||||
const [server, configurations, statistics] = await Promise.all([
|
||||
const [server, configurations, statistics, leaderboard] = await Promise.all([
|
||||
getServer(session.token!, id),
|
||||
getServerConfigurations(session.token!, id),
|
||||
getServerStatistics(session.token!, id, startDate, endDate)
|
||||
getServerStatistics(session.token!, id, { startDate, endDate }),
|
||||
getLeaderboard(session.token!, id)
|
||||
]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-900 text-white">
|
||||
<div className="mx-auto max-w-[120rem] px-4 py-8 sm:px-6 lg:px-8">
|
||||
<ServerHeader server={server} />
|
||||
<ServerHeader server={server} user={session.user!} />
|
||||
|
||||
<div className="mt-8">
|
||||
<ServerConfigurationTabs
|
||||
serverId={id}
|
||||
configurations={configurations}
|
||||
statistics={statistics}
|
||||
leaderboard={leaderboard}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import type { Metadata } from 'next';
|
||||
import './globals.css';
|
||||
import { QueryProvider } from '@/components/providers/QueryProvider';
|
||||
import { WebSocketProvider } from '@/lib/websocket/context';
|
||||
import { SteamCMDProvider } from '@/lib/context/SteamCMDContext';
|
||||
import { ServerCreationPopupProvider } from '@/lib/context/ServerCreationPopupContext';
|
||||
import { ServerCreationPopupContainer } from '@/components/server/ServerCreationPopupContainer';
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'ACC Server Manager',
|
||||
@@ -18,20 +13,7 @@ export default function RootLayout({
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className="bg-gray-900 text-white antialiased">
|
||||
<QueryProvider>
|
||||
<WebSocketProvider
|
||||
websocketURL={process.env.NEXT_PUBLIC_WEBSOCKET_URL || 'ws://localhost:3000/ws'}
|
||||
>
|
||||
<SteamCMDProvider>
|
||||
<ServerCreationPopupProvider>
|
||||
{children}
|
||||
<ServerCreationPopupContainer />
|
||||
</ServerCreationPopupProvider>
|
||||
</SteamCMDProvider>
|
||||
</WebSocketProvider>
|
||||
</QueryProvider>
|
||||
</body>
|
||||
<body className="bg-gray-900 text-white antialiased">{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,65 +1,15 @@
|
||||
'use client';
|
||||
import { Suspense } from 'react';
|
||||
import LoginForm from '@/components/login/LoginForm';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
import { loginAction, LoginResult } from '@/lib/actions/auth';
|
||||
import { useActionState } from 'react';
|
||||
|
||||
const initialState: LoginResult = {
|
||||
message: '',
|
||||
success: true
|
||||
};
|
||||
|
||||
export default function LoginPage() {
|
||||
const [state, formAction] = useActionState(loginAction, initialState);
|
||||
export default function LoginPage({
|
||||
searchParams
|
||||
}: {
|
||||
searchParams: Promise<{ expired: boolean | undefined }>;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-900 px-4">
|
||||
<div className="w-full max-w-md space-y-8 rounded-lg bg-gray-800 p-8 shadow-lg">
|
||||
<div className="text-center">
|
||||
<h1 className="text-3xl font-bold text-white">ACC Server Manager</h1>
|
||||
<p className="mt-2 text-gray-400">Sign in to manage your servers</p>
|
||||
</div>
|
||||
{state?.success ? null : (
|
||||
<div className="rounded-md border border-red-700 bg-red-900/50 p-3 text-sm text-red-200">
|
||||
{state?.message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form action={formAction} className="space-y-6">
|
||||
<div>
|
||||
<label htmlFor="username" className="mb-2 block text-sm font-medium text-gray-300">
|
||||
Username
|
||||
</label>
|
||||
<input
|
||||
id="username"
|
||||
name="username"
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
required
|
||||
className="form-input w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="mb-2 block text-sm font-medium text-gray-300">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
className="form-input w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full rounded-md bg-blue-600 px-4 py-3 font-medium text-white transition-colors hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-800 focus:outline-none"
|
||||
>
|
||||
Sign in
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<Suspense fallback={<div>Loading...</div>}>
|
||||
<LoginForm searchParams={searchParams} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { logout } from '@/lib/auth/server';
|
||||
import { redirect, RedirectType } from 'next/navigation';
|
||||
|
||||
export async function GET() {
|
||||
await logout();
|
||||
redirect('/login', RedirectType.replace);
|
||||
}
|
||||
@@ -7,6 +7,6 @@ export default async function HomePage() {
|
||||
if (session.token && session.user) {
|
||||
redirect('/dashboard');
|
||||
} else {
|
||||
redirect('/logout');
|
||||
redirect('/login');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { AssistRules } from '@/lib/types/config';
|
||||
import type { AssistRules } from '@/lib/schemas/config';
|
||||
import { updateAssistRulesAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface AssistRulesEditorProps {
|
||||
@@ -9,6 +9,54 @@ interface AssistRulesEditorProps {
|
||||
config: AssistRules;
|
||||
}
|
||||
|
||||
const assistFields = [
|
||||
{
|
||||
key: 'stabilityControlLevelMax' as keyof AssistRules,
|
||||
label: 'Stability Control Level Max',
|
||||
type: 'number'
|
||||
},
|
||||
{
|
||||
key: 'disableAutosteer' as keyof AssistRules,
|
||||
label: 'Disable Autosteer',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoLights' as keyof AssistRules,
|
||||
label: 'Disable Auto Lights',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoWiper' as keyof AssistRules,
|
||||
label: 'Disable Auto Wiper',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoEngineStart' as keyof AssistRules,
|
||||
label: 'Disable Auto Engine Start',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoPitLimiter' as keyof AssistRules,
|
||||
label: 'Disable Auto Pit Limiter',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoGear' as keyof AssistRules,
|
||||
label: 'Disable Auto Gear',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoClutch' as keyof AssistRules,
|
||||
label: 'Disable Auto Clutch',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableIdealLine' as keyof AssistRules,
|
||||
label: 'Disable Ideal Line',
|
||||
type: 'select'
|
||||
}
|
||||
];
|
||||
|
||||
export function AssistRulesEditor({ serverId, config }: AssistRulesEditorProps) {
|
||||
const [formData, setFormData] = useState<AssistRules>(config);
|
||||
const [restart, setRestart] = useState(true);
|
||||
@@ -43,54 +91,6 @@ export function AssistRulesEditor({ serverId, config }: AssistRulesEditorProps)
|
||||
}));
|
||||
};
|
||||
|
||||
const assistFields = [
|
||||
{
|
||||
key: 'stabilityControlLevelMax' as keyof AssistRules,
|
||||
label: 'Stability Control Level Max',
|
||||
type: 'number'
|
||||
},
|
||||
{
|
||||
key: 'disableAutosteer' as keyof AssistRules,
|
||||
label: 'Disable Autosteer',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoLights' as keyof AssistRules,
|
||||
label: 'Disable Auto Lights',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoWiper' as keyof AssistRules,
|
||||
label: 'Disable Auto Wiper',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoEngineStart' as keyof AssistRules,
|
||||
label: 'Disable Auto Engine Start',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoPitLimiter' as keyof AssistRules,
|
||||
label: 'Disable Auto Pit Limiter',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoGear' as keyof AssistRules,
|
||||
label: 'Disable Auto Gear',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableAutoClutch' as keyof AssistRules,
|
||||
label: 'Disable Auto Clutch',
|
||||
type: 'select'
|
||||
},
|
||||
{
|
||||
key: 'disableIdealLine' as keyof AssistRules,
|
||||
label: 'Disable Ideal Line',
|
||||
type: 'select'
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-3xl space-y-6">
|
||||
<div className="grid grid-cols-1 gap-6 md:grid-cols-2">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { Configuration } from '@/lib/types/config';
|
||||
import type { Configuration } from '@/lib/schemas/config';
|
||||
import { updateConfigurationAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface ConfigurationEditorProps {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { EventConfig, Session } from '@/lib/types/config';
|
||||
import type { EventConfig, Session } from '@/lib/schemas/config';
|
||||
import { updateEventConfigAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface EventConfigEditorProps {
|
||||
@@ -9,6 +9,12 @@ interface EventConfigEditorProps {
|
||||
config: EventConfig;
|
||||
}
|
||||
|
||||
const sessionTypes = [
|
||||
{ value: 'P', label: 'Practice' },
|
||||
{ value: 'Q', label: 'Qualifying' },
|
||||
{ value: 'R', label: 'Race' }
|
||||
];
|
||||
|
||||
export function EventConfigEditor({ serverId, config }: EventConfigEditorProps) {
|
||||
const [formData, setFormData] = useState<EventConfig>(config);
|
||||
const [restart, setRestart] = useState(true);
|
||||
@@ -90,12 +96,6 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
}));
|
||||
};
|
||||
|
||||
const sessionTypes = [
|
||||
{ value: 'P', label: 'Practice' },
|
||||
{ value: 'Q', label: 'Qualifying' },
|
||||
{ value: 'R', label: 'Race' }
|
||||
];
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-4xl space-y-8">
|
||||
<div className="space-y-6">
|
||||
@@ -113,22 +113,29 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
|
||||
>
|
||||
<option value="barcelona">Barcelona</option>
|
||||
<option value="brands_hatch">Brands Hatch</option>
|
||||
<option value="donington">Donington</option>
|
||||
<option value="cota">COTA</option>
|
||||
<option value="hungaroring">Hungaroring</option>
|
||||
<option value="imola">Imola</option>
|
||||
<option value="indianapolis">Indianapolis</option>
|
||||
<option value="kyalami">Kyalami</option>
|
||||
<option value="laguna_seca">Laguna Seca</option>
|
||||
<option value="misano">Misano</option>
|
||||
<option value="monza">Monza</option>
|
||||
<option value="mount_panorama">Mount Panorama</option>
|
||||
<option value="nurburgring">Nurburgring</option>
|
||||
<option value="nurburgring_24h">Nurburgring 24h</option>
|
||||
<option value="oulton_park">Oulton Park</option>
|
||||
<option value="paul_ricard">Paul Ricard</option>
|
||||
<option value="red_bull_ring">Red Bull Ring</option>
|
||||
<option value="silverstone">Silverstone</option>
|
||||
<option value="snetterton">Snetterton</option>
|
||||
<option value="spa">Spa-Francorchamps</option>
|
||||
<option value="suzuka">Suzuka</option>
|
||||
<option value="valencia">Valencia</option>
|
||||
<option value="zandvoort">Zandvoort</option>
|
||||
<option value="zolder">Zolder</option>
|
||||
<option value="watkins_glen">Watkins Glen</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { EventRules } from '@/lib/types/config';
|
||||
import type { EventRules } from '@/lib/schemas/config';
|
||||
import { updateEventRulesAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface EventRulesEditorProps {
|
||||
@@ -9,6 +9,65 @@ interface EventRulesEditorProps {
|
||||
config: EventRules;
|
||||
}
|
||||
|
||||
const numberFields = [
|
||||
{
|
||||
key: 'qualifyStandingType' as keyof EventRules,
|
||||
label: 'Qualify Standing Type',
|
||||
min: -1,
|
||||
max: 1
|
||||
},
|
||||
{
|
||||
key: 'pitWindowLengthSec' as keyof EventRules,
|
||||
label: 'Pit Window Length (seconds)',
|
||||
min: -1
|
||||
},
|
||||
{
|
||||
key: 'driverStintTimeSec' as keyof EventRules,
|
||||
label: 'Driver Stint Time (seconds)',
|
||||
min: -1
|
||||
},
|
||||
{
|
||||
key: 'mandatoryPitstopCount' as keyof EventRules,
|
||||
label: 'Mandatory Pitstop Count',
|
||||
min: -1,
|
||||
max: 5
|
||||
},
|
||||
{
|
||||
key: 'maxTotalDrivingTime' as keyof EventRules,
|
||||
label: 'Max Total Driving Time (seconds)',
|
||||
min: -1
|
||||
},
|
||||
{
|
||||
key: 'tyreSetCount' as keyof EventRules,
|
||||
label: 'Tyre Set Count',
|
||||
min: 0,
|
||||
max: 50
|
||||
}
|
||||
];
|
||||
|
||||
const booleanFields = [
|
||||
{
|
||||
key: 'isRefuellingAllowedInRace' as keyof EventRules,
|
||||
label: 'Refuelling Allowed in Race'
|
||||
},
|
||||
{
|
||||
key: 'isRefuellingTimeFixed' as keyof EventRules,
|
||||
label: 'Refuelling Time Fixed'
|
||||
},
|
||||
{
|
||||
key: 'isMandatoryPitstopRefuellingRequired' as keyof EventRules,
|
||||
label: 'Mandatory Pitstop Refuelling Required'
|
||||
},
|
||||
{
|
||||
key: 'isMandatoryPitstopTyreChangeRequired' as keyof EventRules,
|
||||
label: 'Mandatory Pitstop Tyre Change Required'
|
||||
},
|
||||
{
|
||||
key: 'isMandatoryPitstopSwapDriverRequired' as keyof EventRules,
|
||||
label: 'Mandatory Pitstop Swap Driver Required'
|
||||
}
|
||||
];
|
||||
|
||||
export function EventRulesEditor({ serverId, config }: EventRulesEditorProps) {
|
||||
const [formData, setFormData] = useState<EventRules>(config);
|
||||
const [restart, setRestart] = useState(true);
|
||||
@@ -43,65 +102,6 @@ export function EventRulesEditor({ serverId, config }: EventRulesEditorProps) {
|
||||
}));
|
||||
};
|
||||
|
||||
const numberFields = [
|
||||
{
|
||||
key: 'qualifyStandingType' as keyof EventRules,
|
||||
label: 'Qualify Standing Type',
|
||||
min: -1,
|
||||
max: 1
|
||||
},
|
||||
{
|
||||
key: 'pitWindowLengthSec' as keyof EventRules,
|
||||
label: 'Pit Window Length (seconds)',
|
||||
min: -1
|
||||
},
|
||||
{
|
||||
key: 'driverStintTimeSec' as keyof EventRules,
|
||||
label: 'Driver Stint Time (seconds)',
|
||||
min: -1
|
||||
},
|
||||
{
|
||||
key: 'mandatoryPitstopCount' as keyof EventRules,
|
||||
label: 'Mandatory Pitstop Count',
|
||||
min: -1,
|
||||
max: 5
|
||||
},
|
||||
{
|
||||
key: 'maxTotalDrivingTime' as keyof EventRules,
|
||||
label: 'Max Total Driving Time (seconds)',
|
||||
min: -1
|
||||
},
|
||||
{
|
||||
key: 'tyreSetCount' as keyof EventRules,
|
||||
label: 'Tyre Set Count',
|
||||
min: 0,
|
||||
max: 50
|
||||
}
|
||||
];
|
||||
|
||||
const booleanFields = [
|
||||
{
|
||||
key: 'isRefuellingAllowedInRace' as keyof EventRules,
|
||||
label: 'Refuelling Allowed in Race'
|
||||
},
|
||||
{
|
||||
key: 'isRefuellingTimeFixed' as keyof EventRules,
|
||||
label: 'Refuelling Time Fixed'
|
||||
},
|
||||
{
|
||||
key: 'isMandatoryPitstopRefuellingRequired' as keyof EventRules,
|
||||
label: 'Mandatory Pitstop Refuelling Required'
|
||||
},
|
||||
{
|
||||
key: 'isMandatoryPitstopTyreChangeRequired' as keyof EventRules,
|
||||
label: 'Mandatory Pitstop Tyre Change Required'
|
||||
},
|
||||
{
|
||||
key: 'isMandatoryPitstopSwapDriverRequired' as keyof EventRules,
|
||||
label: 'Mandatory Pitstop Swap Driver Required'
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-4xl space-y-8">
|
||||
<div className="space-y-6">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { ServerSettings } from '@/lib/types/config';
|
||||
import type { ServerSettings } from '@/lib/schemas/config';
|
||||
import { updateServerSettingsAction } from '@/lib/actions/configuration';
|
||||
|
||||
interface ServerSettingsEditorProps {
|
||||
@@ -9,6 +9,84 @@ interface ServerSettingsEditorProps {
|
||||
config: ServerSettings;
|
||||
}
|
||||
|
||||
const textFields = [
|
||||
{
|
||||
key: 'serverName' as keyof ServerSettings,
|
||||
label: 'Server Name',
|
||||
type: 'text'
|
||||
},
|
||||
{
|
||||
key: 'adminPassword' as keyof ServerSettings,
|
||||
label: 'Admin Password',
|
||||
type: 'password'
|
||||
},
|
||||
{
|
||||
key: 'password' as keyof ServerSettings,
|
||||
label: 'Password',
|
||||
type: 'password'
|
||||
},
|
||||
{
|
||||
key: 'spectatorPassword' as keyof ServerSettings,
|
||||
label: 'Spectator Password',
|
||||
type: 'password'
|
||||
},
|
||||
{
|
||||
key: 'centralEntryListPath' as keyof ServerSettings,
|
||||
label: 'Central Entry List Path',
|
||||
type: 'text'
|
||||
}
|
||||
];
|
||||
|
||||
const carGroups = ['FreeForAll', 'GT3', 'GT4', 'GT2', 'GTC', 'TCX'];
|
||||
|
||||
const numberFields = [
|
||||
{
|
||||
key: 'trackMedalsRequirement' as keyof ServerSettings,
|
||||
label: 'Track Medals Requirement',
|
||||
min: -1,
|
||||
max: 3
|
||||
},
|
||||
{
|
||||
key: 'safetyRatingRequirement' as keyof ServerSettings,
|
||||
label: 'Safety Rating Requirement',
|
||||
min: -1,
|
||||
max: 99
|
||||
},
|
||||
{
|
||||
key: 'racecraftRatingRequirement' as keyof ServerSettings,
|
||||
label: 'Racecraft Rating Requirement',
|
||||
min: -1,
|
||||
max: 99
|
||||
},
|
||||
{
|
||||
key: 'maxCarSlots' as keyof ServerSettings,
|
||||
label: 'Max Car Slots',
|
||||
min: 1,
|
||||
max: 30
|
||||
}
|
||||
];
|
||||
|
||||
const selectFields = [
|
||||
{
|
||||
key: 'dumpLeaderboards' as keyof ServerSettings,
|
||||
label: 'Dump Leaderboards'
|
||||
},
|
||||
{ key: 'isRaceLocked' as keyof ServerSettings, label: 'Race Locked' },
|
||||
{
|
||||
key: 'randomizeTrackWhenEmpty' as keyof ServerSettings,
|
||||
label: 'Randomize Track When Empty'
|
||||
},
|
||||
{ key: 'allowAutoDQ' as keyof ServerSettings, label: 'Allow Auto DQ' },
|
||||
{
|
||||
key: 'shortFormationLap' as keyof ServerSettings,
|
||||
label: 'Short Formation Lap'
|
||||
},
|
||||
{
|
||||
key: 'ignorePrematureDisconnects' as keyof ServerSettings,
|
||||
label: 'Ignore Premature Disconnects'
|
||||
}
|
||||
];
|
||||
|
||||
export function ServerSettingsEditor({ serverId, config }: ServerSettingsEditorProps) {
|
||||
const [formData, setFormData] = useState<ServerSettings>(config);
|
||||
const [restart, setRestart] = useState(true);
|
||||
@@ -43,84 +121,6 @@ export function ServerSettingsEditor({ serverId, config }: ServerSettingsEditorP
|
||||
}));
|
||||
};
|
||||
|
||||
const textFields = [
|
||||
{
|
||||
key: 'serverName' as keyof ServerSettings,
|
||||
label: 'Server Name',
|
||||
type: 'text'
|
||||
},
|
||||
{
|
||||
key: 'adminPassword' as keyof ServerSettings,
|
||||
label: 'Admin Password',
|
||||
type: 'password'
|
||||
},
|
||||
{
|
||||
key: 'password' as keyof ServerSettings,
|
||||
label: 'Password',
|
||||
type: 'password'
|
||||
},
|
||||
{
|
||||
key: 'spectatorPassword' as keyof ServerSettings,
|
||||
label: 'Spectator Password',
|
||||
type: 'password'
|
||||
},
|
||||
{
|
||||
key: 'centralEntryListPath' as keyof ServerSettings,
|
||||
label: 'Central Entry List Path',
|
||||
type: 'text'
|
||||
}
|
||||
];
|
||||
|
||||
const carGroups = ['FreeForAll', 'GT3', 'GT4', 'GT2', 'GTC', 'TCX'];
|
||||
|
||||
const numberFields = [
|
||||
{
|
||||
key: 'trackMedalsRequirement' as keyof ServerSettings,
|
||||
label: 'Track Medals Requirement',
|
||||
min: -1,
|
||||
max: 3
|
||||
},
|
||||
{
|
||||
key: 'safetyRatingRequirement' as keyof ServerSettings,
|
||||
label: 'Safety Rating Requirement',
|
||||
min: -1,
|
||||
max: 99
|
||||
},
|
||||
{
|
||||
key: 'racecraftRatingRequirement' as keyof ServerSettings,
|
||||
label: 'Racecraft Rating Requirement',
|
||||
min: -1,
|
||||
max: 99
|
||||
},
|
||||
{
|
||||
key: 'maxCarSlots' as keyof ServerSettings,
|
||||
label: 'Max Car Slots',
|
||||
min: 1,
|
||||
max: 30
|
||||
}
|
||||
];
|
||||
|
||||
const selectFields = [
|
||||
{
|
||||
key: 'dumpLeaderboards' as keyof ServerSettings,
|
||||
label: 'Dump Leaderboards'
|
||||
},
|
||||
{ key: 'isRaceLocked' as keyof ServerSettings, label: 'Race Locked' },
|
||||
{
|
||||
key: 'randomizeTrackWhenEmpty' as keyof ServerSettings,
|
||||
label: 'Randomize Track When Empty'
|
||||
},
|
||||
{ key: 'allowAutoDQ' as keyof ServerSettings, label: 'Allow Auto DQ' },
|
||||
{
|
||||
key: 'shortFormationLap' as keyof ServerSettings,
|
||||
label: 'Short Formation Lap'
|
||||
},
|
||||
{
|
||||
key: 'ignorePrematureDisconnects' as keyof ServerSettings,
|
||||
label: 'Ignore Premature Disconnects'
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="max-w-4xl space-y-8">
|
||||
<div className="space-y-6">
|
||||
|
||||
162
src/components/leaderboard/LeaderboardManager.tsx
Normal file
162
src/components/leaderboard/LeaderboardManager.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Leaderboard, LeaderboardDriver } from '@/lib/schemas/leaderboard';
|
||||
import { saveLeaderboardAction } from '@/lib/actions/leaderboard';
|
||||
import { LeaderboardStandings } from './LeaderboardStandings';
|
||||
import { DriversEditor } from './editors/DriversEditor';
|
||||
import { PointsTableEditor } from './editors/PointsTableEditor';
|
||||
import { FlPointsEditor } from './editors/FlPointsEditor';
|
||||
import { TracksEditor } from './editors/TracksEditor';
|
||||
|
||||
type Section = 'standings' | 'drivers' | 'points' | 'fl' | 'tracks';
|
||||
|
||||
const sections: { id: Section; label: string }[] = [
|
||||
{ id: 'standings', label: 'Standings' },
|
||||
{ id: 'drivers', label: 'Drivers' },
|
||||
{ id: 'points', label: 'Points Table' },
|
||||
{ id: 'fl', label: 'FL Points' },
|
||||
{ id: 'tracks', label: 'Tracks' }
|
||||
];
|
||||
|
||||
interface LeaderboardManagerProps {
|
||||
serverId: string;
|
||||
initialData: Leaderboard;
|
||||
}
|
||||
|
||||
function isDirty(a: Leaderboard, b: Leaderboard) {
|
||||
return JSON.stringify(a) !== JSON.stringify(b);
|
||||
}
|
||||
|
||||
export function LeaderboardManager({ serverId, initialData }: LeaderboardManagerProps) {
|
||||
const [draft, setDraft] = useState<Leaderboard>(initialData);
|
||||
const [saved, setSaved] = useState<Leaderboard>(initialData);
|
||||
const [activeSection, setActiveSection] = useState<Section>('standings');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const dirty = isDirty(draft, saved);
|
||||
|
||||
const handleDriversChange = (newDrivers: LeaderboardDriver[]) => {
|
||||
const oldDrivers = draft.drivers;
|
||||
|
||||
// Build index map: for each position in newDrivers, what was the old index?
|
||||
const indexMap = newDrivers.map((d) => oldDrivers.indexOf(d));
|
||||
|
||||
// If a driver was added (indexOf returns -1), it's new
|
||||
const newTracks = draft.tracks.map((t) => ({
|
||||
...t,
|
||||
results: indexMap.map((i) => (i === -1 ? 0 : (t.results[i] ?? 0)))
|
||||
}));
|
||||
|
||||
setDraft({ ...draft, drivers: newDrivers, tracks: newTracks });
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setIsSubmitting(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await saveLeaderboardAction(serverId, draft);
|
||||
if (result.success) {
|
||||
setSaved(draft);
|
||||
} else {
|
||||
setError(result.message ?? 'Unknown error');
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to save');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const renderSection = () => {
|
||||
switch (activeSection) {
|
||||
case 'standings':
|
||||
return <LeaderboardStandings leaderboard={draft} />;
|
||||
case 'drivers':
|
||||
return <DriversEditor drivers={draft.drivers} onChange={handleDriversChange} />;
|
||||
case 'points':
|
||||
return (
|
||||
<PointsTableEditor
|
||||
pointsTable={draft.pointsTable}
|
||||
onChange={(pointsTable) => setDraft({ ...draft, pointsTable })}
|
||||
/>
|
||||
);
|
||||
case 'fl':
|
||||
return (
|
||||
<FlPointsEditor
|
||||
flPoints={draft.flPoints}
|
||||
onChange={(flPoints) => setDraft({ ...draft, flPoints })}
|
||||
/>
|
||||
);
|
||||
case 'tracks':
|
||||
return (
|
||||
<TracksEditor
|
||||
tracks={draft.tracks}
|
||||
drivers={draft.drivers}
|
||||
pointsTable={draft.pointsTable}
|
||||
onChange={(tracks) => setDraft({ ...draft, tracks })}
|
||||
/>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{dirty && (
|
||||
<div className="flex items-center justify-between rounded-lg bg-yellow-900/40 px-4 py-2 text-sm text-yellow-300">
|
||||
<span>Unsaved changes</span>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setDraft(saved)}
|
||||
className="rounded px-2 py-1 text-xs text-yellow-400 hover:text-yellow-200"
|
||||
>
|
||||
Discard
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={isSubmitting}
|
||||
className="rounded bg-yellow-600 px-3 py-1 text-xs font-semibold text-white hover:bg-yellow-500 disabled:opacity-50"
|
||||
>
|
||||
{isSubmitting ? 'Saving…' : 'Save'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg bg-red-900/40 px-4 py-2 text-sm text-red-300">{error}</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{sections.map((s) => (
|
||||
<button
|
||||
key={s.id}
|
||||
onClick={() => setActiveSection(s.id)}
|
||||
className={`rounded-lg px-3 py-1.5 text-sm font-medium transition-colors ${
|
||||
activeSection === s.id
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-700 text-gray-300 hover:bg-gray-600'
|
||||
}`}
|
||||
>
|
||||
{s.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div>{renderSection()}</div>
|
||||
|
||||
{!dirty && (
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={isSubmitting}
|
||||
className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-500 disabled:opacity-50"
|
||||
>
|
||||
{isSubmitting ? 'Saving…' : 'Save Leaderboard'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
112
src/components/leaderboard/LeaderboardStandings.tsx
Normal file
112
src/components/leaderboard/LeaderboardStandings.tsx
Normal file
@@ -0,0 +1,112 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { Leaderboard, StandingsRow } from '@/lib/schemas/leaderboard';
|
||||
|
||||
interface LeaderboardStandingsProps {
|
||||
leaderboard: Leaderboard;
|
||||
}
|
||||
|
||||
export function LeaderboardStandings({ leaderboard }: LeaderboardStandingsProps) {
|
||||
const standings = useMemo<StandingsRow[]>(() => {
|
||||
return leaderboard.drivers
|
||||
.map((driver, idx) => {
|
||||
const trackResults = leaderboard.tracks.map((t) => t.results[idx] ?? 0);
|
||||
const fastestLapCount = leaderboard.tracks.filter(
|
||||
(t) => t.fastestLapInitials === driver.initials
|
||||
).length;
|
||||
const totalPoints =
|
||||
trackResults.reduce((sum, r) => sum + (typeof r === 'number' ? r : 0), 0) +
|
||||
fastestLapCount * leaderboard.flPoints.points;
|
||||
return { driver, driverIndex: idx, totalPoints, trackResults, fastestLapCount };
|
||||
})
|
||||
.sort((a, b) => b.totalPoints - a.totalPoints);
|
||||
}, [leaderboard]);
|
||||
|
||||
if (leaderboard.drivers.length === 0) {
|
||||
return (
|
||||
<div className="py-12 text-center">
|
||||
<div className="mb-2 text-4xl">🏆</div>
|
||||
<p className="text-gray-400">No drivers yet. Add drivers to see standings.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-max text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-gray-700">
|
||||
<th className="py-2 pr-4 text-left text-xs font-semibold text-gray-400">Pos</th>
|
||||
<th className="py-2 pr-4 text-left text-xs font-semibold text-gray-400">Driver</th>
|
||||
{leaderboard.tracks.map((track, i) => (
|
||||
<th
|
||||
key={i}
|
||||
className="px-2 py-2 text-center text-xs font-semibold text-gray-400"
|
||||
title={track.name}
|
||||
>
|
||||
{track.name}
|
||||
</th>
|
||||
))}
|
||||
<th className="px-2 py-2 text-center text-xs font-semibold text-gray-400">FL</th>
|
||||
<th className="px-2 py-2 text-center text-xs font-semibold text-yellow-400">Pts</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{standings.map((row, pos) => (
|
||||
<tr key={row.driverIndex} className="border-b border-gray-700/50">
|
||||
<td className="py-2 pr-4 text-gray-400">{pos + 1}</td>
|
||||
<td className="py-2 pr-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className="h-3 w-3 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: row.driver.color }}
|
||||
/>
|
||||
<span className="font-medium text-white">{row.driver.name}</span>
|
||||
<span className="text-xs text-gray-500">{row.driver.initials}</span>
|
||||
</div>
|
||||
</td>
|
||||
{row.trackResults.map((result, ti) => {
|
||||
const track = leaderboard.tracks[ti];
|
||||
const isFl = track.fastestLapInitials === row.driver.initials;
|
||||
return (
|
||||
<td key={ti} className="px-2 py-2 text-center">
|
||||
<span
|
||||
className={`inline-block rounded px-1.5 py-0.5 text-xs font-semibold ${
|
||||
typeof result === 'number'
|
||||
? 'text-white'
|
||||
: result === 'DNF'
|
||||
? 'text-orange-400'
|
||||
: 'text-gray-500'
|
||||
}`}
|
||||
>
|
||||
{result}
|
||||
{isFl && (
|
||||
<span
|
||||
className="ml-0.5 rounded px-0.5 text-xs"
|
||||
style={{
|
||||
backgroundColor: leaderboard.flPoints.color,
|
||||
color: leaderboard.flPoints.textColor
|
||||
}}
|
||||
title={`Fastest lap: ${leaderboard.flPoints.label}`}
|
||||
>
|
||||
FL
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
<td className="px-2 py-2 text-center text-xs text-purple-400">
|
||||
{row.fastestLapCount > 0 ? `×${row.fastestLapCount}` : '—'}
|
||||
</td>
|
||||
<td className="px-2 py-2 text-center font-bold text-yellow-400">
|
||||
{row.totalPoints}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
126
src/components/leaderboard/editors/DriversEditor.tsx
Normal file
126
src/components/leaderboard/editors/DriversEditor.tsx
Normal file
@@ -0,0 +1,126 @@
|
||||
'use client';
|
||||
|
||||
import { LeaderboardDriver } from '@/lib/schemas/leaderboard';
|
||||
|
||||
function randomColor(): string {
|
||||
return '#' + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0');
|
||||
}
|
||||
|
||||
interface DriversEditorProps {
|
||||
drivers: LeaderboardDriver[];
|
||||
onChange: (drivers: LeaderboardDriver[]) => void;
|
||||
}
|
||||
|
||||
export function DriversEditor({ drivers, onChange }: DriversEditorProps) {
|
||||
const update = (index: number, patch: Partial<LeaderboardDriver>) => {
|
||||
const next = drivers.map((d, i) => (i === index ? { ...d, ...patch } : d));
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
const moveUp = (index: number) => {
|
||||
if (index === 0) return;
|
||||
const next = [...drivers];
|
||||
[next[index - 1], next[index]] = [next[index], next[index - 1]];
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
const moveDown = (index: number) => {
|
||||
if (index === drivers.length - 1) return;
|
||||
const next = [...drivers];
|
||||
[next[index], next[index + 1]] = [next[index + 1], next[index]];
|
||||
onChange(next);
|
||||
};
|
||||
|
||||
const remove = (index: number) => {
|
||||
onChange(drivers.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const add = () => {
|
||||
onChange([...drivers, { name: 'New Driver', initials: 'ND', color: randomColor() }]);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{drivers.map((driver, i) => (
|
||||
<div key={i} className="flex items-center gap-3 rounded-lg bg-gray-700 p-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<button
|
||||
onClick={() => moveUp(i)}
|
||||
disabled={i === 0}
|
||||
className="rounded px-1 py-0.5 text-xs text-gray-400 hover:text-white disabled:opacity-30"
|
||||
title="Move up"
|
||||
>
|
||||
▲
|
||||
</button>
|
||||
<button
|
||||
onClick={() => moveDown(i)}
|
||||
disabled={i === drivers.length - 1}
|
||||
className="rounded px-1 py-0.5 text-xs text-gray-400 hover:text-white disabled:opacity-30"
|
||||
title="Move down"
|
||||
>
|
||||
▼
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-1 flex-wrap gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Name</label>
|
||||
<input
|
||||
type="text"
|
||||
value={driver.name}
|
||||
onChange={(e) => update(i, { name: e.target.value })}
|
||||
className="rounded bg-gray-600 px-2 py-1 text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Initials</label>
|
||||
<input
|
||||
type="text"
|
||||
value={driver.initials}
|
||||
maxLength={10}
|
||||
onChange={(e) => update(i, { initials: e.target.value })}
|
||||
className="w-24 rounded bg-gray-600 px-2 py-1 text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Color</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={driver.color}
|
||||
onChange={(e) => update(i, { color: e.target.value })}
|
||||
className="h-8 w-8 cursor-pointer rounded border-0 bg-transparent"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={driver.color}
|
||||
onChange={(e) => {
|
||||
if (/^#[0-9a-fA-F]{6}$/.test(e.target.value)) {
|
||||
update(i, { color: e.target.value });
|
||||
}
|
||||
}}
|
||||
className="w-24 rounded bg-gray-600 px-2 py-1 font-mono text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => remove(i)}
|
||||
className="rounded px-2 py-1 text-sm text-red-400 hover:bg-red-900/30 hover:text-red-300"
|
||||
title="Remove driver"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<button
|
||||
onClick={add}
|
||||
className="w-full rounded-lg border border-dashed border-gray-600 py-2 text-sm text-gray-400 hover:border-gray-400 hover:text-gray-300"
|
||||
>
|
||||
+ Add Driver
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
98
src/components/leaderboard/editors/FlPointsEditor.tsx
Normal file
98
src/components/leaderboard/editors/FlPointsEditor.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
'use client';
|
||||
|
||||
import { FlPoints } from '@/lib/schemas/leaderboard';
|
||||
|
||||
interface FlPointsEditorProps {
|
||||
flPoints: FlPoints;
|
||||
onChange: (flPoints: FlPoints) => void;
|
||||
}
|
||||
|
||||
export function FlPointsEditor({ flPoints, onChange }: FlPointsEditorProps) {
|
||||
const update = (patch: Partial<FlPoints>) => onChange({ ...flPoints, ...patch });
|
||||
|
||||
return (
|
||||
<div className="rounded-lg bg-gray-700 p-4">
|
||||
<p className="mb-4 text-sm text-gray-400">
|
||||
Points awarded to the driver who sets the fastest lap in each race.
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Label</label>
|
||||
<input
|
||||
type="text"
|
||||
value={flPoints.label}
|
||||
onChange={(e) => update({ label: e.target.value })}
|
||||
className="w-24 rounded bg-gray-600 px-2 py-1 text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Points</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={flPoints.points}
|
||||
onChange={(e) => update({ points: parseInt(e.target.value) || 0 })}
|
||||
className="w-20 rounded bg-gray-600 px-2 py-1 text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Priority</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={flPoints.priority}
|
||||
onChange={(e) => update({ priority: parseInt(e.target.value) || 0 })}
|
||||
className="w-20 rounded bg-gray-600 px-2 py-1 text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Bg Color</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={flPoints.color}
|
||||
onChange={(e) => update({ color: e.target.value })}
|
||||
className="h-8 w-8 cursor-pointer rounded border-0 bg-transparent"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={flPoints.color}
|
||||
onChange={(e) => {
|
||||
if (/^#[0-9a-fA-F]{6}$/.test(e.target.value)) update({ color: e.target.value });
|
||||
}}
|
||||
className="w-24 rounded bg-gray-600 px-2 py-1 font-mono text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Text Color</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={flPoints.textColor}
|
||||
onChange={(e) => update({ textColor: e.target.value })}
|
||||
className="h-8 w-8 cursor-pointer rounded border-0 bg-transparent"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={flPoints.textColor}
|
||||
onChange={(e) => {
|
||||
if (/^#[0-9a-fA-F]{6}$/.test(e.target.value)) update({ textColor: e.target.value });
|
||||
}}
|
||||
className="w-24 rounded bg-gray-600 px-2 py-1 font-mono text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Preview</label>
|
||||
<span
|
||||
className="rounded px-2 py-1 text-sm font-semibold"
|
||||
style={{ backgroundColor: flPoints.color, color: flPoints.textColor }}
|
||||
>
|
||||
{flPoints.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
129
src/components/leaderboard/editors/PointsTableEditor.tsx
Normal file
129
src/components/leaderboard/editors/PointsTableEditor.tsx
Normal file
@@ -0,0 +1,129 @@
|
||||
'use client';
|
||||
|
||||
import { PointsEntry } from '@/lib/schemas/leaderboard';
|
||||
|
||||
interface PointsTableEditorProps {
|
||||
pointsTable: PointsEntry[];
|
||||
onChange: (pointsTable: PointsEntry[]) => void;
|
||||
}
|
||||
|
||||
export function PointsTableEditor({ pointsTable, onChange }: PointsTableEditorProps) {
|
||||
const update = (index: number, patch: Partial<PointsEntry>) => {
|
||||
onChange(pointsTable.map((e, i) => (i === index ? { ...e, ...patch } : e)));
|
||||
};
|
||||
|
||||
const remove = (index: number) => {
|
||||
onChange(pointsTable.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const add = () => {
|
||||
const pos = pointsTable.length + 1;
|
||||
onChange([
|
||||
...pointsTable,
|
||||
{ points: 0, label: `P${pos}`, color: '#374151', textColor: '#ffffff', priority: pos }
|
||||
]);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{pointsTable.map((entry, i) => (
|
||||
<div key={i} className="flex items-center gap-3 rounded-lg bg-gray-700 p-3">
|
||||
<div className="flex flex-1 flex-wrap gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Label</label>
|
||||
<input
|
||||
type="text"
|
||||
value={entry.label}
|
||||
onChange={(e) => update(i, { label: e.target.value })}
|
||||
className="w-20 rounded bg-gray-600 px-2 py-1 text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Points</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={entry.points}
|
||||
onChange={(e) => update(i, { points: parseInt(e.target.value) || 0 })}
|
||||
className="w-20 rounded bg-gray-600 px-2 py-1 text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Priority</label>
|
||||
<input
|
||||
type="number"
|
||||
min={0}
|
||||
value={entry.priority}
|
||||
onChange={(e) => update(i, { priority: parseInt(e.target.value) || 0 })}
|
||||
className="w-20 rounded bg-gray-600 px-2 py-1 text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Bg Color</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={entry.color}
|
||||
onChange={(e) => update(i, { color: e.target.value })}
|
||||
className="h-8 w-8 cursor-pointer rounded border-0 bg-transparent"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={entry.color}
|
||||
onChange={(e) => {
|
||||
if (/^#[0-9a-fA-F]{6}$/.test(e.target.value)) update(i, { color: e.target.value });
|
||||
}}
|
||||
className="w-24 rounded bg-gray-600 px-2 py-1 font-mono text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Text Color</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={entry.textColor}
|
||||
onChange={(e) => update(i, { textColor: e.target.value })}
|
||||
className="h-8 w-8 cursor-pointer rounded border-0 bg-transparent"
|
||||
/>
|
||||
<input
|
||||
type="text"
|
||||
value={entry.textColor}
|
||||
onChange={(e) => {
|
||||
if (/^#[0-9a-fA-F]{6}$/.test(e.target.value))
|
||||
update(i, { textColor: e.target.value });
|
||||
}}
|
||||
className="w-24 rounded bg-gray-600 px-2 py-1 font-mono text-sm text-white"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label className="text-xs text-gray-400">Preview</label>
|
||||
<span
|
||||
className="rounded px-2 py-1 text-sm font-semibold"
|
||||
style={{ backgroundColor: entry.color, color: entry.textColor }}
|
||||
>
|
||||
{entry.label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => remove(i)}
|
||||
className="rounded px-2 py-1 text-sm text-red-400 hover:bg-red-900/30 hover:text-red-300"
|
||||
title="Remove entry"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<button
|
||||
onClick={add}
|
||||
className="w-full rounded-lg border border-dashed border-gray-600 py-2 text-sm text-gray-400 hover:border-gray-400 hover:text-gray-300"
|
||||
>
|
||||
+ Add Position
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
141
src/components/leaderboard/editors/TracksEditor.tsx
Normal file
141
src/components/leaderboard/editors/TracksEditor.tsx
Normal file
@@ -0,0 +1,141 @@
|
||||
'use client';
|
||||
|
||||
import { LeaderboardDriver, LeaderboardTrack, PointsEntry, ResultValue } from '@/lib/schemas/leaderboard';
|
||||
|
||||
interface ResultInputProps {
|
||||
value: ResultValue;
|
||||
pointsTable: PointsEntry[];
|
||||
onChange: (value: ResultValue) => void;
|
||||
}
|
||||
|
||||
function ResultInput({ value, pointsTable, onChange }: ResultInputProps) {
|
||||
const knownPoints = Array.from(new Set(pointsTable.map((e) => e.points))).sort((a, b) => b - a);
|
||||
|
||||
const handleChange = (raw: string) => {
|
||||
if (raw === 'DNF') return onChange('DNF');
|
||||
if (raw === 'DNS') return onChange('DNS');
|
||||
onChange(parseInt(raw) || 0);
|
||||
};
|
||||
|
||||
return (
|
||||
<select
|
||||
value={String(value)}
|
||||
onChange={(e) => handleChange(e.target.value)}
|
||||
className="w-full rounded bg-gray-600 px-1 py-1 text-xs text-white"
|
||||
>
|
||||
{knownPoints.map((p) => (
|
||||
<option key={p} value={String(p)}>
|
||||
{p}
|
||||
</option>
|
||||
))}
|
||||
<option value="DNF">DNF</option>
|
||||
<option value="DNS">DNS</option>
|
||||
</select>
|
||||
);
|
||||
}
|
||||
|
||||
interface TracksEditorProps {
|
||||
tracks: LeaderboardTrack[];
|
||||
drivers: LeaderboardDriver[];
|
||||
pointsTable: PointsEntry[];
|
||||
onChange: (tracks: LeaderboardTrack[]) => void;
|
||||
}
|
||||
|
||||
export function TracksEditor({ tracks, drivers, pointsTable, onChange }: TracksEditorProps) {
|
||||
const updateTrack = (index: number, patch: Partial<LeaderboardTrack>) => {
|
||||
onChange(tracks.map((t, i) => (i === index ? { ...t, ...patch } : t)));
|
||||
};
|
||||
|
||||
const updateResult = (trackIndex: number, driverIndex: number, value: ResultValue) => {
|
||||
const newResults = [...tracks[trackIndex].results];
|
||||
newResults[driverIndex] = value;
|
||||
updateTrack(trackIndex, { results: newResults });
|
||||
};
|
||||
|
||||
const removeTrack = (index: number) => {
|
||||
onChange(tracks.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const addTrack = () => {
|
||||
onChange([
|
||||
...tracks,
|
||||
{
|
||||
name: `Race ${tracks.length + 1}`,
|
||||
results: drivers.map(() => 'DNS' as const),
|
||||
fastestLapInitials: ''
|
||||
}
|
||||
]);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{tracks.map((track, ti) => (
|
||||
<div key={ti} className="rounded-lg bg-gray-700 p-4">
|
||||
<div className="mb-3 flex items-center gap-3">
|
||||
<input
|
||||
type="text"
|
||||
value={track.name}
|
||||
onChange={(e) => updateTrack(ti, { name: e.target.value })}
|
||||
className="flex-1 rounded bg-gray-600 px-2 py-1 text-sm font-semibold text-white"
|
||||
placeholder="Track name"
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-xs text-gray-400">FL Driver:</label>
|
||||
<select
|
||||
value={track.fastestLapInitials}
|
||||
onChange={(e) => updateTrack(ti, { fastestLapInitials: e.target.value })}
|
||||
className="rounded bg-gray-600 px-2 py-1 text-sm text-white"
|
||||
>
|
||||
<option value="">—</option>
|
||||
{drivers.map((d) => (
|
||||
<option key={d.initials} value={d.initials}>
|
||||
{d.initials} ({d.name})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => removeTrack(ti)}
|
||||
className="rounded px-2 py-1 text-sm text-red-400 hover:bg-red-900/30 hover:text-red-300"
|
||||
title="Remove track"
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{drivers.length === 0 ? (
|
||||
<p className="text-xs text-gray-500">Add drivers first to enter results.</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
{drivers.map((driver, di) => (
|
||||
<div key={di} className="flex items-center gap-3">
|
||||
<div className="flex w-40 items-center gap-2">
|
||||
<div
|
||||
className="h-3 w-3 shrink-0 rounded-full"
|
||||
style={{ backgroundColor: driver.color }}
|
||||
/>
|
||||
<span className="truncate text-sm text-gray-300">{driver.name}</span>
|
||||
</div>
|
||||
<div className="w-24">
|
||||
<ResultInput
|
||||
value={track.results[di] ?? 0}
|
||||
pointsTable={pointsTable}
|
||||
onChange={(v) => updateResult(ti, di, v)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
<button
|
||||
onClick={addTrack}
|
||||
className="w-full rounded-lg border border-dashed border-gray-600 py-2 text-sm text-gray-400 hover:border-gray-400 hover:text-gray-300"
|
||||
>
|
||||
+ Add Track / Race
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
82
src/components/login/LoginForm.tsx
Normal file
82
src/components/login/LoginForm.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
'use client';
|
||||
|
||||
import { clearExpiredSessionAction, loginAction, LoginResult } from '@/lib/actions/auth';
|
||||
import { use, useActionState, useEffect } from 'react';
|
||||
|
||||
const initialState: LoginResult = {
|
||||
message: '',
|
||||
success: true
|
||||
};
|
||||
|
||||
export default function LoginForm({
|
||||
searchParams
|
||||
}: {
|
||||
searchParams: Promise<{ expired: boolean | undefined }>;
|
||||
}) {
|
||||
const params = use(searchParams);
|
||||
const expired = params.expired;
|
||||
|
||||
useEffect(() => {
|
||||
if (expired) {
|
||||
clearExpiredSessionAction();
|
||||
}
|
||||
}, [expired]);
|
||||
const [state, formAction] = useActionState(loginAction, initialState);
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-gray-900 px-4">
|
||||
<div className="w-full max-w-md space-y-8 rounded-lg bg-gray-800 p-8 shadow-lg">
|
||||
<div className="text-center">
|
||||
<h1 className="text-3xl font-bold text-white">ACC Server Manager</h1>
|
||||
<p className="mt-2 text-gray-400">Sign in to manage your servers</p>
|
||||
</div>
|
||||
{expired && (
|
||||
<div className="rounded-md border border-yellow-700 bg-yellow-900/50 p-3 text-sm text-yellow-200">
|
||||
Your session has expired. Please sign in again.
|
||||
</div>
|
||||
)}
|
||||
{state?.success ? null : (
|
||||
<div className="rounded-md border border-red-700 bg-red-900/50 p-3 text-sm text-red-200">
|
||||
{state?.message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form action={formAction} className="space-y-6">
|
||||
<div>
|
||||
<label htmlFor="username" className="mb-2 block text-sm font-medium text-gray-300">
|
||||
Username
|
||||
</label>
|
||||
<input
|
||||
id="username"
|
||||
name="username"
|
||||
type="text"
|
||||
autoComplete="username"
|
||||
required
|
||||
className="form-input w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="password" className="mb-2 block text-sm font-medium text-gray-300">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
className="form-input w-full"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full rounded-md bg-blue-600 px-4 py-3 font-medium text-white transition-colors hover:bg-blue-700 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 focus:ring-offset-gray-800 focus:outline-none"
|
||||
>
|
||||
Sign in
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { Role } from '@/lib/types';
|
||||
import type { Role } from '@/lib/schemas';
|
||||
import { createUserAction } from '@/lib/actions/membership';
|
||||
|
||||
interface CreateUserModalProps {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import type { User } from '@/lib/types';
|
||||
import type { User } from '@/lib/schemas';
|
||||
import { deleteUserAction } from '@/lib/actions/membership';
|
||||
|
||||
interface DeleteUserModalProps {
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
import { useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import type { Role, User } from '@/lib/types';
|
||||
import { hasPermission } from '@/lib/types/user';
|
||||
import type { Role, User } from '@/lib/schemas';
|
||||
import { hasPermission } from '@/lib/schemas/user';
|
||||
import { CreateUserModal } from './CreateUserModal';
|
||||
import { DeleteUserModal } from './DeleteUserModal';
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useState, useTransition } from 'react';
|
||||
import { Modal } from '@/components/ui/Modal';
|
||||
import { LoadingSpinner } from '@/components/ui/LoadingSpinner';
|
||||
import { deleteServerAction } from '@/lib/actions/server-management';
|
||||
import { Server } from '@/lib/types/server';
|
||||
import { Server } from '@/lib/schemas/server';
|
||||
|
||||
interface DeleteServerModalProps {
|
||||
isOpen: boolean;
|
||||
|
||||
@@ -1,26 +1,21 @@
|
||||
import Link from 'next/link';
|
||||
import { useState, useTransition } from 'react';
|
||||
import { Server, ServiceStatus, getStatusColor, serviceStatusToString } from '@/lib/types';
|
||||
import { User, hasPermission } from '@/lib/types/user';
|
||||
import { useTransition } from 'react';
|
||||
import { Server, ServiceStatus, getStatusColor, serviceStatusToString } from '@/lib/schemas';
|
||||
import {
|
||||
startServerEventAction,
|
||||
restartServerEventAction,
|
||||
stopServerEventAction
|
||||
} from '@/lib/actions/servers';
|
||||
import { DeleteServerModal } from './DeleteServerModal';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
interface ServerCardProps {
|
||||
server: Server;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export function ServerCard({ server, user }: ServerCardProps) {
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
export function ServerCard({ server }: ServerCardProps) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const router = useRouter();
|
||||
|
||||
const canDeleteServer = hasPermission(user, 'server.delete');
|
||||
const startServer = () =>
|
||||
startTransition(async () => {
|
||||
await startServerEventAction(server.id);
|
||||
@@ -62,29 +57,6 @@ export function ServerCard({ server, user }: ServerCardProps) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
{canDeleteServer && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDeleteModalOpen(true);
|
||||
}}
|
||||
className="text-gray-400 hover:text-red-400"
|
||||
title="Delete Server"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="h-5 w-5"
|
||||
viewBox="0 0 20 20"
|
||||
fill="currentColor"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M9 2a1 1 0 000 2h2a1 1 0 100-2H9zM4 5a2 2 0 012-2h8a2 2 0 012 2v6a2 2 0 01-2 2H6a2 2 0 01-2-2V5zm3 4a1 1 0 102 0v3a1 1 0 11-2 0V9zm4 0a1 1 0 10-2 0v3a1 1 0 002 0V9z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
<div className="text-gray-400 hover:text-white">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
@@ -140,12 +112,6 @@ export function ServerCard({ server, user }: ServerCardProps) {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DeleteServerModal
|
||||
isOpen={isDeleteModalOpen}
|
||||
onClose={() => setIsDeleteModalOpen(false)}
|
||||
server={server}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,35 +1,40 @@
|
||||
'use client';
|
||||
|
||||
import { Configurations, ServerTab } from '@/lib/types/config';
|
||||
import { Configurations, ServerTab } from '@/lib/schemas/config';
|
||||
import { ConfigurationEditor } from '@/components/configuration/ConfigurationEditor';
|
||||
import { AssistRulesEditor } from '@/components/configuration/AssistRulesEditor';
|
||||
import { EventConfigEditor } from '@/components/configuration/EventConfigEditor';
|
||||
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 { useState } from 'react';
|
||||
import { StateHistoryStats } from '@/lib/types';
|
||||
import { StateHistoryStats } from '@/lib/schemas';
|
||||
import { Leaderboard } from '@/lib/schemas/leaderboard';
|
||||
|
||||
interface ServerConfigurationTabsProps {
|
||||
serverId: string;
|
||||
configurations: Configurations;
|
||||
statistics: StateHistoryStats;
|
||||
leaderboard: Leaderboard;
|
||||
}
|
||||
const tabs = [
|
||||
{ id: ServerTab.statistics, name: 'Statistics', icon: '📊' },
|
||||
{ id: ServerTab.configuration, name: 'Configuration', icon: '⚙️' },
|
||||
{ id: ServerTab.assistRules, name: 'Assist Rules', icon: '🚗' },
|
||||
{ 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: '🏆' }
|
||||
];
|
||||
|
||||
export function ServerConfigurationTabs({
|
||||
serverId,
|
||||
configurations,
|
||||
statistics
|
||||
statistics,
|
||||
leaderboard
|
||||
}: ServerConfigurationTabsProps) {
|
||||
const [currentTab, setCurrentTab] = useState(ServerTab.statistics);
|
||||
const tabs = [
|
||||
{ id: ServerTab.statistics, name: 'Statistics', icon: '📊' },
|
||||
{ id: ServerTab.configuration, name: 'Configuration', icon: '⚙️' },
|
||||
{ id: ServerTab.assistRules, name: 'Assist Rules', icon: '🚗' },
|
||||
{ id: ServerTab.event, name: 'Event Config', icon: '🏁' },
|
||||
{ id: ServerTab.eventRules, name: 'Event Rules', icon: '📋' },
|
||||
{ id: ServerTab.settings, name: 'Server Settings', icon: '🔧' }
|
||||
];
|
||||
|
||||
const renderTabContent = () => {
|
||||
switch (currentTab) {
|
||||
@@ -51,6 +56,9 @@ export function ServerConfigurationTabs({
|
||||
case ServerTab.settings:
|
||||
return <ServerSettingsEditor serverId={serverId} config={configurations.settings} />;
|
||||
|
||||
case ServerTab.leaderboard:
|
||||
return <LeaderboardManager serverId={serverId} initialData={leaderboard} />;
|
||||
|
||||
default:
|
||||
return (
|
||||
<div className="py-12 text-center">
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useWebSocket } from '@/lib/websocket/context';
|
||||
import {
|
||||
import type {
|
||||
WebSocketMessage,
|
||||
StepData,
|
||||
SteamOutputData,
|
||||
ErrorData,
|
||||
CompleteData
|
||||
} from '@/lib/websocket/client';
|
||||
} from '@/lib/schemas/websocket';
|
||||
|
||||
interface ServerCreationPopupProps {
|
||||
serverId: string;
|
||||
|
||||
@@ -4,10 +4,12 @@ import { useServerCreationPopup } from '@/lib/context/ServerCreationPopupContext
|
||||
import { ServerCreationPopup } from './ServerCreationPopup';
|
||||
import { useSteamCMD } from '@/lib/context/SteamCMDContext';
|
||||
import { useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
|
||||
export function ServerCreationPopupContainer() {
|
||||
const { popup, hidePopup } = useServerCreationPopup();
|
||||
const { dissociateServer } = useSteamCMD();
|
||||
const router = useRouter();
|
||||
const handleClose = useCallback(() => {
|
||||
hidePopup();
|
||||
if (popup) return dissociateServer(popup.serverId);
|
||||
@@ -17,7 +19,7 @@ export function ServerCreationPopupContainer() {
|
||||
const handleComplete = (success: boolean) => {
|
||||
if (success) {
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
router.refresh();
|
||||
}, 2000);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,432 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { useWebSocket } from '@/lib/websocket/context';
|
||||
import {
|
||||
WebSocketMessage,
|
||||
StepData,
|
||||
SteamOutputData,
|
||||
ErrorData,
|
||||
CompleteData
|
||||
} from '@/lib/websocket/client';
|
||||
|
||||
interface ServerCreationProgressClientProps {
|
||||
serverId: string;
|
||||
}
|
||||
|
||||
interface ConsoleEntry {
|
||||
id: string;
|
||||
timestamp: number;
|
||||
type: 'step' | 'steam_output' | 'error' | 'complete';
|
||||
content: string;
|
||||
level: 'info' | 'success' | 'warning' | 'error';
|
||||
}
|
||||
|
||||
interface StepStatus {
|
||||
step: string;
|
||||
status: 'pending' | 'in_progress' | 'completed' | 'failed';
|
||||
message: string;
|
||||
}
|
||||
|
||||
const STEPS = [
|
||||
{ key: 'validation', label: 'Validation' },
|
||||
{ key: 'directory_creation', label: 'Directory Creation' },
|
||||
{ key: 'steam_download', label: 'Steam Download' },
|
||||
{ key: 'config_generation', label: 'Config Generation' },
|
||||
{ key: 'service_creation', label: 'Service Creation' },
|
||||
{ key: 'firewall_rules', label: 'Firewall Rules' },
|
||||
{ key: 'database_save', label: 'Database Save' },
|
||||
{ key: 'completed', label: 'Completed' }
|
||||
];
|
||||
|
||||
export function ServerCreationProgressClient({ serverId }: ServerCreationProgressClientProps) {
|
||||
const [entries, setEntries] = useState<ConsoleEntry[]>([]);
|
||||
const [steps, setSteps] = useState<Record<string, StepStatus>>({});
|
||||
const [isCompleted, setIsCompleted] = useState(false);
|
||||
const [completionResult, setCompletionResult] = useState<{
|
||||
success: boolean;
|
||||
message: string;
|
||||
} | null>(null);
|
||||
const [isMinimized, setIsMinimized] = useState(false);
|
||||
|
||||
const {
|
||||
associateWithServer,
|
||||
addMessageHandler,
|
||||
removeMessageHandler,
|
||||
connectionStatus,
|
||||
connectionError,
|
||||
reconnect
|
||||
} = useWebSocket();
|
||||
const router = useRouter();
|
||||
const consoleRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const addEntry = (entry: Omit<ConsoleEntry, 'id'>) => {
|
||||
const newEntry = {
|
||||
...entry,
|
||||
id: `${Date.now()}-${Math.random()}`
|
||||
};
|
||||
setEntries((prev) => [...prev, newEntry]);
|
||||
};
|
||||
|
||||
const scrollToBottom = () => {
|
||||
if (consoleRef.current && !isMinimized) {
|
||||
consoleRef.current.scrollTop = consoleRef.current.scrollHeight;
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
scrollToBottom();
|
||||
}, [entries, isMinimized]);
|
||||
|
||||
useEffect(() => {
|
||||
if (serverId) {
|
||||
associateWithServer(serverId);
|
||||
}
|
||||
}, [serverId, associateWithServer]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleMessage = (message: WebSocketMessage) => {
|
||||
if (message.server_id !== serverId) return;
|
||||
|
||||
const timestamp = message.timestamp;
|
||||
|
||||
switch (message.type) {
|
||||
case 'step': {
|
||||
const data = message.data as StepData;
|
||||
setSteps((prev) => ({
|
||||
...prev,
|
||||
[data.step]: {
|
||||
step: data.step,
|
||||
status: data.status,
|
||||
message: data.message
|
||||
}
|
||||
}));
|
||||
|
||||
let level: ConsoleEntry['level'] = 'info';
|
||||
if (data.status === 'completed') level = 'success';
|
||||
else if (data.status === 'failed') level = 'error';
|
||||
else if (data.status === 'in_progress') level = 'warning';
|
||||
|
||||
addEntry({
|
||||
timestamp,
|
||||
type: 'step',
|
||||
content: `[${data.step.toUpperCase()}] ${data.message}${data.error ? ` - ${data.error}` : ''}`,
|
||||
level
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'steam_output': {
|
||||
const data = message.data as SteamOutputData;
|
||||
addEntry({
|
||||
timestamp,
|
||||
type: 'steam_output',
|
||||
content: data.output,
|
||||
level: data.is_error ? 'error' : 'info'
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'error': {
|
||||
const data = message.data as ErrorData;
|
||||
addEntry({
|
||||
timestamp,
|
||||
type: 'error',
|
||||
content: `ERROR: ${data.error}${data.details ? ` - ${data.details}` : ''}`,
|
||||
level: 'error'
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'complete': {
|
||||
const data = message.data as CompleteData;
|
||||
setIsCompleted(true);
|
||||
setCompletionResult({ success: data.success, message: data.message });
|
||||
|
||||
addEntry({
|
||||
timestamp,
|
||||
type: 'complete',
|
||||
content: `COMPLETED: ${data.message}`,
|
||||
level: data.success ? 'success' : 'error'
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
addMessageHandler(handleMessage);
|
||||
return () => {
|
||||
removeMessageHandler(handleMessage);
|
||||
};
|
||||
}, [addMessageHandler, removeMessageHandler, serverId]);
|
||||
|
||||
const handleReturnToDashboard = () => {
|
||||
router.push('/dashboard');
|
||||
};
|
||||
|
||||
const handleReconnect = async () => {
|
||||
try {
|
||||
await reconnect();
|
||||
} catch (error) {
|
||||
console.error('Failed to reconnect:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const getStepStatusIcon = (status: StepStatus['status']) => {
|
||||
switch (status) {
|
||||
case 'pending':
|
||||
return '⏳';
|
||||
case 'in_progress':
|
||||
return '🔄';
|
||||
case 'completed':
|
||||
return '✅';
|
||||
case 'failed':
|
||||
return '❌';
|
||||
}
|
||||
};
|
||||
|
||||
const getEntryClassName = (level: ConsoleEntry['level']) => {
|
||||
switch (level) {
|
||||
case 'success':
|
||||
return 'text-green-400';
|
||||
case 'warning':
|
||||
return 'text-yellow-400';
|
||||
case 'error':
|
||||
return 'text-red-400';
|
||||
default:
|
||||
return 'text-gray-300';
|
||||
}
|
||||
};
|
||||
|
||||
const getConnectionStatusColor = () => {
|
||||
switch (connectionStatus) {
|
||||
case 'connected':
|
||||
return 'text-green-400';
|
||||
case 'connecting':
|
||||
return 'text-yellow-400';
|
||||
case 'disconnected':
|
||||
return 'text-gray-400';
|
||||
case 'error':
|
||||
return 'text-red-400';
|
||||
}
|
||||
};
|
||||
|
||||
const getConnectionStatusIcon = () => {
|
||||
switch (connectionStatus) {
|
||||
case 'connected':
|
||||
return '🟢';
|
||||
case 'connecting':
|
||||
return '🟡';
|
||||
case 'disconnected':
|
||||
return '⚫';
|
||||
case 'error':
|
||||
return '🔴';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-900 text-white">
|
||||
{/* Header */}
|
||||
<header className="bg-gray-800 shadow-md">
|
||||
<div className="mx-auto flex max-w-[120rem] items-center justify-between px-4 py-4 sm:px-6 lg:px-8">
|
||||
<div className="flex items-center space-x-4">
|
||||
<Link
|
||||
href="/dashboard"
|
||||
className="text-gray-400 hover:text-white"
|
||||
title="Back to Dashboard"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="h-6 w-6"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M10 19l-7-7m0 0l7-7m-7 7h18"
|
||||
/>
|
||||
</svg>
|
||||
</Link>
|
||||
<h1 className="text-xl font-bold">Server Creation Progress</h1>
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
{/* Connection Status */}
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-lg">{getConnectionStatusIcon()}</span>
|
||||
<span className={`text-sm ${getConnectionStatusColor()}`}>
|
||||
{connectionStatus === 'connected' && 'Connected'}
|
||||
{connectionStatus === 'connecting' && 'Connecting...'}
|
||||
{connectionStatus === 'disconnected' && 'Disconnected'}
|
||||
{connectionStatus === 'error' && 'Connection Error'}
|
||||
</span>
|
||||
{(connectionStatus === 'disconnected' || connectionStatus === 'error') && (
|
||||
<button
|
||||
onClick={handleReconnect}
|
||||
className="rounded bg-blue-600 px-2 py-1 text-xs hover:bg-blue-700"
|
||||
title="Reconnect to WebSocket"
|
||||
>
|
||||
Reconnect
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setIsMinimized(!isMinimized)}
|
||||
className="text-gray-400 hover:text-white"
|
||||
title={isMinimized ? 'Expand Console' : 'Minimize Console'}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="h-5 w-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
{isMinimized ? (
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M7 14l3-3 3 3"
|
||||
/>
|
||||
) : (
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M17 10l-3 3-3-3"
|
||||
/>
|
||||
)}
|
||||
</svg>
|
||||
</button>
|
||||
{isCompleted && (
|
||||
<button
|
||||
onClick={handleReturnToDashboard}
|
||||
className={`rounded-md px-4 py-2 text-sm font-medium ${
|
||||
completionResult?.success
|
||||
? 'bg-green-600 hover:bg-green-700'
|
||||
: 'bg-red-600 hover:bg-red-700'
|
||||
}`}
|
||||
>
|
||||
{completionResult?.success ? 'Return to Dashboard' : 'Back to Dashboard'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Connection Error Banner */}
|
||||
{(connectionStatus === 'disconnected' || connectionStatus === 'error') && (
|
||||
<div className="border-l-4 border-red-400 bg-red-600 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center">
|
||||
<div className="flex-shrink-0">
|
||||
<svg className="h-5 w-5 text-red-50" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div className="ml-3">
|
||||
<p className="text-sm text-red-50">
|
||||
<strong>WebSocket Connection Lost</strong> -
|
||||
{connectionError
|
||||
? ` ${connectionError}`
|
||||
: ' Unable to receive real-time updates.'}{' '}
|
||||
Progress may not be current.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleReconnect}
|
||||
className="rounded bg-red-700 px-3 py-1 text-sm text-red-50 hover:bg-red-800"
|
||||
>
|
||||
Reconnect
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<main className="mx-auto max-w-[120rem] px-4 py-6 sm:px-6 lg:px-8">
|
||||
<div className="space-y-6">
|
||||
{/* Steps Progress */}
|
||||
<div className="rounded-lg bg-gray-800 p-6">
|
||||
<h2 className="mb-4 text-lg font-medium text-gray-300">Progress Steps</h2>
|
||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-4">
|
||||
{STEPS.map(({ key, label }) => {
|
||||
const stepStatus = steps[key];
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
className={`flex items-center space-x-3 rounded-lg p-3 text-sm ${
|
||||
stepStatus?.status === 'completed'
|
||||
? 'bg-green-900/50 text-green-100'
|
||||
: stepStatus?.status === 'in_progress'
|
||||
? 'bg-yellow-900/50 text-yellow-100'
|
||||
: stepStatus?.status === 'failed'
|
||||
? 'bg-red-900/50 text-red-100'
|
||||
: 'bg-gray-700 text-gray-300'
|
||||
}`}
|
||||
>
|
||||
<span className="text-lg">
|
||||
{getStepStatusIcon(stepStatus?.status || 'pending')}
|
||||
</span>
|
||||
<span className="font-medium">{label}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Console Output */}
|
||||
{!isMinimized && (
|
||||
<div className="rounded-lg bg-gray-800">
|
||||
<div className="flex items-center justify-between border-b border-gray-700 p-4">
|
||||
<h2 className="text-lg font-medium text-gray-300">Console Output</h2>
|
||||
<div className="text-sm text-gray-400">{entries.length} log entries</div>
|
||||
</div>
|
||||
<div className="h-96 overflow-hidden rounded-b-lg bg-black p-4">
|
||||
<div
|
||||
ref={consoleRef}
|
||||
className="h-full space-y-1 overflow-y-auto font-mono text-sm"
|
||||
>
|
||||
{entries.map((entry) => (
|
||||
<div
|
||||
key={entry.id}
|
||||
className={`${getEntryClassName(entry.level)} leading-tight`}
|
||||
>
|
||||
<span className="text-xs text-gray-500">
|
||||
{new Date(entry.timestamp * 1000).toLocaleTimeString()}
|
||||
</span>{' '}
|
||||
<span>{entry.content}</span>
|
||||
</div>
|
||||
))}
|
||||
{entries.length === 0 && (
|
||||
<div className="py-8 text-center text-gray-500">
|
||||
Waiting for server creation to begin...
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isMinimized && (
|
||||
<div className="rounded-lg bg-gray-800 p-4">
|
||||
<div className="text-center text-gray-400">
|
||||
Console minimized - click the expand button in the header to view output
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,48 @@
|
||||
'use client';
|
||||
import Link from 'next/link';
|
||||
import { Server, getStatusColor, serviceStatusToString, ServiceStatus } from '@/lib/types/server';
|
||||
import { Server, getStatusColor, serviceStatusToString, ServiceStatus } from '@/lib/schemas/server';
|
||||
import {
|
||||
startServerEventAction,
|
||||
restartServerEventAction,
|
||||
stopServerEventAction
|
||||
} from '@/lib/actions/servers';
|
||||
import { hasPermission, User } from '@/lib/schemas';
|
||||
import { useState, useTransition } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { DeleteServerModal } from './DeleteServerModal';
|
||||
|
||||
interface ServerHeaderProps {
|
||||
server: Server;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export function ServerHeader({ server }: ServerHeaderProps) {
|
||||
export function ServerHeader({ server, user }: ServerHeaderProps) {
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const router = useRouter();
|
||||
const canDeleteServer = hasPermission(user, 'server.delete');
|
||||
const startServer = () =>
|
||||
startTransition(async () => {
|
||||
await startServerEventAction(server.id);
|
||||
router.refresh();
|
||||
});
|
||||
const restartServer = () =>
|
||||
startTransition(async () => {
|
||||
await restartServerEventAction(server.id);
|
||||
router.refresh();
|
||||
});
|
||||
const stopServer = () =>
|
||||
startTransition(async () => {
|
||||
await stopServerEventAction(server.id);
|
||||
router.refresh();
|
||||
});
|
||||
|
||||
const disabled = [
|
||||
ServiceStatus.Restarting,
|
||||
ServiceStatus.Starting,
|
||||
ServiceStatus.Stopping,
|
||||
ServiceStatus.Unknown
|
||||
].includes(server.status);
|
||||
return (
|
||||
<div className="rounded-lg bg-gray-800 p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
@@ -53,35 +85,45 @@ export function ServerHeader({ server }: ServerHeaderProps) {
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-3">
|
||||
<form action={startServerEventAction.bind(null, server.id)}>
|
||||
{canDeleteServer && (
|
||||
<button
|
||||
type="submit"
|
||||
disabled={server.status === ServiceStatus.Running}
|
||||
className="rounded bg-green-600 px-4 py-2 font-medium text-white transition-colors hover:bg-green-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
setIsDeleteModalOpen(true);
|
||||
}}
|
||||
disabled={disabled || isPending}
|
||||
className="mr-3 rounded bg-red-800 px-4 py-2 font-medium text-white transition-colors hover:bg-red-900 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
Start
|
||||
Remove Server
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={startServer}
|
||||
disabled={server.status === ServiceStatus.Running || disabled || isPending}
|
||||
className="rounded bg-green-600 px-4 py-2 font-medium text-white transition-colors hover:bg-green-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
Start
|
||||
</button>
|
||||
|
||||
<form action={restartServerEventAction.bind(null, server.id)}>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={server.status === ServiceStatus.Stopped}
|
||||
className="rounded bg-yellow-600 px-4 py-2 font-medium text-white transition-colors hover:bg-yellow-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
Restart
|
||||
</button>
|
||||
</form>
|
||||
<button
|
||||
type="button"
|
||||
onClick={restartServer}
|
||||
disabled={server.status === ServiceStatus.Stopped || disabled || isPending}
|
||||
className="rounded bg-yellow-600 px-4 py-2 font-medium text-white transition-colors hover:bg-yellow-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
Restart
|
||||
</button>
|
||||
|
||||
<form action={stopServerEventAction.bind(null, server.id)}>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={server.status === ServiceStatus.Stopped}
|
||||
className="rounded bg-red-600 px-4 py-2 font-medium text-white transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
Stop
|
||||
</button>
|
||||
</form>
|
||||
<button
|
||||
type="button"
|
||||
onClick={stopServer}
|
||||
disabled={server.status === ServiceStatus.Stopped || disabled || isPending}
|
||||
className="rounded bg-red-600 px-4 py-2 font-medium text-white transition-colors hover:bg-red-700 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
Stop
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -108,6 +150,12 @@ export function ServerHeader({ server }: ServerHeaderProps) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DeleteServerModal
|
||||
isOpen={isDeleteModalOpen}
|
||||
onClose={() => setIsDeleteModalOpen(false)}
|
||||
server={server}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Server } from '@/lib/types/server';
|
||||
import { User, hasPermission } from '@/lib/types/user';
|
||||
import { Server } from '@/lib/schemas/server';
|
||||
import { User, hasPermission } from '@/lib/schemas/user';
|
||||
import { ServerCard } from './ServerCard';
|
||||
import { CreateServerModal } from './CreateServerModal';
|
||||
import RefreshButton from '@/components/ui/RefreshButton';
|
||||
@@ -41,7 +41,7 @@ export function ServerListWithActions({ servers, user }: ServerListWithActionsPr
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
{servers.map((server) => (
|
||||
<ServerCard key={server.id} server={server} user={user} />
|
||||
<ServerCard key={server.id} server={server} />
|
||||
))}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
interface RecentSession {
|
||||
id: number;
|
||||
id: string;
|
||||
date: string;
|
||||
type: string;
|
||||
track: string;
|
||||
|
||||
@@ -14,16 +14,16 @@ interface SessionTypesChartProps {
|
||||
data: SessionCount[];
|
||||
}
|
||||
|
||||
export function SessionTypesChart({ data }: SessionTypesChartProps) {
|
||||
const colors = [
|
||||
'#3b82f6', // blue
|
||||
'#10b981', // emerald
|
||||
'#f59e0b', // amber
|
||||
'#ef4444', // red
|
||||
'#8b5cf6', // violet
|
||||
'#06b6d4' // cyan
|
||||
];
|
||||
const colors = [
|
||||
'#3b82f6', // blue
|
||||
'#10b981', // emerald
|
||||
'#f59e0b', // amber
|
||||
'#ef4444', // red
|
||||
'#8b5cf6', // violet
|
||||
'#06b6d4' // cyan
|
||||
];
|
||||
|
||||
export function SessionTypesChart({ data }: SessionTypesChartProps) {
|
||||
const chartData = {
|
||||
labels: data.map((item) => item.name),
|
||||
datasets: [
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import type { StateHistoryStats } from '@/lib/types/statistics';
|
||||
import type { StateHistoryStats } from '@/lib/schemas/statistics';
|
||||
import { PlayerCountChart } from './PlayerCountChart';
|
||||
import { SessionTypesChart } from './SessionTypesChart';
|
||||
import { DailyActivityChart } from './DailyActivityChart';
|
||||
|
||||
@@ -8,27 +8,27 @@ interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
const baseClasses =
|
||||
'inline-flex items-center justify-center font-medium rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed';
|
||||
|
||||
const variants = {
|
||||
primary: 'bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500',
|
||||
secondary: 'bg-gray-600 text-white hover:bg-gray-700 focus:ring-gray-500',
|
||||
danger: 'bg-red-600 text-white hover:bg-red-700 focus:ring-red-500',
|
||||
ghost: 'text-gray-300 hover:text-white hover:bg-gray-700 focus:ring-gray-500'
|
||||
};
|
||||
|
||||
const sizes = {
|
||||
sm: 'px-3 py-1 text-sm',
|
||||
md: 'px-4 py-2 text-sm',
|
||||
lg: 'px-6 py-3 text-base'
|
||||
};
|
||||
|
||||
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
(
|
||||
{ className, variant = 'primary', size = 'md', isLoading, children, disabled, ...props },
|
||||
ref
|
||||
) => {
|
||||
const baseClasses =
|
||||
'inline-flex items-center justify-center font-medium rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed';
|
||||
|
||||
const variants = {
|
||||
primary: 'bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500',
|
||||
secondary: 'bg-gray-600 text-white hover:bg-gray-700 focus:ring-gray-500',
|
||||
danger: 'bg-red-600 text-white hover:bg-red-700 focus:ring-red-500',
|
||||
ghost: 'text-gray-300 hover:text-white hover:bg-gray-700 focus:ring-gray-500'
|
||||
};
|
||||
|
||||
const sizes = {
|
||||
sm: 'px-3 py-1 text-sm',
|
||||
md: 'px-4 py-2 text-sm',
|
||||
lg: 'px-6 py-3 text-base'
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
className={cn(baseClasses, variants[variant], sizes[size], className)}
|
||||
|
||||
29
src/components/ui/LogoutButton.tsx
Normal file
29
src/components/ui/LogoutButton.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
'use client';
|
||||
|
||||
import { logoutAction } from '@/lib/actions/auth';
|
||||
import { useActionState } from 'react';
|
||||
|
||||
export default function LogoutButton() {
|
||||
const [, formAction] = useActionState(logoutAction, null);
|
||||
return (
|
||||
<form action={formAction}>
|
||||
<button type="submit" className="flex items-center text-gray-300 hover:text-white">
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="h-6 w-6"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
|
||||
/>
|
||||
</svg>
|
||||
<span className="ml-1 hidden sm:inline">Logout</span>
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { redirect } from 'next/navigation';
|
||||
import { loginUser, getOpenToken } from '@/lib/api/server/auth';
|
||||
import { login } from '@/lib/auth/server';
|
||||
import { login, logout } from '@/lib/auth/server';
|
||||
import { loginSchema, loginResponseSchema } from '../schemas';
|
||||
|
||||
export type LoginResult = {
|
||||
success: boolean;
|
||||
@@ -14,18 +15,19 @@ export async function loginAction(prevState: LoginResult, formData: FormData) {
|
||||
const username = formData.get('username') as string;
|
||||
const password = formData.get('password') as string;
|
||||
|
||||
if (!username || !password) {
|
||||
const loginData = loginSchema.safeParse({ username, password });
|
||||
if (!loginData.success) {
|
||||
return {
|
||||
success: false,
|
||||
message: 'Username and password are required'
|
||||
message: loginData.error.message
|
||||
};
|
||||
}
|
||||
|
||||
const result = await loginUser(username, password);
|
||||
const result = loginResponseSchema.safeParse(await loginUser(loginData.data));
|
||||
|
||||
if (result.token && result.user) {
|
||||
const openToken = await getOpenToken(result.token);
|
||||
await login(result.token, result.user, openToken);
|
||||
if (result.success) {
|
||||
const openToken = await getOpenToken(result.data.token);
|
||||
await login(result.data.token, result.data.user, openToken);
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
@@ -43,5 +45,9 @@ export async function loginAction(prevState: LoginResult, formData: FormData) {
|
||||
}
|
||||
|
||||
export async function logoutAction() {
|
||||
redirect('/logout');
|
||||
await logout();
|
||||
}
|
||||
|
||||
export async function clearExpiredSessionAction() {
|
||||
await logout();
|
||||
}
|
||||
|
||||
@@ -3,14 +3,21 @@
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { updateServerConfiguration } from '@/lib/api/server/configuration';
|
||||
import { ConfigFile } from '@/lib/types/config';
|
||||
import {
|
||||
assistRulesSchema,
|
||||
ConfigFile,
|
||||
eventConfigSchema,
|
||||
eventRulesSchema,
|
||||
serverSettingsSchema
|
||||
} from '@/lib/schemas/config';
|
||||
import type {
|
||||
Configuration,
|
||||
AssistRules,
|
||||
EventConfig,
|
||||
EventRules,
|
||||
ServerSettings
|
||||
} from '@/lib/types/config';
|
||||
} from '@/lib/schemas/config';
|
||||
import { boolToInt } from '@/lib/utils';
|
||||
|
||||
export async function updateConfigurationAction(serverId: string, formData: FormData) {
|
||||
try {
|
||||
@@ -49,7 +56,7 @@ export async function updateAssistRulesAction(serverId: string, formData: FormDa
|
||||
const session = await requireAuth();
|
||||
const restart = formData.get('restart') === 'on';
|
||||
|
||||
const config: AssistRules = {
|
||||
const rawConfig: AssistRules = {
|
||||
stabilityControlLevelMax: parseInt(formData.get('stabilityControlLevelMax') as string),
|
||||
disableAutosteer: parseInt(formData.get('disableAutosteer') as string),
|
||||
disableAutoLights: parseInt(formData.get('disableAutoLights') as string),
|
||||
@@ -61,11 +68,16 @@ export async function updateAssistRulesAction(serverId: string, formData: FormDa
|
||||
disableIdealLine: parseInt(formData.get('disableIdealLine') as string)
|
||||
};
|
||||
|
||||
const config = assistRulesSchema.safeParse(rawConfig);
|
||||
if (!config.success) {
|
||||
return { success: false, message: config.error.message };
|
||||
}
|
||||
|
||||
await updateServerConfiguration(
|
||||
session.token!,
|
||||
serverId,
|
||||
ConfigFile.assistRules,
|
||||
config,
|
||||
config.data,
|
||||
restart
|
||||
);
|
||||
revalidatePath(`/dashboard/server/${serverId}`);
|
||||
@@ -84,7 +96,7 @@ export async function updateServerSettingsAction(serverId: string, formData: For
|
||||
const session = await requireAuth();
|
||||
const restart = formData.get('restart') === 'on';
|
||||
|
||||
const config: ServerSettings = {
|
||||
const rawConfig: ServerSettings = {
|
||||
serverName: formData.get('serverName') as string,
|
||||
adminPassword: formData.get('adminPassword') as string,
|
||||
carGroup: formData.get('carGroup') as string,
|
||||
@@ -103,8 +115,18 @@ export async function updateServerSettingsAction(serverId: string, formData: For
|
||||
formationLapType: parseInt(formData.get('formationLapType') as string),
|
||||
ignorePrematureDisconnects: parseInt(formData.get('ignorePrematureDisconnects') as string)
|
||||
};
|
||||
const config = serverSettingsSchema.safeParse(rawConfig);
|
||||
if (!config.success) {
|
||||
return { success: false, message: config.error.message };
|
||||
}
|
||||
|
||||
await updateServerConfiguration(session.token!, serverId, ConfigFile.settings, config, restart);
|
||||
await updateServerConfiguration(
|
||||
session.token!,
|
||||
serverId,
|
||||
ConfigFile.settings,
|
||||
config.data,
|
||||
restart
|
||||
);
|
||||
revalidatePath(`/dashboard/server/${serverId}`);
|
||||
|
||||
return { success: true, message: 'Server settings updated successfully' };
|
||||
@@ -124,7 +146,7 @@ export async function updateEventConfigAction(serverId: string, formData: FormDa
|
||||
const sessionsData = formData.get('sessions') as string;
|
||||
const sessions = sessionsData ? JSON.parse(sessionsData) : [];
|
||||
|
||||
const config: EventConfig = {
|
||||
const rawConfig: EventConfig = {
|
||||
track: formData.get('track') as string,
|
||||
preRaceWaitingTimeSeconds: parseInt(formData.get('preRaceWaitingTimeSeconds') as string),
|
||||
sessionOverTimeSeconds: parseInt(formData.get('sessionOverTimeSeconds') as string),
|
||||
@@ -140,8 +162,18 @@ export async function updateEventConfigAction(serverId: string, formData: FormDa
|
||||
),
|
||||
sessions
|
||||
};
|
||||
const config = eventConfigSchema.safeParse(rawConfig);
|
||||
if (!config.success) {
|
||||
return { success: false, message: config.error.message };
|
||||
}
|
||||
|
||||
await updateServerConfiguration(session.token!, serverId, ConfigFile.event, config, restart);
|
||||
await updateServerConfiguration(
|
||||
session.token!,
|
||||
serverId,
|
||||
ConfigFile.event,
|
||||
config.data,
|
||||
restart
|
||||
);
|
||||
revalidatePath(`/dashboard/server/${serverId}`);
|
||||
|
||||
return {
|
||||
@@ -161,28 +193,33 @@ export async function updateEventRulesAction(serverId: string, formData: FormDat
|
||||
const session = await requireAuth();
|
||||
const restart = formData.get('restart') === 'on';
|
||||
|
||||
const config: EventRules = {
|
||||
const rawConfig: EventRules = {
|
||||
qualifyStandingType: parseInt(formData.get('qualifyStandingType') as string),
|
||||
pitWindowLengthSec: parseInt(formData.get('pitWindowLengthSec') as string),
|
||||
driverStintTimeSec: parseInt(formData.get('driverStintTimeSec') as string),
|
||||
mandatoryPitstopCount: parseInt(formData.get('mandatoryPitstopCount') as string),
|
||||
maxTotalDrivingTime: parseInt(formData.get('maxTotalDrivingTime') as string),
|
||||
isRefuellingAllowedInRace: formData.get('isRefuellingAllowedInRace') === 'true',
|
||||
isRefuellingTimeFixed: formData.get('isRefuellingTimeFixed') === 'true',
|
||||
isRefuellingAllowedInRace: boolToInt(formData.get('isRefuellingAllowedInRace') === 'true'),
|
||||
isRefuellingTimeFixed: boolToInt(formData.get('isRefuellingTimeFixed') === 'true'),
|
||||
isMandatoryPitstopRefuellingRequired:
|
||||
formData.get('isMandatoryPitstopRefuellingRequired') === 'true',
|
||||
boolToInt(formData.get('isMandatoryPitstopRefuellingRequired') === 'true'),
|
||||
isMandatoryPitstopTyreChangeRequired:
|
||||
formData.get('isMandatoryPitstopTyreChangeRequired') === 'true',
|
||||
boolToInt(formData.get('isMandatoryPitstopTyreChangeRequired') === 'true'),
|
||||
isMandatoryPitstopSwapDriverRequired:
|
||||
formData.get('isMandatoryPitstopSwapDriverRequired') === 'true',
|
||||
boolToInt(formData.get('isMandatoryPitstopSwapDriverRequired') === 'true'),
|
||||
tyreSetCount: parseInt(formData.get('tyreSetCount') as string)
|
||||
};
|
||||
|
||||
const config = eventRulesSchema.safeParse(rawConfig);
|
||||
if (!config.success) {
|
||||
return { success: false, message: config.error.message };
|
||||
}
|
||||
|
||||
await updateServerConfiguration(
|
||||
session.token!,
|
||||
serverId,
|
||||
ConfigFile.eventRules,
|
||||
config,
|
||||
config.data,
|
||||
restart
|
||||
);
|
||||
revalidatePath(`/dashboard/server/${serverId}`);
|
||||
|
||||
24
src/lib/actions/leaderboard.ts
Normal file
24
src/lib/actions/leaderboard.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
'use server';
|
||||
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { fetchServerAPI } from '@/lib/api/server/base';
|
||||
import { leaderboardSchema, type Leaderboard } from '@/lib/schemas/leaderboard';
|
||||
|
||||
export async function saveLeaderboardAction(serverId: string, data: Leaderboard) {
|
||||
try {
|
||||
const session = await requireAuth();
|
||||
const validated = leaderboardSchema.safeParse(data);
|
||||
if (!validated.success) {
|
||||
return { success: false, message: validated.error.message };
|
||||
}
|
||||
await fetchServerAPI(`/server/${serverId}/leaderboard`, session.token!, 'PUT', validated.data);
|
||||
revalidatePath(`/dashboard/server/${serverId}`);
|
||||
return { success: true, message: 'Leaderboard saved successfully' };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: error instanceof Error ? error.message : 'Failed to save leaderboard'
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { requireAuth } from '@/lib/auth/server';
|
||||
import { createUser, deleteUser } from '@/lib/api/server/membership';
|
||||
import { userCreateSchema } from '../schemas';
|
||||
|
||||
export async function createUserAction(formData: FormData) {
|
||||
try {
|
||||
@@ -11,7 +12,13 @@ export async function createUserAction(formData: FormData) {
|
||||
const password = formData.get('password') as string;
|
||||
const role = formData.get('role') as string;
|
||||
|
||||
await createUser(session.token!, { username, password, role });
|
||||
const rawData = { username, password, role };
|
||||
const data = userCreateSchema.safeParse(rawData);
|
||||
if (!data.success) {
|
||||
return { success: false, message: data.error.message };
|
||||
}
|
||||
|
||||
await createUser(session.token!, data.data);
|
||||
revalidatePath('/dashboard/membership');
|
||||
|
||||
return { success: true, message: 'User created successfully' };
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { SessionData } from '@/lib/session/config';
|
||||
|
||||
const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:8080';
|
||||
|
||||
export type ClientApiResponse<T> = {
|
||||
@@ -8,6 +10,14 @@ export type ClientApiResponse<T> = {
|
||||
message?: string;
|
||||
};
|
||||
|
||||
const getSession = async (): Promise<SessionData | null> => {
|
||||
const response = await fetch('/api/session');
|
||||
if (response.ok) {
|
||||
return await response.json();
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export async function fetchClientAPI<T>(
|
||||
endpoint: string,
|
||||
method: string = 'GET',
|
||||
@@ -15,13 +25,11 @@ export async function fetchClientAPI<T>(
|
||||
customToken?: string
|
||||
): Promise<ClientApiResponse<T>> {
|
||||
let token = customToken;
|
||||
let session: SessionData | null = null;
|
||||
|
||||
if (!token) {
|
||||
const response = await fetch('/api/session');
|
||||
if (response.ok) {
|
||||
const session = await response.json();
|
||||
token = session.openToken;
|
||||
}
|
||||
session = await getSession();
|
||||
token = session?.openToken;
|
||||
|
||||
if (!token) {
|
||||
throw new Error('No authentication token available');
|
||||
@@ -41,7 +49,7 @@ export async function fetchClientAPI<T>(
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
window.location.href = '/logout';
|
||||
window.location.href = '/login?expired=true';
|
||||
return { error: 'unauthorized' };
|
||||
}
|
||||
throw new Error(`API Error: ${response.statusText} - ${method} - ${BASE_URL}${endpoint}`);
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
import { User } from '@/lib/types';
|
||||
import {
|
||||
Login,
|
||||
LoginResponse,
|
||||
loginResponseSchema,
|
||||
loginSchema,
|
||||
loginTokenSchema,
|
||||
User,
|
||||
userSchema
|
||||
} from '@/lib/schemas';
|
||||
import { fetchServerAPI } from './base';
|
||||
|
||||
const BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080';
|
||||
|
||||
const authRoute = '/auth';
|
||||
|
||||
export async function loginUser(username: string, password: string) {
|
||||
export async function loginUser(login: Login): Promise<LoginResponse> {
|
||||
const validatedLogin = loginSchema.parse(login);
|
||||
const response = await fetch(`${BASE_URL}${authRoute}/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ username, password })
|
||||
body: JSON.stringify(validatedLogin)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -22,16 +31,18 @@ export async function loginUser(username: string, password: string) {
|
||||
throw new Error(`Login failed: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const { token } = await response.json();
|
||||
const rawData = await response.json();
|
||||
|
||||
const { token } = loginTokenSchema.parse(rawData);
|
||||
|
||||
const userResponse = await getCurrentUser(token);
|
||||
|
||||
return { token, user: userResponse };
|
||||
return loginResponseSchema.parse({ token, user: userResponse });
|
||||
}
|
||||
|
||||
export async function getCurrentUser(token: string): Promise<User> {
|
||||
const response = await fetchServerAPI<User>(`${authRoute}/me`, token);
|
||||
return response.data!;
|
||||
return userSchema.parse(response.data);
|
||||
}
|
||||
|
||||
export async function getOpenToken(token: string): Promise<string> {
|
||||
@@ -40,5 +51,5 @@ export async function getOpenToken(token: string): Promise<string> {
|
||||
token,
|
||||
'POST'
|
||||
);
|
||||
return response.data!.token;
|
||||
return loginTokenSchema.parse(response.data).token;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
const BASE_URL = process.env.API_BASE_URL || 'http://localhost:8080';
|
||||
|
||||
type ApiResponse<T> = {
|
||||
@@ -8,6 +6,8 @@ type ApiResponse<T> = {
|
||||
message?: string;
|
||||
};
|
||||
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
export async function fetchServerAPI<T>(
|
||||
endpoint: string,
|
||||
token: string,
|
||||
@@ -28,8 +28,7 @@ export async function fetchServerAPI<T>(
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status == 401) {
|
||||
redirect('/logout');
|
||||
return { error: 'unauthorized' };
|
||||
redirect('/login?expired=true');
|
||||
}
|
||||
throw new Error(
|
||||
`API Error: ${response.statusText} - ${method} - ${BASE_URL}${endpoint} - ${token}`
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import type { Configurations, ConfigFile, Config } from '@/lib/types/config';
|
||||
import {
|
||||
type Configurations,
|
||||
type Config,
|
||||
ConfigFile,
|
||||
configurationsSchema,
|
||||
configSchemaMap
|
||||
} from '@/lib/schemas/config';
|
||||
import * as z from 'zod';
|
||||
|
||||
const serverRoute = '/server';
|
||||
|
||||
@@ -7,8 +14,16 @@ export async function getServerConfigurations(
|
||||
token: string,
|
||||
serverId: string
|
||||
): Promise<Configurations> {
|
||||
const response = await fetchServerAPI<Configurations>(`${serverRoute}/${serverId}/config`, token);
|
||||
return response.data!;
|
||||
const response = await fetchServerAPI<Configurations>(`${serverRoute}/${serverId}/config`, token);
|
||||
return configurationsSchema.parse(response.data);
|
||||
}
|
||||
|
||||
export function validateConfig(
|
||||
configType: ConfigFile,
|
||||
data: unknown
|
||||
): z.infer<(typeof configSchemaMap)[typeof configType]> {
|
||||
const schema = configSchemaMap[configType];
|
||||
return schema.parse(data);
|
||||
}
|
||||
|
||||
export async function getServerConfiguration(
|
||||
@@ -20,7 +35,7 @@ export async function getServerConfiguration(
|
||||
`${serverRoute}/${serverId}/config/${configType}`,
|
||||
token
|
||||
);
|
||||
return response.data!;
|
||||
return validateConfig(configType, response.data);
|
||||
}
|
||||
|
||||
export async function updateServerConfiguration(
|
||||
@@ -30,8 +45,8 @@ export async function updateServerConfiguration(
|
||||
config: Config,
|
||||
restart = false
|
||||
): Promise<void> {
|
||||
await fetchServerAPI(`${serverRoute}/${serverId}/config/${configType}`, token, 'PUT', {
|
||||
...config,
|
||||
await fetchServerAPI(`${serverRoute}/${serverId}/config/${configType}?override=true`, token, 'PUT', {
|
||||
...validateConfig(configType, config),
|
||||
restart
|
||||
});
|
||||
}
|
||||
|
||||
8
src/lib/api/server/leaderboard.ts
Normal file
8
src/lib/api/server/leaderboard.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import { emptyLeaderboard, leaderboardSchema, type Leaderboard } from '@/lib/schemas/leaderboard';
|
||||
|
||||
export async function getLeaderboard(token: string, serverId: string): Promise<Leaderboard> {
|
||||
const response = await fetchServerAPI<Leaderboard>(`/server/${serverId}/leaderboard`, token);
|
||||
const parsed = leaderboardSchema.safeParse(response.data);
|
||||
return parsed.success ? parsed.data : emptyLeaderboard;
|
||||
}
|
||||
@@ -1,21 +1,32 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import { Track, CarModel, CupCategory, DriverCategory, SessionType } from '@/lib/types';
|
||||
import {
|
||||
Track,
|
||||
CarModel,
|
||||
CupCategory,
|
||||
DriverCategory,
|
||||
SessionType,
|
||||
trackSchema,
|
||||
carModelSchema,
|
||||
cupCategorySchema,
|
||||
driverCategorySchema,
|
||||
sessionTypeSchema
|
||||
} from '@/lib/schemas';
|
||||
|
||||
const lookupRoute = '/lookup';
|
||||
|
||||
export async function getTracks(token: string): Promise<Track[]> {
|
||||
const response = await fetchServerAPI<Track[]>(`${lookupRoute}/tracks`, token);
|
||||
return response.data!;
|
||||
return trackSchema.array().parse(response.data);
|
||||
}
|
||||
|
||||
export async function getCarModels(token: string): Promise<CarModel[]> {
|
||||
const response = await fetchServerAPI<CarModel[]>(`${lookupRoute}/car-models`, token);
|
||||
return response.data!;
|
||||
return carModelSchema.array().parse(response.data);
|
||||
}
|
||||
|
||||
export async function getCupCategories(token: string): Promise<CupCategory[]> {
|
||||
const response = await fetchServerAPI<CupCategory[]>(`${lookupRoute}/cup-categories`, token);
|
||||
return response.data!;
|
||||
return cupCategorySchema.array().parse(response.data);
|
||||
}
|
||||
|
||||
export async function getDriverCategories(token: string): Promise<DriverCategory[]> {
|
||||
@@ -23,10 +34,10 @@ export async function getDriverCategories(token: string): Promise<DriverCategory
|
||||
`${lookupRoute}/driver-categories`,
|
||||
token
|
||||
);
|
||||
return response.data!;
|
||||
return driverCategorySchema.array().parse(response.data);
|
||||
}
|
||||
|
||||
export async function getSessionTypes(token: string): Promise<SessionType[]> {
|
||||
const response = await fetchServerAPI<SessionType[]>(`${lookupRoute}/session-types`, token);
|
||||
return response.data!;
|
||||
return sessionTypeSchema.array().parse(response.data);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { use } from 'react';
|
||||
import { fetchServerAPI } from './base';
|
||||
import { User, Role } from '@/lib/types';
|
||||
import { User, Role, userSchema, UserCreate, userCreateSchema, roleSchema } from '@/lib/schemas';
|
||||
|
||||
export interface UserListParams {
|
||||
username?: string;
|
||||
@@ -25,27 +26,29 @@ export async function getUsers(token: string, params: UserListParams = {}): Prom
|
||||
const endpoint = `${membershipRoute}${queryString ? `?${queryString}` : ''}`;
|
||||
|
||||
const response = await fetchServerAPI<User[]>(endpoint, token);
|
||||
return response.data!;
|
||||
return userSchema.array().parse(response.data);
|
||||
}
|
||||
|
||||
export async function createUser(
|
||||
token: string,
|
||||
userData: { username: string; password: string; role: string }
|
||||
): Promise<void> {
|
||||
await fetchServerAPI(membershipRoute, token, 'POST', userData);
|
||||
export async function createUser(token: string, userData: UserCreate): Promise<void> {
|
||||
await fetchServerAPI(membershipRoute, token, 'POST', userCreateSchema.parse(userData));
|
||||
}
|
||||
|
||||
export async function getUserById(token: string, userId: string): Promise<User> {
|
||||
const response = await fetchServerAPI<User>(`${membershipRoute}/${userId}`, token);
|
||||
return response.data!;
|
||||
return userSchema.parse(response.data);
|
||||
}
|
||||
|
||||
export async function updateUser(
|
||||
token: string,
|
||||
userId: string,
|
||||
userData: Partial<User>
|
||||
userData: Partial<UserCreate>
|
||||
): Promise<void> {
|
||||
await fetchServerAPI(`${membershipRoute}/${userId}`, token, 'PUT', userData);
|
||||
await fetchServerAPI(
|
||||
`${membershipRoute}/${userId}`,
|
||||
token,
|
||||
'PUT',
|
||||
userCreateSchema.parse(userData)
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteUser(token: string, userId: string): Promise<void> {
|
||||
@@ -54,5 +57,5 @@ export async function deleteUser(token: string, userId: string): Promise<void> {
|
||||
|
||||
export async function getRoles(token: string): Promise<Role[]> {
|
||||
const response = await fetchServerAPI<Role[]>(`${membershipRoute}/roles`, token);
|
||||
return response.data!;
|
||||
return roleSchema.array().parse(response.data);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import { Server, ServiceStatus } from '@/lib/types/server';
|
||||
import { Server, serverSchema, ServiceStatus, serviceStatusSchema } from '@/lib/schemas/server';
|
||||
|
||||
const serverRoute = '/server';
|
||||
|
||||
export async function getServers(token: string): Promise<Server[]> {
|
||||
const response = await fetchServerAPI<Server[]>(serverRoute, token);
|
||||
return response.data!;
|
||||
return serverSchema.array().parse(response.data);
|
||||
}
|
||||
|
||||
export async function getServer(token: string, serverId: string): Promise<Server> {
|
||||
const response = await fetchServerAPI<Server>(`${serverRoute}/${serverId}`, token);
|
||||
return response.data!;
|
||||
return serverSchema.parse(response.data);
|
||||
}
|
||||
|
||||
export async function restartService(token: string, serverId: string): Promise<void> {
|
||||
@@ -27,12 +27,12 @@ export async function stopService(token: string, serverId: string): Promise<void
|
||||
|
||||
export async function getServiceStatus(token: string, serverId: string): Promise<ServiceStatus> {
|
||||
const response = await fetchServerAPI<ServiceStatus>(`${serverRoute}/${serverId}/service`, token);
|
||||
return response.data!;
|
||||
return serviceStatusSchema.parse(response.data);
|
||||
}
|
||||
|
||||
export async function createServer(token: string, name: string): Promise<Server> {
|
||||
const response = await fetchServerAPI<Server>(serverRoute, token, 'POST', { name });
|
||||
return response.data!;
|
||||
return serverSchema.parse(response.data);
|
||||
}
|
||||
|
||||
export async function deleteServer(token: string, serverId: string): Promise<void> {
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import { fetchServerAPI } from './base';
|
||||
import type { StateHistoryStats } from '@/lib/types/statistics';
|
||||
import {
|
||||
StateHistoryStatsFilter,
|
||||
stateHistoryStatsFilterSchema,
|
||||
stateHistoryStatsSchema,
|
||||
type StateHistoryStats
|
||||
} from '@/lib/schemas/statistics';
|
||||
|
||||
const serverRoute = '/server';
|
||||
|
||||
export async function getServerStatistics(
|
||||
token: string,
|
||||
serverId: string,
|
||||
startDate: string,
|
||||
endDate: string
|
||||
filters: StateHistoryStatsFilter
|
||||
): Promise<StateHistoryStats> {
|
||||
const { startDate, endDate } = stateHistoryStatsFilterSchema.parse(filters);
|
||||
const response = await fetchServerAPI<StateHistoryStats>(
|
||||
`${serverRoute}/${serverId}/state-history/statistics?start_date=${startDate}&end_date=${endDate}`,
|
||||
token
|
||||
);
|
||||
return response.data!;
|
||||
return stateHistoryStatsSchema.parse(response.data);
|
||||
}
|
||||
|
||||
@@ -8,11 +8,11 @@ export async function getSession() {
|
||||
return session;
|
||||
}
|
||||
|
||||
export async function requireAuth() {
|
||||
export async function requireAuth(skipRedirect?: boolean) {
|
||||
const session = await getSession();
|
||||
|
||||
if (!session.token || !session.user) {
|
||||
redirect('/logout');
|
||||
if (!skipRedirect && (!session.token || !session.user)) {
|
||||
redirect('/login?expired=true');
|
||||
}
|
||||
|
||||
return session;
|
||||
@@ -27,6 +27,7 @@ export async function login(token: string, user: SessionData['user'], openToken?
|
||||
}
|
||||
|
||||
export async function logout() {
|
||||
'use server';
|
||||
const session = await getSession();
|
||||
session.destroy();
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { createContext, useContext, useState, ReactNode, useEffect, useCallback } from 'react';
|
||||
import { useWebSocket } from '@/lib/websocket/context';
|
||||
import { WebSocketMessage, StepData } from '@/lib/websocket/client';
|
||||
import type { WebSocketMessage, StepData } from '@/lib/schemas/websocket';
|
||||
|
||||
interface SteamCMDContextType {
|
||||
isSteamCMDRunning: boolean;
|
||||
|
||||
131
src/lib/schemas/config.ts
Normal file
131
src/lib/schemas/config.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import * as z from 'zod';
|
||||
|
||||
export enum ConfigFile {
|
||||
configuration = 'configuration.json',
|
||||
assistRules = 'assistRules.json',
|
||||
event = 'event.json',
|
||||
eventRules = 'eventRules.json',
|
||||
settings = 'settings.json'
|
||||
}
|
||||
export const configFileSchema = z.enum(ConfigFile);
|
||||
|
||||
export enum ServerTab {
|
||||
statistics = 'statistics',
|
||||
configuration = 'configuration',
|
||||
assistRules = 'assistRules',
|
||||
event = 'event',
|
||||
eventRules = 'eventRules',
|
||||
settings = 'settings',
|
||||
leaderboard = 'leaderboard'
|
||||
}
|
||||
export const serverTabSchema = z.enum(ServerTab);
|
||||
|
||||
export const configurationSchema = z.object({
|
||||
udpPort: z.number().min(1025).max(65535),
|
||||
tcpPort: z.number().min(1025).max(65535),
|
||||
maxConnections: z.number().min(1).max(64),
|
||||
lanDiscovery: z.number().min(0).max(1),
|
||||
registerToLobby: z.number().min(0).max(2),
|
||||
configVersion: z.number().min(1).max(2).default(1).optional()
|
||||
});
|
||||
|
||||
export type Configuration = z.infer<typeof configurationSchema>;
|
||||
|
||||
export const assistRulesSchema = z.object({
|
||||
stabilityControlLevelMax: z.number().min(0).max(100).default(100),
|
||||
disableAutosteer: z.number().min(0).max(1).default(0),
|
||||
disableAutoLights: z.number().min(0).max(1).default(0),
|
||||
disableAutoWiper: z.number().min(0).max(1).default(0),
|
||||
disableAutoEngineStart: z.number().min(0).max(1).default(0),
|
||||
disableAutoPitLimiter: z.number().min(0).max(1).default(0),
|
||||
disableAutoGear: z.number().min(0).max(1).default(0),
|
||||
disableAutoClutch: z.number().min(0).max(1).default(0),
|
||||
disableIdealLine: z.number().min(0).max(1).default(0)
|
||||
});
|
||||
|
||||
export type AssistRules = z.infer<typeof assistRulesSchema>;
|
||||
|
||||
export const serverSettingsSchema = z.object({
|
||||
serverName: z.string().min(3).max(150),
|
||||
adminPassword: z.string().min(6).max(50),
|
||||
carGroup: z.string().min(1).max(50),
|
||||
trackMedalsRequirement: z.number().min(-1).max(3),
|
||||
safetyRatingRequirement: z.number().min(-1).max(99),
|
||||
racecraftRatingRequirement: z.number().min(-1).max(99),
|
||||
password: z.string().max(50).optional().or(z.literal('')),
|
||||
spectatorPassword: z.string().max(50).optional().or(z.literal('')),
|
||||
maxCarSlots: z.number().min(1).max(30),
|
||||
dumpLeaderboards: z.number().min(0).max(1).default(0),
|
||||
isRaceLocked: z.number().min(0).max(1).default(0),
|
||||
randomizeTrackWhenEmpty: z.number().min(0).max(1).default(0),
|
||||
centralEntryListPath: z.string().max(255).optional().or(z.literal('')),
|
||||
allowAutoDQ: z.number().min(0).max(1).default(0),
|
||||
shortFormationLap: z.number().min(0).max(1).default(0),
|
||||
formationLapType: z.number().min(0).max(3).default(0),
|
||||
ignorePrematureDisconnects: z.number().min(0).max(1).default(0)
|
||||
});
|
||||
|
||||
export type ServerSettings = z.infer<typeof serverSettingsSchema>;
|
||||
|
||||
export const sessionSchema = z.object({
|
||||
hourOfDay: z.number().min(1).max(24).default(14),
|
||||
dayOfWeekend: z.number().min(1).max(3).default(1),
|
||||
timeMultiplier: z.number().min(1).max(120).default(1),
|
||||
sessionType: z.string().min(1).max(20),
|
||||
sessionDurationMinutes: z.number().min(1).max(180).default(20)
|
||||
});
|
||||
|
||||
export type Session = z.infer<typeof sessionSchema>;
|
||||
|
||||
export const eventConfigSchema = z.object({
|
||||
track: z.string().min(1).max(100),
|
||||
preRaceWaitingTimeSeconds: z.number().min(0).max(600).default(30),
|
||||
sessionOverTimeSeconds: z.number().min(0).max(300).default(30),
|
||||
ambientTemp: z.number().min(0).max(50).default(24),
|
||||
cloudLevel: z.number().min(0).max(1).default(0),
|
||||
rain: z.number().min(0).max(1).default(0),
|
||||
weatherRandomness: z.number().min(0).max(7).default(0),
|
||||
postQualySeconds: z.number().min(0).max(600).default(30),
|
||||
postRaceSeconds: z.number().min(0).max(600).default(30),
|
||||
simracerWeatherConditions: z.number().min(0).max(1).default(0),
|
||||
isFixedConditionQualification: z.number().min(0).max(1).default(0),
|
||||
sessions: z.array(sessionSchema).min(1).max(10)
|
||||
});
|
||||
|
||||
export type EventConfig = z.infer<typeof eventConfigSchema>;
|
||||
|
||||
export const eventRulesSchema = z.object({
|
||||
qualifyStandingType: z.number().min(-1).max(1).default(0),
|
||||
pitWindowLengthSec: z.number().min(-1).max(3600).default(30),
|
||||
driverStintTimeSec: z.number().min(-1).max(7200).default(30),
|
||||
mandatoryPitstopCount: z.number().min(-1).max(5).default(0),
|
||||
maxTotalDrivingTime: z.number().min(-1).max(14400).default(60),
|
||||
isRefuellingAllowedInRace: z.number().min(0).max(1).default(0),
|
||||
isRefuellingTimeFixed: z.number().min(0).max(1).default(0),
|
||||
isMandatoryPitstopRefuellingRequired: z.number().min(0).max(1).default(0),
|
||||
isMandatoryPitstopTyreChangeRequired: z.number().min(0).max(1).default(0),
|
||||
isMandatoryPitstopSwapDriverRequired: z.number().min(0).max(1).default(0),
|
||||
tyreSetCount: z.number().min(0).max(50).default(0)
|
||||
});
|
||||
|
||||
export type EventRules = z.infer<typeof eventRulesSchema>;
|
||||
|
||||
export const configurationsSchema = z.object({
|
||||
configuration: configurationSchema,
|
||||
assistRules: assistRulesSchema,
|
||||
settings: serverSettingsSchema,
|
||||
event: eventConfigSchema,
|
||||
eventRules: eventRulesSchema
|
||||
});
|
||||
|
||||
export type Configurations = z.infer<typeof configurationsSchema>;
|
||||
|
||||
export const configSchemaMap = {
|
||||
[ConfigFile.configuration]: configurationSchema,
|
||||
[ConfigFile.assistRules]: assistRulesSchema,
|
||||
[ConfigFile.event]: eventConfigSchema,
|
||||
[ConfigFile.eventRules]: eventRulesSchema,
|
||||
[ConfigFile.settings]: serverSettingsSchema
|
||||
};
|
||||
|
||||
export type Config = Configuration | AssistRules | EventConfig | EventRules | ServerSettings;
|
||||
@@ -3,3 +3,4 @@ export * from './user';
|
||||
export * from './config';
|
||||
export * from './statistics';
|
||||
export * from './lookups';
|
||||
export * from './leaderboard';
|
||||
56
src/lib/schemas/leaderboard.ts
Normal file
56
src/lib/schemas/leaderboard.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import * as z from 'zod';
|
||||
|
||||
export const resultValueSchema = z.union([z.literal('DNF'), z.literal('DNS'), z.coerce.number().int().min(0)]);
|
||||
export type ResultValue = z.infer<typeof resultValueSchema>;
|
||||
|
||||
export const leaderboardDriverSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
color: z.string().regex(/^#[0-9a-fA-F]{6}$/),
|
||||
initials: z.string().min(1).max(10)
|
||||
});
|
||||
export type LeaderboardDriver = z.infer<typeof leaderboardDriverSchema>;
|
||||
|
||||
const pointsEntryFields = {
|
||||
points: z.number().int().min(0),
|
||||
label: z.string().min(1),
|
||||
color: z.string().regex(/^#[0-9a-fA-F]{6}$/),
|
||||
textColor: z.string().regex(/^#[0-9a-fA-F]{6}$/),
|
||||
priority: z.number().int().min(0)
|
||||
};
|
||||
|
||||
export const pointsEntrySchema = z.object(pointsEntryFields);
|
||||
export type PointsEntry = z.infer<typeof pointsEntrySchema>;
|
||||
|
||||
export const flPointsSchema = z.object(pointsEntryFields);
|
||||
export type FlPoints = z.infer<typeof flPointsSchema>;
|
||||
|
||||
export const leaderboardTrackSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
results: z.array(resultValueSchema),
|
||||
fastestLapInitials: z.string()
|
||||
});
|
||||
export type LeaderboardTrack = z.infer<typeof leaderboardTrackSchema>;
|
||||
|
||||
export const leaderboardSchema = z.object({
|
||||
drivers: z.array(leaderboardDriverSchema),
|
||||
pointsTable: z.array(pointsEntrySchema),
|
||||
flPoints: flPointsSchema,
|
||||
tracks: z.array(leaderboardTrackSchema)
|
||||
});
|
||||
export type Leaderboard = z.infer<typeof leaderboardSchema>;
|
||||
|
||||
export const emptyLeaderboard: Leaderboard = {
|
||||
drivers: [],
|
||||
pointsTable: [],
|
||||
flPoints: { points: 1, label: 'FL +1', color: '#8b5cf6', textColor: '#000000', priority: 3 },
|
||||
tracks: []
|
||||
};
|
||||
|
||||
// Client-side derived type — never sent to API
|
||||
export type StandingsRow = {
|
||||
driver: LeaderboardDriver;
|
||||
driverIndex: number;
|
||||
totalPoints: number;
|
||||
trackResults: ResultValue[];
|
||||
fastestLapCount: number;
|
||||
};
|
||||
33
src/lib/schemas/lookups.ts
Normal file
33
src/lib/schemas/lookups.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import * as z from 'zod';
|
||||
|
||||
export const trackSchema = z.object({
|
||||
track: z.string(),
|
||||
uniquePitBoxes: z.number().int().nonnegative(),
|
||||
privateServerSlots: z.number().int().nonnegative()
|
||||
});
|
||||
|
||||
export type Track = z.infer<typeof trackSchema>;
|
||||
|
||||
export const carModelSchema = z.object({
|
||||
value: z.number().int().nonnegative(),
|
||||
carModel: z.string()
|
||||
});
|
||||
export type CarModel = z.infer<typeof carModelSchema>;
|
||||
|
||||
export const driverCategorySchema = z.object({
|
||||
value: z.number().int().nonnegative(),
|
||||
category: z.string()
|
||||
});
|
||||
export type DriverCategory = z.infer<typeof driverCategorySchema>;
|
||||
|
||||
export const cupCategorySchema = z.object({
|
||||
value: z.number().int().nonnegative(),
|
||||
category: z.string()
|
||||
});
|
||||
export type CupCategory = z.infer<typeof cupCategorySchema>;
|
||||
|
||||
export const sessionTypeSchema = z.object({
|
||||
value: z.number().int().nonnegative(),
|
||||
sessionType: z.string()
|
||||
});
|
||||
export type SessionType = z.infer<typeof sessionTypeSchema>;
|
||||
@@ -1,3 +1,5 @@
|
||||
import * as z from 'zod';
|
||||
|
||||
export enum ServiceStatus {
|
||||
Unknown,
|
||||
Stopped,
|
||||
@@ -6,6 +8,7 @@ export enum ServiceStatus {
|
||||
Starting,
|
||||
Running
|
||||
}
|
||||
export const serviceStatusSchema = z.enum(ServiceStatus);
|
||||
|
||||
export const serviceStatusToString = (status: ServiceStatus): string => {
|
||||
switch (status) {
|
||||
@@ -41,16 +44,20 @@ export const getStatusColor = (status: ServiceStatus): string => {
|
||||
}
|
||||
};
|
||||
|
||||
interface State {
|
||||
session: string;
|
||||
playerCount: number;
|
||||
track: string;
|
||||
maxConnections: number;
|
||||
}
|
||||
export const stateSchema = z.object({
|
||||
session: z.string(),
|
||||
playerCount: z.number().min(0),
|
||||
track: z.string(),
|
||||
maxConnections: z.number().min(0)
|
||||
});
|
||||
|
||||
export interface Server {
|
||||
id: string;
|
||||
name: string;
|
||||
status: ServiceStatus;
|
||||
state: State;
|
||||
}
|
||||
export type State = z.infer<typeof stateSchema>;
|
||||
|
||||
export const serverSchema = z.object({
|
||||
id: z.uuid(),
|
||||
name: z.string().min(1),
|
||||
status: z.enum(ServiceStatus),
|
||||
state: stateSchema.optional().nullable()
|
||||
});
|
||||
|
||||
export type Server = z.infer<typeof serverSchema>;
|
||||
58
src/lib/schemas/statistics.ts
Normal file
58
src/lib/schemas/statistics.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import * as z from 'zod';
|
||||
|
||||
export const stateHistorySchema = z.object({
|
||||
dateCreated: z.string(),
|
||||
sessionStart: z.string(),
|
||||
playerCount: z.number(),
|
||||
track: z.string(),
|
||||
sessionDurationMinutes: z.number(),
|
||||
session: z.string()
|
||||
});
|
||||
export type StateHistory = z.infer<typeof stateHistorySchema>;
|
||||
|
||||
export const sessionCountSchema = z.object({
|
||||
name: z.string(),
|
||||
count: z.number()
|
||||
});
|
||||
export type SessionCount = z.infer<typeof sessionCountSchema>;
|
||||
|
||||
export const dailyActivitySchema = z.object({
|
||||
date: z.string(),
|
||||
sessionsCount: z.number()
|
||||
});
|
||||
export type DailyActivity = z.infer<typeof dailyActivitySchema>;
|
||||
|
||||
export const playerCountPointSchema = z.object({
|
||||
timestamp: z.string(),
|
||||
count: z.number()
|
||||
});
|
||||
export type PlayerCountPoint = z.infer<typeof playerCountPointSchema>;
|
||||
|
||||
export const recentSessionSchema = z.object({
|
||||
id: z.uuid(),
|
||||
date: z.string(),
|
||||
type: z.string(),
|
||||
track: z.string(),
|
||||
duration: z.number(),
|
||||
players: z.number()
|
||||
});
|
||||
export type RecentSession = z.infer<typeof recentSessionSchema>;
|
||||
|
||||
export const stateHistoryStatsSchema = z.object({
|
||||
averagePlayers: z.number(),
|
||||
peakPlayers: z.number(),
|
||||
totalSessions: z.number(),
|
||||
totalPlaytime: z.number(),
|
||||
playerCountOverTime: z.array(playerCountPointSchema),
|
||||
sessionTypes: z.array(sessionCountSchema),
|
||||
dailyActivity: z.array(dailyActivitySchema),
|
||||
recentSessions: z.array(recentSessionSchema)
|
||||
});
|
||||
export type StateHistoryStats = z.infer<typeof stateHistoryStatsSchema>;
|
||||
|
||||
export const stateHistoryStatsFilterSchema = z.object({
|
||||
startDate: z.string().min(10, 'Start date is required'),
|
||||
endDate: z.string().min(10, 'End date is required')
|
||||
});
|
||||
|
||||
export type StateHistoryStatsFilter = z.infer<typeof stateHistoryStatsFilterSchema>;
|
||||
69
src/lib/schemas/user.ts
Normal file
69
src/lib/schemas/user.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import * as z from 'zod';
|
||||
|
||||
export const permissionSchema = z.object({
|
||||
id: z.uuid(),
|
||||
name: z.string()
|
||||
});
|
||||
|
||||
export type Permission = z.infer<typeof permissionSchema>;
|
||||
|
||||
export const roleSchema = z.object({
|
||||
id: z.uuid(),
|
||||
name: z.string(),
|
||||
permissions: z.array(permissionSchema)
|
||||
});
|
||||
|
||||
export type Role = z.infer<typeof roleSchema>;
|
||||
|
||||
export const userSchema = z.object({
|
||||
id: z.uuid(),
|
||||
username: z.string(),
|
||||
role_id: z.uuid(),
|
||||
role: roleSchema
|
||||
});
|
||||
|
||||
export type User = z.infer<typeof userSchema>;
|
||||
|
||||
export const userCreateSchema = z.object({
|
||||
username: z
|
||||
.string()
|
||||
.min(1, 'Username is required')
|
||||
.max(50, 'Username must be at most 50 characters'),
|
||||
password: z
|
||||
.string()
|
||||
.min(6, 'Password must be at least 6 characters')
|
||||
.max(100, 'Password must be at most 100 characters'),
|
||||
role: z.string().min(1, 'Role is required')
|
||||
});
|
||||
|
||||
export type UserCreate = z.infer<typeof userCreateSchema>;
|
||||
|
||||
export const loginSchema = z.object({
|
||||
username: z.string().min(1, 'Username is required'),
|
||||
password: z.string().min(1, 'Password is required')
|
||||
});
|
||||
|
||||
export type Login = z.infer<typeof loginSchema>;
|
||||
|
||||
export const loginTokenSchema = z.object({
|
||||
token: z.string().min(1)
|
||||
});
|
||||
|
||||
export type LoginTokenResponse = z.infer<typeof loginTokenSchema>;
|
||||
|
||||
export const loginResponseSchema = loginTokenSchema.extend({
|
||||
user: userSchema
|
||||
});
|
||||
|
||||
export type LoginResponse = z.infer<typeof loginResponseSchema>;
|
||||
|
||||
export function hasPermission(user: User | null, permission: string): boolean {
|
||||
if (!user || !user.role || !user.role.permissions) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (user.role.name === 'Super Admin') {
|
||||
return true;
|
||||
}
|
||||
return user.role.permissions.some((p) => p.name === permission);
|
||||
}
|
||||
87
src/lib/schemas/websocket.ts
Normal file
87
src/lib/schemas/websocket.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import * as z from 'zod';
|
||||
|
||||
// Step data schema
|
||||
export const stepDataSchema = z.object({
|
||||
step: z.enum([
|
||||
'validation',
|
||||
'directory_creation',
|
||||
'steam_download',
|
||||
'config_generation',
|
||||
'service_creation',
|
||||
'firewall_rules',
|
||||
'database_save',
|
||||
'completed'
|
||||
]),
|
||||
status: z.enum(['pending', 'in_progress', 'completed', 'failed']),
|
||||
message: z.string(),
|
||||
error: z.string()
|
||||
});
|
||||
|
||||
export type StepData = z.infer<typeof stepDataSchema>;
|
||||
|
||||
// Steam output data schema
|
||||
export const steamOutputDataSchema = z.object({
|
||||
output: z.string(),
|
||||
is_error: z.boolean()
|
||||
});
|
||||
|
||||
export type SteamOutputData = z.infer<typeof steamOutputDataSchema>;
|
||||
|
||||
// Error data schema
|
||||
export const errorDataSchema = z.object({
|
||||
error: z.string(),
|
||||
details: z.string()
|
||||
});
|
||||
|
||||
export type ErrorData = z.infer<typeof errorDataSchema>;
|
||||
|
||||
// Complete data schema
|
||||
export const completeDataSchema = z.object({
|
||||
server_id: z.string(),
|
||||
success: z.boolean(),
|
||||
message: z.string()
|
||||
});
|
||||
|
||||
export type CompleteData = z.infer<typeof completeDataSchema>;
|
||||
|
||||
// WebSocket message schema using discriminated union
|
||||
export const webSocketMessageSchema = z.discriminatedUnion('type', [
|
||||
z.object({
|
||||
type: z.literal('step'),
|
||||
server_id: z.string(),
|
||||
timestamp: z.number(),
|
||||
data: stepDataSchema
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal('steam_output'),
|
||||
server_id: z.string(),
|
||||
timestamp: z.number(),
|
||||
data: steamOutputDataSchema
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal('error'),
|
||||
server_id: z.string(),
|
||||
timestamp: z.number(),
|
||||
data: errorDataSchema
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal('complete'),
|
||||
server_id: z.string(),
|
||||
timestamp: z.number(),
|
||||
data: completeDataSchema
|
||||
})
|
||||
]);
|
||||
|
||||
export type WebSocketMessage = z.infer<typeof webSocketMessageSchema>;
|
||||
|
||||
// Connection status schema
|
||||
export const connectionStatusSchema = z.enum(['connecting', 'connected', 'disconnected', 'error']);
|
||||
|
||||
export type ConnectionStatus = z.infer<typeof connectionStatusSchema>;
|
||||
|
||||
// Handler types (these remain as types since they're function signatures)
|
||||
export type MessageHandler = (message: WebSocketMessage) => void;
|
||||
export type ConnectionStatusHandler = (
|
||||
status: ConnectionStatus,
|
||||
error?: string
|
||||
) => void;
|
||||
@@ -1,5 +1,5 @@
|
||||
import { SessionOptions } from 'iron-session';
|
||||
import { User } from '@/lib/types';
|
||||
import { User } from '@/lib/schemas';
|
||||
|
||||
export interface SessionData {
|
||||
token?: string;
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
export enum ConfigFile {
|
||||
configuration = 'configuration.json',
|
||||
assistRules = 'assistRules.json',
|
||||
event = 'event.json',
|
||||
eventRules = 'eventRules.json',
|
||||
settings = 'settings.json'
|
||||
}
|
||||
|
||||
export enum ServerTab {
|
||||
statistics = 'statistics',
|
||||
configuration = 'configuration',
|
||||
assistRules = 'assistRules',
|
||||
event = 'event',
|
||||
eventRules = 'eventRules',
|
||||
settings = 'settings'
|
||||
}
|
||||
|
||||
export interface Configuration {
|
||||
udpPort: number;
|
||||
tcpPort: number;
|
||||
maxConnections: number;
|
||||
lanDiscovery: number;
|
||||
registerToLobby: number;
|
||||
configVersion: number;
|
||||
}
|
||||
|
||||
export interface AssistRules {
|
||||
stabilityControlLevelMax: number;
|
||||
disableAutosteer: number;
|
||||
disableAutoLights: number;
|
||||
disableAutoWiper: number;
|
||||
disableAutoEngineStart: number;
|
||||
disableAutoPitLimiter: number;
|
||||
disableAutoGear: number;
|
||||
disableAutoClutch: number;
|
||||
disableIdealLine: number;
|
||||
}
|
||||
|
||||
export interface ServerSettings {
|
||||
serverName: string;
|
||||
adminPassword: string;
|
||||
carGroup: string;
|
||||
trackMedalsRequirement: number;
|
||||
safetyRatingRequirement: number;
|
||||
racecraftRatingRequirement: number;
|
||||
password: string;
|
||||
spectatorPassword: string;
|
||||
maxCarSlots: number;
|
||||
dumpLeaderboards: number;
|
||||
isRaceLocked: number;
|
||||
randomizeTrackWhenEmpty: number;
|
||||
centralEntryListPath: string;
|
||||
allowAutoDQ: number;
|
||||
shortFormationLap: number;
|
||||
formationLapType: number;
|
||||
ignorePrematureDisconnects: number;
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
hourOfDay: number;
|
||||
dayOfWeekend: number;
|
||||
timeMultiplier: number;
|
||||
sessionType: string;
|
||||
sessionDurationMinutes: number;
|
||||
}
|
||||
|
||||
export interface EventConfig {
|
||||
track: string;
|
||||
preRaceWaitingTimeSeconds: number;
|
||||
sessionOverTimeSeconds: number;
|
||||
ambientTemp: number;
|
||||
cloudLevel: number;
|
||||
rain: number;
|
||||
weatherRandomness: number;
|
||||
postQualySeconds: number;
|
||||
postRaceSeconds: number;
|
||||
simracerWeatherConditions: number;
|
||||
isFixedConditionQualification: number;
|
||||
sessions: Session[];
|
||||
}
|
||||
|
||||
export interface EventRules {
|
||||
qualifyStandingType: number;
|
||||
pitWindowLengthSec: number;
|
||||
driverStintTimeSec: number;
|
||||
mandatoryPitstopCount: number;
|
||||
maxTotalDrivingTime: number;
|
||||
isRefuellingAllowedInRace: boolean;
|
||||
isRefuellingTimeFixed: boolean;
|
||||
isMandatoryPitstopRefuellingRequired: boolean;
|
||||
isMandatoryPitstopTyreChangeRequired: boolean;
|
||||
isMandatoryPitstopSwapDriverRequired: boolean;
|
||||
tyreSetCount: number;
|
||||
}
|
||||
|
||||
export interface Configurations {
|
||||
configuration: Configuration;
|
||||
assistRules: AssistRules;
|
||||
event: EventConfig;
|
||||
eventRules: EventRules;
|
||||
settings: ServerSettings;
|
||||
}
|
||||
|
||||
export type Config = Configuration | AssistRules | EventConfig | EventRules | ServerSettings;
|
||||
@@ -1,25 +0,0 @@
|
||||
export interface Track {
|
||||
track: string;
|
||||
uniquePitBoxes: number;
|
||||
privateServerSlots: number;
|
||||
}
|
||||
|
||||
export interface CarModel {
|
||||
value: number;
|
||||
carModel: string;
|
||||
}
|
||||
|
||||
export interface DriverCategory {
|
||||
value: number;
|
||||
category: string;
|
||||
}
|
||||
|
||||
export interface CupCategory {
|
||||
value: number;
|
||||
category: string;
|
||||
}
|
||||
|
||||
export interface SessionType {
|
||||
value: number;
|
||||
sessionType: string;
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
export interface StateHistory {
|
||||
dateCreated: string;
|
||||
sessionStart: string;
|
||||
playerCount: number;
|
||||
track: string;
|
||||
sessionDurationMinutes: number;
|
||||
session: string;
|
||||
}
|
||||
|
||||
interface SessionCount {
|
||||
name: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface DailyActivity {
|
||||
date: string;
|
||||
sessionsCount: number;
|
||||
}
|
||||
|
||||
interface PlayerCountPoint {
|
||||
timestamp: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface RecentSession {
|
||||
id: number;
|
||||
date: string;
|
||||
type: string;
|
||||
track: string;
|
||||
duration: number;
|
||||
players: number;
|
||||
}
|
||||
|
||||
export interface StateHistoryStats {
|
||||
averagePlayers: number;
|
||||
peakPlayers: number;
|
||||
totalSessions: number;
|
||||
totalPlaytime: number;
|
||||
playerCountOverTime: PlayerCountPoint[];
|
||||
sessionTypes: SessionCount[];
|
||||
dailyActivity: DailyActivity[];
|
||||
recentSessions: RecentSession[];
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
export interface Permission {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Role {
|
||||
id: string;
|
||||
name: string;
|
||||
permissions: Permission[];
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
role_id: string;
|
||||
role: Role;
|
||||
}
|
||||
|
||||
export function hasPermission(user: User | null, permission: string): boolean {
|
||||
if (!user || !user.role || !user.role.permissions) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (user.role.name === 'Super Admin') {
|
||||
return true;
|
||||
}
|
||||
return user.role.permissions.some((p) => p.name === permission);
|
||||
}
|
||||
@@ -4,3 +4,11 @@ import { twMerge } from 'tailwind-merge';
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export function boolToInt(val: boolean) {
|
||||
return val ? 1 : 0;
|
||||
}
|
||||
|
||||
export function intToBool(val: number) {
|
||||
return !!val
|
||||
}
|
||||
|
||||
@@ -1,46 +1,9 @@
|
||||
export interface WebSocketMessage {
|
||||
type: 'step' | 'steam_output' | 'error' | 'complete';
|
||||
server_id: string;
|
||||
timestamp: number;
|
||||
data: StepData | SteamOutputData | ErrorData | CompleteData;
|
||||
}
|
||||
|
||||
export interface StepData {
|
||||
step:
|
||||
| 'validation'
|
||||
| 'directory_creation'
|
||||
| 'steam_download'
|
||||
| 'config_generation'
|
||||
| 'service_creation'
|
||||
| 'firewall_rules'
|
||||
| 'database_save'
|
||||
| 'completed';
|
||||
status: 'pending' | 'in_progress' | 'completed' | 'failed';
|
||||
message: string;
|
||||
error: string;
|
||||
}
|
||||
|
||||
export interface SteamOutputData {
|
||||
output: string;
|
||||
is_error: boolean;
|
||||
}
|
||||
|
||||
export interface ErrorData {
|
||||
error: string;
|
||||
details: string;
|
||||
}
|
||||
|
||||
export interface CompleteData {
|
||||
server_id: string;
|
||||
success: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export type MessageHandler = (message: WebSocketMessage) => void;
|
||||
export type ConnectionStatusHandler = (
|
||||
status: 'connecting' | 'connected' | 'disconnected' | 'error',
|
||||
error?: string
|
||||
) => void;
|
||||
import {
|
||||
webSocketMessageSchema,
|
||||
type WebSocketMessage,
|
||||
type MessageHandler,
|
||||
type ConnectionStatusHandler
|
||||
} from '@/lib/schemas/websocket';
|
||||
|
||||
export class WebSocketClient {
|
||||
private ws: WebSocket | null = null;
|
||||
@@ -89,7 +52,8 @@ export class WebSocketClient {
|
||||
|
||||
this.ws.onmessage = (event) => {
|
||||
try {
|
||||
const message: WebSocketMessage = JSON.parse(event.data);
|
||||
const rawMessage: WebSocketMessage = JSON.parse(event.data);
|
||||
const message = webSocketMessageSchema.parse(rawMessage);
|
||||
this.messageHandlers.forEach((handler) => handler(message));
|
||||
} catch (error) {
|
||||
console.error('Failed to parse WebSocket message:', error);
|
||||
|
||||
7
src/lib/websocket/config.ts
Normal file
7
src/lib/websocket/config.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export interface WebsocketOptions {
|
||||
url: string;
|
||||
}
|
||||
|
||||
export const websocketOptions: WebsocketOptions = {
|
||||
url: process.env.NEXT_PUBLIC_WEBSOCKET_URL || 'ws://localhost:3000/ws'
|
||||
};
|
||||
@@ -1,7 +1,17 @@
|
||||
'use client';
|
||||
|
||||
import { createContext, useContext, useEffect, useState, ReactNode, useCallback } from 'react';
|
||||
import { WebSocketClient, MessageHandler, ConnectionStatusHandler } from './client';
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
ReactNode,
|
||||
useCallback,
|
||||
useRef
|
||||
} from 'react';
|
||||
import { WebSocketClient } from './client';
|
||||
import { websocketOptions } from './config';
|
||||
import type { ConnectionStatusHandler, MessageHandler } from '../schemas/websocket';
|
||||
|
||||
interface WebSocketContextType {
|
||||
client: WebSocketClient | null;
|
||||
@@ -30,10 +40,10 @@ export function useWebSocket() {
|
||||
|
||||
interface WebSocketProviderProps {
|
||||
children: ReactNode;
|
||||
websocketURL: string;
|
||||
openToken: string;
|
||||
}
|
||||
|
||||
export function WebSocketProvider({ children, websocketURL }: WebSocketProviderProps) {
|
||||
export function WebSocketProvider({ children, openToken }: WebSocketProviderProps) {
|
||||
const [client, setClient] = useState<WebSocketClient | null>(null);
|
||||
const [isConnected, setIsConnected] = useState(false);
|
||||
const [connectionStatus, setConnectionStatus] = useState<
|
||||
@@ -51,7 +61,7 @@ export function WebSocketProvider({ children, websocketURL }: WebSocketProviderP
|
||||
client.disconnect();
|
||||
}
|
||||
|
||||
const newClient = new WebSocketClient(token, websocketURL);
|
||||
const newClient = new WebSocketClient(token, websocketOptions.url);
|
||||
|
||||
const statusHandler: ConnectionStatusHandler = (status, error) => {
|
||||
setConnectionStatus(status);
|
||||
@@ -82,7 +92,7 @@ export function WebSocketProvider({ children, websocketURL }: WebSocketProviderP
|
||||
}
|
||||
}, [client]);
|
||||
|
||||
const reconnect = async () => {
|
||||
const reconnect = useCallback(async () => {
|
||||
if (client) {
|
||||
try {
|
||||
await client.reconnect();
|
||||
@@ -91,37 +101,60 @@ export function WebSocketProvider({ children, websocketURL }: WebSocketProviderP
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [client]);
|
||||
const hasInitialized = useRef(false);
|
||||
|
||||
const associateWithServer = (serverId: string) => {
|
||||
if (client && isConnected) {
|
||||
client.associateWithServer(serverId);
|
||||
}
|
||||
};
|
||||
const associateWithServer = useCallback(
|
||||
(serverId: string) => {
|
||||
if (openToken && !isConnected && !hasInitialized.current) {
|
||||
hasInitialized.current = true;
|
||||
connect(openToken).catch((error) => {
|
||||
console.error('Failed to connect WebSocket:', error);
|
||||
hasInitialized.current = false;
|
||||
});
|
||||
}
|
||||
if (client && isConnected) {
|
||||
client.associateWithServer(serverId);
|
||||
}
|
||||
},
|
||||
[client, isConnected, connect]
|
||||
);
|
||||
|
||||
const addMessageHandler = (handler: MessageHandler) => {
|
||||
if (client) {
|
||||
client.addMessageHandler(handler);
|
||||
}
|
||||
};
|
||||
const addMessageHandler = useCallback(
|
||||
(handler: MessageHandler) => {
|
||||
if (client) {
|
||||
client.addMessageHandler(handler);
|
||||
}
|
||||
},
|
||||
[client]
|
||||
);
|
||||
|
||||
const removeMessageHandler = (handler: MessageHandler) => {
|
||||
if (client) {
|
||||
client.removeMessageHandler(handler);
|
||||
}
|
||||
};
|
||||
const removeMessageHandler = useCallback(
|
||||
(handler: MessageHandler) => {
|
||||
if (client) {
|
||||
client.removeMessageHandler(handler);
|
||||
}
|
||||
},
|
||||
[client]
|
||||
);
|
||||
|
||||
const addConnectionStatusHandler = (handler: ConnectionStatusHandler) => {
|
||||
if (client) {
|
||||
client.addConnectionStatusHandler(handler);
|
||||
}
|
||||
};
|
||||
const addConnectionStatusHandler = useCallback(
|
||||
(handler: ConnectionStatusHandler) => {
|
||||
if (client) {
|
||||
client.addConnectionStatusHandler(handler);
|
||||
}
|
||||
},
|
||||
[client]
|
||||
);
|
||||
|
||||
const removeConnectionStatusHandler = (handler: ConnectionStatusHandler) => {
|
||||
if (client) {
|
||||
client.removeConnectionStatusHandler(handler);
|
||||
}
|
||||
};
|
||||
const removeConnectionStatusHandler = useCallback(
|
||||
(handler: ConnectionStatusHandler) => {
|
||||
if (client) {
|
||||
client.removeConnectionStatusHandler(handler);
|
||||
}
|
||||
},
|
||||
[client]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
|
||||
Reference in New Issue
Block a user