8 Commits

18 changed files with 897 additions and 12 deletions

View File

@@ -4,6 +4,7 @@ import { getServerConfigurations } from '@/lib/api/server/configuration';
import { ServerConfigurationTabs } from '@/components/server/ServerConfigurationTabs'; import { ServerConfigurationTabs } from '@/components/server/ServerConfigurationTabs';
import { ServerHeader } from '@/components/server/ServerHeader'; import { ServerHeader } from '@/components/server/ServerHeader';
import { getServerStatistics } from '@/lib/api/server/statistics'; import { getServerStatistics } from '@/lib/api/server/statistics';
import { getLeaderboard } from '@/lib/api/server/leaderboard';
import { subDays, formatISO } from 'date-fns'; import { subDays, formatISO } from 'date-fns';
import { UTCDate } from '@date-fns/utc'; import { UTCDate } from '@date-fns/utc';
@@ -19,10 +20,11 @@ export default async function ServerPage({ params }: ServerPageProps) {
const endDate = formatISO(today); const endDate = formatISO(today);
const startDate = formatISO(subDays(today, 30)); 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), getServer(session.token!, id),
getServerConfigurations(session.token!, id), getServerConfigurations(session.token!, id),
getServerStatistics(session.token!, id, { startDate, endDate }) getServerStatistics(session.token!, id, { startDate, endDate }),
getLeaderboard(session.token!, id)
]); ]);
return ( return (
@@ -35,6 +37,7 @@ export default async function ServerPage({ params }: ServerPageProps) {
serverId={id} serverId={id}
configurations={configurations} configurations={configurations}
statistics={statistics} statistics={statistics}
leaderboard={leaderboard}
/> />
</div> </div>
</div> </div>

View File

@@ -113,22 +113,29 @@ export function EventConfigEditor({ serverId, config }: EventConfigEditorProps)
> >
<option value="barcelona">Barcelona</option> <option value="barcelona">Barcelona</option>
<option value="brands_hatch">Brands Hatch</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="hungaroring">Hungaroring</option>
<option value="imola">Imola</option> <option value="imola">Imola</option>
<option value="indianapolis">Indianapolis</option>
<option value="kyalami">Kyalami</option> <option value="kyalami">Kyalami</option>
<option value="laguna_seca">Laguna Seca</option> <option value="laguna_seca">Laguna Seca</option>
<option value="misano">Misano</option> <option value="misano">Misano</option>
<option value="monza">Monza</option> <option value="monza">Monza</option>
<option value="mount_panorama">Mount Panorama</option> <option value="mount_panorama">Mount Panorama</option>
<option value="nurburgring">Nurburgring</option> <option value="nurburgring">Nurburgring</option>
<option value="nurburgring_24h">Nurburgring 24h</option>
<option value="oulton_park">Oulton Park</option> <option value="oulton_park">Oulton Park</option>
<option value="paul_ricard">Paul Ricard</option> <option value="paul_ricard">Paul Ricard</option>
<option value="red_bull_ring">Red Bull Ring</option>
<option value="silverstone">Silverstone</option> <option value="silverstone">Silverstone</option>
<option value="snetterton">Snetterton</option> <option value="snetterton">Snetterton</option>
<option value="spa">Spa-Francorchamps</option> <option value="spa">Spa-Francorchamps</option>
<option value="suzuka">Suzuka</option> <option value="suzuka">Suzuka</option>
<option value="valencia">Valencia</option>
<option value="zandvoort">Zandvoort</option> <option value="zandvoort">Zandvoort</option>
<option value="zolder">Zolder</option> <option value="zolder">Zolder</option>
<option value="watkins_glen">Watkins Glen</option>
</select> </select>
</div> </div>

View 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>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View 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>
);
}

View File

@@ -7,13 +7,16 @@ import { EventConfigEditor } from '@/components/configuration/EventConfigEditor'
import { EventRulesEditor } from '@/components/configuration/EventRulesEditor'; import { EventRulesEditor } from '@/components/configuration/EventRulesEditor';
import { ServerSettingsEditor } from '@/components/configuration/ServerSettingsEditor'; import { ServerSettingsEditor } from '@/components/configuration/ServerSettingsEditor';
import { StatisticsDashboard } from '@/components/statistics/StatisticsDashboard'; import { StatisticsDashboard } from '@/components/statistics/StatisticsDashboard';
import { LeaderboardManager } from '@/components/leaderboard/LeaderboardManager';
import { useState } from 'react'; import { useState } from 'react';
import { StateHistoryStats } from '@/lib/schemas'; import { StateHistoryStats } from '@/lib/schemas';
import { Leaderboard } from '@/lib/schemas/leaderboard';
interface ServerConfigurationTabsProps { interface ServerConfigurationTabsProps {
serverId: string; serverId: string;
configurations: Configurations; configurations: Configurations;
statistics: StateHistoryStats; statistics: StateHistoryStats;
leaderboard: Leaderboard;
} }
const tabs = [ const tabs = [
{ id: ServerTab.statistics, name: 'Statistics', icon: '📊' }, { id: ServerTab.statistics, name: 'Statistics', icon: '📊' },
@@ -21,13 +24,15 @@ const tabs = [
{ id: ServerTab.assistRules, name: 'Assist Rules', icon: '🚗' }, { id: ServerTab.assistRules, name: 'Assist Rules', icon: '🚗' },
{ id: ServerTab.event, name: 'Event Config', icon: '🏁' }, { id: ServerTab.event, name: 'Event Config', icon: '🏁' },
{ id: ServerTab.eventRules, name: 'Event Rules', icon: '📋' }, { id: ServerTab.eventRules, name: 'Event Rules', icon: '📋' },
{ id: ServerTab.settings, name: 'Server Settings', icon: '🔧' } { id: ServerTab.settings, name: 'Server Settings', icon: '🔧' },
{ id: ServerTab.leaderboard, name: 'Leaderboard', icon: '🏆' }
]; ];
export function ServerConfigurationTabs({ export function ServerConfigurationTabs({
serverId, serverId,
configurations, configurations,
statistics statistics,
leaderboard
}: ServerConfigurationTabsProps) { }: ServerConfigurationTabsProps) {
const [currentTab, setCurrentTab] = useState(ServerTab.statistics); const [currentTab, setCurrentTab] = useState(ServerTab.statistics);
@@ -51,6 +56,9 @@ export function ServerConfigurationTabs({
case ServerTab.settings: case ServerTab.settings:
return <ServerSettingsEditor serverId={serverId} config={configurations.settings} />; return <ServerSettingsEditor serverId={serverId} config={configurations.settings} />;
case ServerTab.leaderboard:
return <LeaderboardManager serverId={serverId} initialData={leaderboard} />;
default: default:
return ( return (
<div className="py-12 text-center"> <div className="py-12 text-center">

View File

@@ -1,5 +1,5 @@
interface RecentSession { interface RecentSession {
id: number; id: string;
date: string; date: string;
type: string; type: string;
track: string; track: string;

View File

@@ -17,6 +17,7 @@ import type {
EventRules, EventRules,
ServerSettings ServerSettings
} from '@/lib/schemas/config'; } from '@/lib/schemas/config';
import { boolToInt } from '@/lib/utils';
export async function updateConfigurationAction(serverId: string, formData: FormData) { export async function updateConfigurationAction(serverId: string, formData: FormData) {
try { try {
@@ -198,14 +199,14 @@ export async function updateEventRulesAction(serverId: string, formData: FormDat
driverStintTimeSec: parseInt(formData.get('driverStintTimeSec') as string), driverStintTimeSec: parseInt(formData.get('driverStintTimeSec') as string),
mandatoryPitstopCount: parseInt(formData.get('mandatoryPitstopCount') as string), mandatoryPitstopCount: parseInt(formData.get('mandatoryPitstopCount') as string),
maxTotalDrivingTime: parseInt(formData.get('maxTotalDrivingTime') as string), maxTotalDrivingTime: parseInt(formData.get('maxTotalDrivingTime') as string),
isRefuellingAllowedInRace: formData.get('isRefuellingAllowedInRace') === 'true', isRefuellingAllowedInRace: boolToInt(formData.get('isRefuellingAllowedInRace') === 'true'),
isRefuellingTimeFixed: formData.get('isRefuellingTimeFixed') === 'true', isRefuellingTimeFixed: boolToInt(formData.get('isRefuellingTimeFixed') === 'true'),
isMandatoryPitstopRefuellingRequired: isMandatoryPitstopRefuellingRequired:
formData.get('isMandatoryPitstopRefuellingRequired') === 'true', boolToInt(formData.get('isMandatoryPitstopRefuellingRequired') === 'true'),
isMandatoryPitstopTyreChangeRequired: isMandatoryPitstopTyreChangeRequired:
formData.get('isMandatoryPitstopTyreChangeRequired') === 'true', boolToInt(formData.get('isMandatoryPitstopTyreChangeRequired') === 'true'),
isMandatoryPitstopSwapDriverRequired: isMandatoryPitstopSwapDriverRequired:
formData.get('isMandatoryPitstopSwapDriverRequired') === 'true', boolToInt(formData.get('isMandatoryPitstopSwapDriverRequired') === 'true'),
tyreSetCount: parseInt(formData.get('tyreSetCount') as string) tyreSetCount: parseInt(formData.get('tyreSetCount') as string)
}; };

View 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'
};
}
}

View 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;
}

View File

@@ -15,7 +15,8 @@ export enum ServerTab {
assistRules = 'assistRules', assistRules = 'assistRules',
event = 'event', event = 'event',
eventRules = 'eventRules', eventRules = 'eventRules',
settings = 'settings' settings = 'settings',
leaderboard = 'leaderboard'
} }
export const serverTabSchema = z.enum(ServerTab); export const serverTabSchema = z.enum(ServerTab);

View File

@@ -3,3 +3,4 @@ export * from './user';
export * from './config'; export * from './config';
export * from './statistics'; export * from './statistics';
export * from './lookups'; export * from './lookups';
export * from './leaderboard';

View 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;
};

View File

@@ -57,7 +57,7 @@ export const serverSchema = z.object({
id: z.uuid(), id: z.uuid(),
name: z.string().min(1), name: z.string().min(1),
status: z.enum(ServiceStatus), status: z.enum(ServiceStatus),
state: stateSchema.optional() state: stateSchema.optional().nullable()
}); });
export type Server = z.infer<typeof serverSchema>; export type Server = z.infer<typeof serverSchema>;

View File

@@ -4,3 +4,11 @@ import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)); return twMerge(clsx(inputs));
} }
export function boolToInt(val: boolean) {
return val ? 1 : 0;
}
export function intToBool(val: number) {
return !!val
}