This commit is contained in:
2025-12-09 10:32:59 +01:00
parent 35f988f885
commit a780139692
26 changed files with 2224 additions and 344 deletions

View File

@@ -334,7 +334,7 @@ export default function LeagueDetailPage() {
</h4>
<p className="text-gray-200 flex items-center gap-1.5">
<Trophy className="w-4 h-4 text-gray-500" />
{league.settings.pointsSystem.toUpperCase()}
{scoringConfig?.scoringPresetName ?? scoringConfig?.scoringPresetId ?? 'Standard'}
</p>
</div>
<div>

View File

@@ -3,6 +3,7 @@
import { useState, useEffect } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import {
User,
Trophy,
@@ -352,10 +353,14 @@ function FinishDistributionChart({ wins, podiums, topTen, total }: FinishDistrib
// ============================================================================
export default function ProfilePage() {
const router = useRouter();
const searchParams = useSearchParams();
const tabParam = searchParams.get('tab') as ProfileTab | null;
const [driver, setDriver] = useState<DriverDTO | null>(null);
const [loading, setLoading] = useState(true);
const [editMode, setEditMode] = useState(false);
const [activeTab, setActiveTab] = useState<ProfileTab>('overview');
const [activeTab, setActiveTab] = useState<ProfileTab>(tabParam || 'overview');
const [teamData, setTeamData] = useState<GetDriverTeamQueryResultDTO | null>(null);
const [allTeamMemberships, setAllTeamMemberships] = useState<TeamMembershipInfo[]>([]);
const [friends, setFriends] = useState<Driver[]>([]);
@@ -413,6 +418,27 @@ export default function ProfilePage() {
void loadData();
}, [effectiveDriverId]);
// Update URL when tab changes
useEffect(() => {
if (tabParam !== activeTab) {
const params = new URLSearchParams(searchParams.toString());
if (activeTab === 'overview') {
params.delete('tab');
} else {
params.set('tab', activeTab);
}
const query = params.toString();
router.replace(`/profile${query ? `?${query}` : ''}`, { scroll: false });
}
}, [activeTab, tabParam, searchParams, router]);
// Sync tab from URL on mount and param change
useEffect(() => {
if (tabParam && tabParam !== activeTab) {
setActiveTab(tabParam);
}
}, [tabParam]);
const handleSaveSettings = async (updates: Partial<DriverDTO>) => {
if (!driver) return;
@@ -497,7 +523,7 @@ export default function ProfilePage() {
}
return (
<div className="max-w-6xl mx-auto px-4 pb-12 space-y-6">
<div className="max-w-7xl mx-auto px-4 pb-12 space-y-6">
{/* Hero Header Section */}
<div className="relative rounded-2xl overflow-hidden bg-gradient-to-br from-iron-gray/80 via-iron-gray/60 to-deep-graphite border border-charcoal-outline">
{/* Background Pattern */}
@@ -1000,13 +1026,13 @@ export default function ProfilePage() {
</>
)}
{activeTab === 'history' && (
{activeTab === 'history' && driver && (
<Card>
<h2 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<History className="w-5 h-5 text-red-400" />
Race History
</h2>
<ProfileRaceHistory />
<ProfileRaceHistory driverId={driver.id} />
</Card>
)}

View File

@@ -7,9 +7,11 @@ import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import Heading from '@/components/ui/Heading';
import Breadcrumbs from '@/components/layout/Breadcrumbs';
import FileProtestModal from '@/components/races/FileProtestModal';
import type { Race } from '@gridpilot/racing/domain/entities/Race';
import type { League } from '@gridpilot/racing/domain/entities/League';
import type { Driver } from '@gridpilot/racing/domain/entities/Driver';
import type { Result } from '@gridpilot/racing/domain/entities/Result';
import {
getRaceRepository,
getLeagueRepository,
@@ -18,12 +20,13 @@ import {
getIsDriverRegisteredForRaceQuery,
getRegisterForRaceUseCase,
getWithdrawFromRaceUseCase,
getTrackRepository,
getCarRepository,
getGetRaceWithSOFQuery,
getResultRepository,
getImageService,
} from '@/lib/di-container';
import { getMembership } from '@/lib/leagueMembership';
import { useEffectiveDriverId } from '@/lib/currentDriver';
import { getDriverStats } from '@/lib/di-container';
import {
Calendar,
Clock,
@@ -45,8 +48,9 @@ import {
ArrowLeft,
ExternalLink,
Award,
Scale,
} from 'lucide-react';
import { getDriverStats, getAllDriverRankings } from '@/lib/di-container';
import { getAllDriverRankings } from '@/lib/di-container';
export default function RaceDetailPage() {
const router = useRouter();
@@ -63,6 +67,10 @@ export default function RaceDetailPage() {
const [isUserRegistered, setIsUserRegistered] = useState(false);
const [canRegister, setCanRegister] = useState(false);
const [raceSOF, setRaceSOF] = useState<number | null>(null);
const [userResult, setUserResult] = useState<Result | null>(null);
const [ratingChange, setRatingChange] = useState<number | null>(null);
const [animatedRatingChange, setAnimatedRatingChange] = useState(0);
const [showProtestModal, setShowProtestModal] = useState(false);
const currentDriverId = useEffectiveDriverId();
@@ -94,6 +102,26 @@ export default function RaceDetailPage() {
// Load entry list
await loadEntryList(raceData.id, raceData.leagueId);
// Load user's result if race is completed
if (raceData.status === 'completed') {
const resultRepo = getResultRepository();
const results = await resultRepo.findByRaceId(raceData.id);
const result = results.find(r => r.driverId === currentDriverId);
setUserResult(result || null);
// Get rating change from driver stats (mock based on position)
if (result) {
const stats = getDriverStats(currentDriverId);
if (stats) {
// Calculate rating change based on position - simplified domain logic
const baseChange = result.position <= 3 ? 25 : result.position <= 10 ? 10 : -5;
const positionBonus = Math.max(0, (20 - result.position) * 2);
const change = baseChange + positionBonus;
setRatingChange(change);
}
}
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load race');
} finally {
@@ -134,6 +162,31 @@ export default function RaceDetailPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [raceId]);
// Animate rating change when it changes
useEffect(() => {
if (ratingChange !== null) {
let start = 0;
const end = ratingChange;
const duration = 1000;
const startTime = performance.now();
const animate = (currentTime: number) => {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
// Ease out cubic
const eased = 1 - Math.pow(1 - progress, 3);
const current = Math.round(start + (end - start) * eased);
setAnimatedRatingChange(current);
if (progress < 1) {
requestAnimationFrame(animate);
}
};
requestAnimationFrame(animate);
}
}, [ratingChange]);
const handleCancelRace = async () => {
if (!race || race.status !== 'scheduled') return;
@@ -329,6 +382,15 @@ export default function RaceDetailPage() {
{ label: race.track },
];
// Country code to flag emoji converter
const getCountryFlag = (countryCode: string): string => {
const codePoints = countryCode
.toUpperCase()
.split('')
.map(char => 127397 + char.charCodeAt(0));
return String.fromCodePoint(...codePoints);
};
// Build driver rankings for entry list display
const getDriverRank = (driverId: string): { rating: number | null; rank: number | null } => {
const stats = getDriverStats(driverId);
@@ -348,7 +410,7 @@ export default function RaceDetailPage() {
return (
<div className="min-h-screen bg-deep-graphite py-8 px-4 sm:px-6 lg:px-8">
<div className="max-w-4xl mx-auto space-y-6">
<div className="max-w-7xl mx-auto space-y-6">
{/* Navigation Row: Breadcrumbs left, Back button right */}
<div className="flex items-center justify-between">
<Breadcrumbs items={breadcrumbItems} className="text-sm text-gray-400" />
@@ -362,6 +424,141 @@ export default function RaceDetailPage() {
</Button>
</div>
{/* User Result - Premium Achievement Card */}
{userResult && (
<div className={`
relative overflow-hidden rounded-2xl p-1
${userResult.position === 1
? 'bg-gradient-to-r from-yellow-500 via-yellow-400 to-yellow-600'
: userResult.isPodium()
? 'bg-gradient-to-r from-gray-400 via-gray-300 to-gray-500'
: 'bg-gradient-to-r from-primary-blue via-primary-blue/80 to-primary-blue'}
`}>
<div className="relative bg-deep-graphite rounded-xl p-6 sm:p-8">
{/* Decorative elements */}
<div className="absolute top-0 left-0 w-32 h-32 bg-gradient-to-br from-white/10 to-transparent rounded-full blur-2xl" />
<div className="absolute bottom-0 right-0 w-48 h-48 bg-gradient-to-tl from-white/5 to-transparent rounded-full blur-3xl" />
{/* Victory confetti effect for P1 */}
{userResult.position === 1 && (
<div className="absolute inset-0 overflow-hidden pointer-events-none">
<div className="absolute top-4 left-[10%] w-2 h-2 bg-yellow-400 rounded-full animate-pulse" />
<div className="absolute top-8 left-[25%] w-1.5 h-1.5 bg-yellow-300 rounded-full animate-pulse delay-100" />
<div className="absolute top-6 right-[20%] w-2 h-2 bg-yellow-500 rounded-full animate-pulse delay-200" />
<div className="absolute top-10 right-[35%] w-1 h-1 bg-yellow-400 rounded-full animate-pulse delay-300" />
</div>
)}
<div className="relative z-10">
{/* Main content grid */}
<div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-6">
{/* Left: Position and achievement */}
<div className="flex items-center gap-5">
{/* Giant position badge */}
<div className={`
relative flex items-center justify-center w-24 h-24 sm:w-28 sm:h-28 rounded-3xl font-black text-4xl sm:text-5xl
${userResult.position === 1
? 'bg-gradient-to-br from-yellow-400 to-yellow-600 text-deep-graphite shadow-2xl shadow-yellow-500/30'
: userResult.position === 2
? 'bg-gradient-to-br from-gray-300 to-gray-500 text-deep-graphite shadow-xl shadow-gray-400/20'
: userResult.position === 3
? 'bg-gradient-to-br from-amber-600 to-amber-800 text-white shadow-xl shadow-amber-600/20'
: 'bg-gradient-to-br from-primary-blue to-primary-blue/70 text-white shadow-xl shadow-primary-blue/20'}
`}>
{userResult.position === 1 && (
<Trophy className="absolute -top-3 -right-2 w-8 h-8 text-yellow-300 drop-shadow-lg" />
)}
<span>P{userResult.position}</span>
</div>
{/* Achievement text */}
<div>
<p className={`
text-2xl sm:text-3xl font-bold mb-1
${userResult.position === 1 ? 'text-yellow-400' :
userResult.isPodium() ? 'text-gray-300' : 'text-white'}
`}>
{userResult.position === 1 ? '🏆 VICTORY!' :
userResult.position === 2 ? '🥈 Second Place' :
userResult.position === 3 ? '🥉 Podium Finish' :
userResult.position <= 5 ? '⭐ Top 5 Finish' :
userResult.position <= 10 ? 'Points Finish' :
`P${userResult.position} Finish`}
</p>
<div className="flex items-center gap-3 text-sm text-gray-400">
<span>Started P{userResult.startPosition}</span>
<span className="w-1 h-1 rounded-full bg-gray-600" />
<span className={userResult.isClean() ? 'text-performance-green' : ''}>
{userResult.incidents}x incidents
{userResult.isClean() && ' ✨'}
</span>
</div>
</div>
</div>
{/* Right: Stats cards */}
<div className="flex flex-wrap gap-3">
{/* Position change */}
{userResult.getPositionChange() !== 0 && (
<div className={`
flex flex-col items-center px-5 py-3 rounded-2xl min-w-[100px]
${userResult.getPositionChange() > 0
? 'bg-gradient-to-br from-performance-green/30 to-performance-green/10 border border-performance-green/40'
: 'bg-gradient-to-br from-red-500/30 to-red-500/10 border border-red-500/40'}
`}>
<div className={`
flex items-center gap-1 font-black text-2xl
${userResult.getPositionChange() > 0 ? 'text-performance-green' : 'text-red-400'}
`}>
{userResult.getPositionChange() > 0 ? (
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 17a.75.75 0 01-.75-.75V5.612L5.29 9.77a.75.75 0 01-1.08-1.04l5.25-5.5a.75.75 0 011.08 0l5.25 5.5a.75.75 0 11-1.08 1.04l-3.96-4.158V16.25A.75.75 0 0110 17z" clipRule="evenodd" />
</svg>
) : (
<svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
<path fillRule="evenodd" d="M10 3a.75.75 0 01.75.75v10.638l3.96-4.158a.75.75 0 111.08 1.04l-5.25 5.5a.75.75 0 01-1.08 0l-5.25-5.5a.75.75 0 111.08-1.04l3.96 4.158V3.75A.75.75 0 0110 3z" clipRule="evenodd" />
</svg>
)}
{Math.abs(userResult.getPositionChange())}
</div>
<div className="text-xs text-gray-400 mt-0.5">
{userResult.getPositionChange() > 0 ? 'Gained' : 'Lost'}
</div>
</div>
)}
{/* Rating change */}
{ratingChange !== null && (
<div className={`
flex flex-col items-center px-5 py-3 rounded-2xl min-w-[100px]
${ratingChange > 0
? 'bg-gradient-to-br from-warning-amber/30 to-warning-amber/10 border border-warning-amber/40'
: 'bg-gradient-to-br from-red-500/30 to-red-500/10 border border-red-500/40'}
`}>
<div className={`
font-mono font-black text-2xl
${ratingChange > 0 ? 'text-warning-amber' : 'text-red-400'}
`}>
{animatedRatingChange > 0 ? '+' : ''}{animatedRatingChange}
</div>
<div className="text-xs text-gray-400 mt-0.5">iRating</div>
</div>
)}
{/* Clean race bonus */}
{userResult.isClean() && (
<div className="flex flex-col items-center px-5 py-3 rounded-2xl min-w-[100px] bg-gradient-to-br from-performance-green/30 to-performance-green/10 border border-performance-green/40">
<div className="text-2xl"></div>
<div className="text-xs text-performance-green mt-0.5 font-medium">Clean Race</div>
</div>
)}
</div>
</div>
</div>
</div>
</div>
)}
{/* Hero Header */}
<div className={`relative overflow-hidden rounded-2xl ${config.bg} border ${config.border} p-6 sm:p-8`}>
{/* Live indicator */}
@@ -407,43 +604,38 @@ export default function RaceDetailPage() {
<Car className="w-4 h-4" />
{race.car}
</span>
{raceSOF && (
<span className="flex items-center gap-2 text-warning-amber">
<Zap className="w-4 h-4" />
SOF {raceSOF}
</span>
)}
</div>
</div>
</div>
{/* League Banner */}
{league && (
<Link
href={`/leagues/${league.id}`}
className="block group"
>
<div className="relative overflow-hidden rounded-xl bg-gradient-to-r from-primary-blue/10 via-primary-blue/5 to-transparent border border-primary-blue/20 p-4 transition-all hover:border-primary-blue/40">
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<div className="p-3 bg-primary-blue/20 rounded-xl">
<Trophy className="w-6 h-6 text-primary-blue" />
{/* Prominent SOF Badge - Electric Design */}
{raceSOF && (
<div className="absolute top-6 right-6 sm:top-8 sm:right-8">
<div className="relative group">
{/* Glow effect */}
<div className="absolute inset-0 bg-warning-amber/40 rounded-2xl blur-xl group-hover:blur-2xl transition-all duration-300" />
<div className="relative flex items-center gap-4 px-6 py-4 rounded-2xl bg-gradient-to-br from-warning-amber/30 via-warning-amber/20 to-orange-500/20 border border-warning-amber/50 shadow-2xl backdrop-blur-sm">
{/* Electric bolt with animation */}
<div className="relative">
<Zap className="w-8 h-8 text-warning-amber drop-shadow-lg" />
<Zap className="absolute inset-0 w-8 h-8 text-warning-amber animate-pulse opacity-50" />
</div>
<div>
<p className="text-xs text-gray-400 uppercase tracking-wide">Part of</p>
<p className="text-lg font-semibold text-white group-hover:text-primary-blue transition-colors">
{league.name}
</p>
<div className="text-[10px] text-warning-amber/90 uppercase tracking-widest font-bold mb-0.5">
Strength of Field
</div>
<div className="flex items-baseline gap-1">
<span className="text-3xl font-black text-warning-amber font-mono tracking-tight drop-shadow-lg">
{raceSOF}
</span>
<span className="text-sm text-warning-amber/70 font-medium">SOF</span>
</div>
</div>
</div>
<div className="flex items-center gap-2 text-primary-blue">
<span className="text-sm hidden sm:block">View League</span>
<ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
</div>
</div>
</div>
</Link>
)}
)}
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Main Content */}
@@ -503,53 +695,139 @@ export default function RaceDetailPage() {
</span>
</div>
{entryList.length === 0 ? (
<div className="text-center py-8">
<div className="p-4 bg-iron-gray rounded-full inline-block mb-3">
<Users className="w-6 h-6 text-gray-500" />
{(() => {
const imageService = getImageService();
return entryList.length === 0 ? (
<div className="text-center py-8">
<div className="p-4 bg-iron-gray rounded-full inline-block mb-3">
<Users className="w-6 h-6 text-gray-500" />
</div>
<p className="text-gray-400">No drivers registered yet</p>
<p className="text-sm text-gray-500">Be the first to sign up!</p>
</div>
<p className="text-gray-400">No drivers registered yet</p>
<p className="text-sm text-gray-500">Be the first to sign up!</p>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
) : (
<div className="space-y-1">
{entryList.map((driver, index) => {
const driverRankInfo = getDriverRank(driver.id);
const isCurrentUser = driver.id === currentDriverId;
const avatarUrl = imageService.getDriverAvatar(driver.id);
const countryFlag = getCountryFlag(driver.country);
return (
<div
key={driver.id}
onClick={() => router.push(`/drivers/${driver.id}`)}
className="flex items-center gap-2 p-2 bg-deep-graphite rounded-lg hover:bg-charcoal-outline/50 cursor-pointer transition-colors"
className={`
flex items-center gap-3 p-3 rounded-xl cursor-pointer transition-all duration-200
${isCurrentUser
? 'bg-gradient-to-r from-primary-blue/20 via-primary-blue/10 to-transparent border border-primary-blue/40 shadow-lg shadow-primary-blue/10'
: 'bg-deep-graphite hover:bg-charcoal-outline/50 border border-transparent'}
`}
>
<span className="w-6 text-xs text-gray-500 font-mono">#{index + 1}</span>
<div className="w-7 h-7 bg-iron-gray rounded-full flex items-center justify-center flex-shrink-0">
<span className="text-sm font-bold text-gray-400">
{driver.name.charAt(0)}
</span>
{/* Position number */}
<div className={`
flex items-center justify-center w-8 h-8 rounded-lg font-bold text-sm
${index === 0 ? 'bg-yellow-500/20 text-yellow-400' :
index === 1 ? 'bg-gray-400/20 text-gray-300' :
index === 2 ? 'bg-amber-600/20 text-amber-500' :
'bg-iron-gray text-gray-500'}
`}>
{index + 1}
</div>
{/* Avatar with nation flag */}
<div className="relative flex-shrink-0">
<img
src={avatarUrl}
alt={driver.name}
className={`
w-10 h-10 rounded-full object-cover
${isCurrentUser ? 'ring-2 ring-primary-blue/50' : ''}
`}
/>
{/* Nation flag */}
<div className="absolute -bottom-0.5 -right-0.5 w-5 h-5 rounded-full bg-deep-graphite border-2 border-deep-graphite flex items-center justify-center text-xs shadow-sm">
{countryFlag}
</div>
</div>
{/* Driver info */}
<div className="flex-1 min-w-0">
<p className="text-white text-sm font-medium truncate">{driver.name}</p>
<div className="flex items-center gap-2">
<p className={`text-sm font-semibold truncate ${isCurrentUser ? 'text-primary-blue' : 'text-white'}`}>
{driver.name}
</p>
{isCurrentUser && (
<span className="px-2 py-0.5 text-[10px] font-bold bg-primary-blue text-white rounded-full uppercase tracking-wide">
You
</span>
)}
</div>
<p className="text-xs text-gray-500">{driver.country}</p>
</div>
{/* Rating badge */}
{driverRankInfo.rating && (
<span className="text-xs text-warning-amber font-medium">
{driverRankInfo.rating}
</span>
)}
{driver.id === currentDriverId && (
<span className="px-1.5 py-0.5 text-xs font-medium bg-primary-blue/20 text-primary-blue rounded">
You
</span>
<div className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-warning-amber/10 border border-warning-amber/20">
<Zap className="w-3 h-3 text-warning-amber" />
<span className="text-xs font-bold text-warning-amber font-mono">
{driverRankInfo.rating}
</span>
</div>
)}
</div>
);
})}
</div>
)}
);
})()}
</Card>
</div>
{/* Sidebar - Actions */}
{/* Sidebar */}
<div className="space-y-6">
{/* League Card - Premium Design */}
{league && (
<Card className="overflow-hidden">
<div className="flex items-center gap-4 mb-4">
<div className="w-14 h-14 rounded-xl overflow-hidden bg-iron-gray flex-shrink-0">
<img
src={getImageService().getLeagueLogo(league.id)}
alt={league.name}
className="w-full h-full object-cover"
/>
</div>
<div className="flex-1 min-w-0">
<p className="text-xs text-gray-500 uppercase tracking-wide mb-0.5">League</p>
<h3 className="text-white font-semibold truncate">{league.name}</h3>
</div>
</div>
{league.description && (
<p className="text-sm text-gray-400 mb-4 line-clamp-2">{league.description}</p>
)}
<div className="grid grid-cols-2 gap-3 mb-4">
<div className="p-3 rounded-lg bg-deep-graphite">
<p className="text-xs text-gray-500 mb-1">Max Drivers</p>
<p className="text-white font-medium">{league.settings.maxDrivers ?? 32}</p>
</div>
<div className="p-3 rounded-lg bg-deep-graphite">
<p className="text-xs text-gray-500 mb-1">Format</p>
<p className="text-white font-medium capitalize">{league.settings.qualifyingFormat ?? 'Open'}</p>
</div>
</div>
<Link
href={`/leagues/${league.id}`}
className="flex items-center justify-center gap-2 w-full py-2.5 rounded-lg bg-primary-blue/10 border border-primary-blue/30 text-primary-blue text-sm font-medium hover:bg-primary-blue/20 transition-colors"
>
View League
<ArrowRight className="w-4 h-4" />
</Link>
</Card>
)}
{/* Quick Actions Card */}
<Card>
<h2 className="text-lg font-semibold text-white mb-4">Actions</h2>
@@ -587,14 +865,26 @@ export default function RaceDetailPage() {
)}
{race.status === 'completed' && (
<Button
variant="primary"
className="w-full flex items-center justify-center gap-2"
onClick={() => router.push(`/races/${race.id}/results`)}
>
<Trophy className="w-4 h-4" />
View Results
</Button>
<>
<Button
variant="primary"
className="w-full flex items-center justify-center gap-2"
onClick={() => router.push(`/races/${race.id}/results`)}
>
<Trophy className="w-4 h-4" />
View Results
</Button>
{userResult && (
<Button
variant="secondary"
className="w-full flex items-center justify-center gap-2"
onClick={() => setShowProtestModal(true)}
>
<Scale className="w-4 h-4" />
File Protest
</Button>
)}
</>
)}
{race.status === 'scheduled' && (
@@ -658,6 +948,16 @@ export default function RaceDetailPage() {
</div>
</div>
</div>
{/* Protest Filing Modal */}
<FileProtestModal
isOpen={showProtestModal}
onClose={() => setShowProtestModal(false)}
raceId={race.id}
leagueId={league?.id}
protestingDriverId={currentDriverId}
participants={entryList}
/>
</div>
);
}

View File

@@ -11,6 +11,7 @@ import { Race } from '@gridpilot/racing/domain/entities/Race';
import { League } from '@gridpilot/racing/domain/entities/League';
import { Result } from '@gridpilot/racing/domain/entities/Result';
import { Driver } from '@gridpilot/racing/domain/entities/Driver';
import type { PenaltyType } from '@gridpilot/racing/domain/entities/Penalty';
import {
getRaceRepository,
getLeagueRepository,
@@ -18,7 +19,14 @@ import {
getStandingRepository,
getDriverRepository,
getGetRaceWithSOFQuery,
getGetRacePenaltiesQuery,
} from '@/lib/di-container';
interface PenaltyData {
driverId: string;
type: PenaltyType;
value?: number;
}
import { ArrowLeft, Zap, Trophy, Users, Clock, Calendar } from 'lucide-react';
export default function RaceResultsPage() {
@@ -30,7 +38,9 @@ export default function RaceResultsPage() {
const [league, setLeague] = useState<League | null>(null);
const [results, setResults] = useState<Result[]>([]);
const [drivers, setDrivers] = useState<Driver[]>([]);
const [currentDriverId, setCurrentDriverId] = useState<string | undefined>(undefined);
const [raceSOF, setRaceSOF] = useState<number | null>(null);
const [penalties, setPenalties] = useState<PenaltyData[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [importing, setImporting] = useState(false);
@@ -71,6 +81,26 @@ export default function RaceResultsPage() {
// Load drivers
const driversData = await driverRepo.findAll();
setDrivers(driversData);
// Get current driver (first driver in demo mode)
if (driversData.length > 0) {
setCurrentDriverId(driversData[0].id);
}
// Load penalties for this race
try {
const penaltiesQuery = getGetRacePenaltiesQuery();
const penaltiesData = await penaltiesQuery.execute(raceId);
// Map the DTO to the PenaltyData interface expected by ResultsTable
setPenalties(penaltiesData.map(p => ({
driverId: p.driverId,
type: p.type,
value: p.value,
})));
} catch (penaltyErr) {
console.error('Failed to load penalties:', penaltyErr);
// Don't fail the whole page if penalties fail to load
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load race data');
} finally {
@@ -268,6 +298,8 @@ export default function RaceResultsPage() {
drivers={drivers}
pointsSystem={getPointsSystem()}
fastestLapTime={getFastestLapTime()}
penalties={penalties}
currentDriverId={currentDriverId}
/>
) : (
<>

View File

@@ -1,43 +1,74 @@
'use client';
import { useState } from 'react';
import { useState, useEffect } from 'react';
import Card from '../ui/Card';
import Button from '../ui/Button';
import RaceResultCard from '../races/RaceResultCard';
import { getRaceRepository, getLeagueRepository, getResultRepository } from '@/lib/di-container';
import { Race } from '@gridpilot/racing/domain/entities/Race';
import { Result } from '@gridpilot/racing/domain/entities/Result';
import { League } from '@gridpilot/racing/domain/entities/League';
interface RaceResult {
id: string;
date: string;
track: string;
car: string;
position: number;
startPosition: number;
incidents: number;
league: string;
interface RaceHistoryProps {
driverId: string;
}
const mockRaceHistory: RaceResult[] = [
{ id: '1', date: '2024-11-28', track: 'Spa-Francorchamps', car: 'Porsche 911 GT3 R', position: 1, startPosition: 3, incidents: 0, league: 'GridPilot Championship' },
{ id: '2', date: '2024-11-21', track: 'Nürburgring GP', car: 'Porsche 911 GT3 R', position: 4, startPosition: 5, incidents: 2, league: 'GridPilot Championship' },
{ id: '3', date: '2024-11-14', track: 'Monza', car: 'Ferrari 488 GT3', position: 2, startPosition: 1, incidents: 1, league: 'GT3 Sprint Series' },
{ id: '4', date: '2024-11-07', track: 'Silverstone', car: 'Audi R8 LMS GT3', position: 7, startPosition: 12, incidents: 0, league: 'GridPilot Championship' },
{ id: '5', date: '2024-10-31', track: 'Interlagos', car: 'Mercedes-AMG GT3', position: 3, startPosition: 4, incidents: 1, league: 'GT3 Sprint Series' },
{ id: '6', date: '2024-10-24', track: 'Road Atlanta', car: 'Porsche 911 GT3 R', position: 5, startPosition: 8, incidents: 2, league: 'GridPilot Championship' },
{ id: '7', date: '2024-10-17', track: 'Watkins Glen', car: 'BMW M4 GT3', position: 1, startPosition: 2, incidents: 0, league: 'GT3 Sprint Series' },
{ id: '8', date: '2024-10-10', track: 'Brands Hatch', car: 'Porsche 911 GT3 R', position: 6, startPosition: 7, incidents: 3, league: 'GridPilot Championship' },
{ id: '9', date: '2024-10-03', track: 'Suzuka', car: 'McLaren 720S GT3', position: 2, startPosition: 6, incidents: 1, league: 'GT3 Sprint Series' },
{ id: '10', date: '2024-09-26', track: 'Bathurst', car: 'Porsche 911 GT3 R', position: 8, startPosition: 10, incidents: 0, league: 'GridPilot Championship' },
{ id: '11', date: '2024-09-19', track: 'Laguna Seca', car: 'Ferrari 488 GT3', position: 3, startPosition: 5, incidents: 2, league: 'GT3 Sprint Series' },
{ id: '12', date: '2024-09-12', track: 'Imola', car: 'Audi R8 LMS GT3', position: 1, startPosition: 1, incidents: 0, league: 'GridPilot Championship' },
];
export default function ProfileRaceHistory() {
export default function ProfileRaceHistory({ driverId }: RaceHistoryProps) {
const [filter, setFilter] = useState<'all' | 'wins' | 'podiums'>('all');
const [page, setPage] = useState(1);
const [races, setRaces] = useState<Race[]>([]);
const [results, setResults] = useState<Result[]>([]);
const [leagues, setLeagues] = useState<Map<string, League>>(new Map());
const [loading, setLoading] = useState(true);
const resultsPerPage = 10;
const filteredResults = mockRaceHistory.filter(result => {
if (filter === 'wins') return result.position === 1;
if (filter === 'podiums') return result.position <= 3;
useEffect(() => {
async function loadRaceHistory() {
try {
const resultRepo = getResultRepository();
const raceRepo = getRaceRepository();
const leagueRepo = getLeagueRepository();
const driverResults = await resultRepo.findByDriverId(driverId);
const allRaces = await raceRepo.findAll();
const allLeagues = await leagueRepo.findAll();
// Filter races to only those where driver has results
const raceIds = new Set(driverResults.map(r => r.raceId));
const driverRaces = allRaces
.filter(race => raceIds.has(race.id) && race.status === 'completed')
.sort((a, b) => b.scheduledAt.getTime() - a.scheduledAt.getTime());
const leagueMap = new Map<string, League>();
allLeagues.forEach(league => leagueMap.set(league.id, league));
setRaces(driverRaces);
setResults(driverResults);
setLeagues(leagueMap);
} catch (err) {
console.error('Failed to load race history:', err);
} finally {
setLoading(false);
}
}
loadRaceHistory();
}, [driverId]);
const raceHistory = races.map(race => {
const result = results.find(r => r.raceId === race.id);
const league = leagues.get(race.leagueId);
return {
race,
result,
league,
};
}).filter(item => item.result);
const filteredResults = raceHistory.filter(item => {
if (!item.result) return false;
if (filter === 'wins') return item.result.position === 1;
if (filter === 'podiums') return item.result.position <= 3;
return true;
});
@@ -47,6 +78,34 @@ export default function ProfileRaceHistory() {
page * resultsPerPage
);
if (loading) {
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
{[1, 2, 3].map(i => (
<div key={i} className="h-9 w-24 bg-iron-gray rounded animate-pulse" />
))}
</div>
<Card>
<div className="space-y-2">
{[1, 2, 3].map(i => (
<div key={i} className="h-20 bg-deep-graphite rounded animate-pulse" />
))}
</div>
</Card>
</div>
);
}
if (raceHistory.length === 0) {
return (
<Card className="text-center py-12">
<p className="text-gray-400 mb-2">No race history yet</p>
<p className="text-sm text-gray-500">Complete races to build your racing record</p>
</Card>
);
}
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
@@ -75,53 +134,19 @@ export default function ProfileRaceHistory() {
<Card>
<div className="space-y-2">
{paginatedResults.map((result) => (
<div
key={result.id}
className="p-4 rounded bg-deep-graphite border border-charcoal-outline hover:border-primary-blue/50 transition-colors"
>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-3">
<div className={`
w-8 h-8 rounded flex items-center justify-center font-bold text-sm
${result.position === 1 ? 'bg-green-400/20 text-green-400' :
result.position === 2 ? 'bg-gray-400/20 text-gray-400' :
result.position === 3 ? 'bg-warning-amber/20 text-warning-amber' :
'bg-charcoal-outline text-gray-400'}
`}>
P{result.position}
</div>
<div>
<div className="text-white font-medium">{result.track}</div>
<div className="text-sm text-gray-400">{result.car}</div>
</div>
</div>
<div className="text-right">
<div className="text-sm text-gray-400">
{new Date(result.date).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
})}
</div>
<div className="text-xs text-gray-500">{result.league}</div>
</div>
</div>
<div className="flex items-center gap-4 text-xs text-gray-500">
<span>Started P{result.startPosition}</span>
<span></span>
<span className={result.incidents === 0 ? 'text-green-400' : result.incidents > 2 ? 'text-red-400' : ''}>
{result.incidents}x incidents
</span>
{result.position < result.startPosition && (
<>
<span></span>
<span className="text-green-400">+{result.startPosition - result.position} positions</span>
</>
)}
</div>
</div>
))}
{paginatedResults.map(({ race, result, league }) => {
if (!result) return null;
return (
<RaceResultCard
key={race.id}
race={race}
result={result}
league={league}
showLeague={true}
/>
);
})}
</div>
{totalPages > 1 && (

View File

@@ -13,6 +13,8 @@ import {
getAllDriverRankings,
getDriverRepository,
getGetLeagueFullConfigQuery,
getRaceRepository,
getProtestRepository,
} from '@/lib/di-container';
import type { LeagueConfigFormModel } from '@gridpilot/racing/application';
import { LeagueBasicsSection } from './LeagueBasicsSection';
@@ -27,6 +29,9 @@ import { EntityMappers } from '@gridpilot/racing/application/mappers/EntityMappe
import DriverSummaryPill from '@/components/profile/DriverSummaryPill';
import DriverIdentity from '@/components/drivers/DriverIdentity';
import Modal from '@/components/ui/Modal';
import { AlertTriangle, CheckCircle, Clock, XCircle, Flag, Calendar, User } from 'lucide-react';
import type { Protest } from '@gridpilot/racing/domain/entities/Protest';
import type { Race } from '@gridpilot/racing/domain/entities/Race';
interface JoinRequest {
id: string;
@@ -51,10 +56,14 @@ export default function LeagueAdmin({ league, onLeagueUpdate }: LeagueAdminProps
const [ownerDriver, setOwnerDriver] = useState<DriverDTO | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<'members' | 'requests' | 'races' | 'settings' | 'disputes'>('members');
const [activeTab, setActiveTab] = useState<'members' | 'requests' | 'races' | 'settings' | 'protests'>('members');
const [rejectReason, setRejectReason] = useState('');
const [configForm, setConfigForm] = useState<LeagueConfigFormModel | null>(null);
const [configLoading, setConfigLoading] = useState(false);
const [protests, setProtests] = useState<Protest[]>([]);
const [protestRaces, setProtestRaces] = useState<Record<string, Race>>({});
const [protestDriversById, setProtestDriversById] = useState<Record<string, DriverDTO>>({});
const [protestsLoading, setProtestsLoading] = useState(false);
const loadJoinRequests = useCallback(async () => {
setLoading(true);
@@ -119,6 +128,62 @@ export default function LeagueAdmin({ league, onLeagueUpdate }: LeagueAdminProps
loadConfig();
}, [league.id]);
// Load protests for this league's races
useEffect(() => {
async function loadProtests() {
setProtestsLoading(true);
try {
const raceRepo = getRaceRepository();
const protestRepo = getProtestRepository();
const driverRepo = getDriverRepository();
// Get all races for this league
const leagueRaces = await raceRepo.findByLeagueId(league.id);
// Get protests for each race
const allProtests: Protest[] = [];
const racesById: Record<string, Race> = {};
for (const race of leagueRaces) {
racesById[race.id] = race;
const raceProtests = await protestRepo.findByRaceId(race.id);
allProtests.push(...raceProtests);
}
setProtests(allProtests);
setProtestRaces(racesById);
// Load driver info for all protesters and accused
const driverIds = new Set<string>();
allProtests.forEach((p) => {
driverIds.add(p.protestingDriverId);
driverIds.add(p.accusedDriverId);
});
const driverEntities = await Promise.all(
Array.from(driverIds).map((id) => driverRepo.findById(id)),
);
const driverDtos = driverEntities
.map((driver) => (driver ? EntityMappers.toDriverDTO(driver) : null))
.filter((dto): dto is DriverDTO => dto !== null);
const byId: Record<string, DriverDTO> = {};
for (const dto of driverDtos) {
byId[dto.id] = dto;
}
setProtestDriversById(byId);
} catch (err) {
console.error('Failed to load protests:', err);
} finally {
setProtestsLoading(false);
}
}
if (activeTab === 'protests') {
loadProtests();
}
}, [league.id, activeTab]);
const handleApproveRequest = async (requestId: string) => {
try {
const membershipRepo = getLeagueMembershipRepository();
@@ -341,14 +406,19 @@ export default function LeagueAdmin({ league, onLeagueUpdate }: LeagueAdminProps
Create Race
</button>
<button
onClick={() => setActiveTab('disputes')}
className={`pb-3 px-1 font-medium transition-colors ${
activeTab === 'disputes'
onClick={() => setActiveTab('protests')}
className={`pb-3 px-1 font-medium transition-colors flex items-center gap-2 ${
activeTab === 'protests'
? 'text-primary-blue border-b-2 border-primary-blue'
: 'text-gray-400 hover:text-white'
}`}
>
Disputes
Protests
{protests.length > 0 && (
<span className="px-2 py-0.5 text-xs bg-warning-amber/20 text-warning-amber rounded-full">
{protests.filter(p => p.status === 'pending').length || protests.length}
</span>
)}
</button>
<button
onClick={() => setActiveTab('settings')}
@@ -462,27 +532,156 @@ export default function LeagueAdmin({ league, onLeagueUpdate }: LeagueAdminProps
</Card>
)}
{activeTab === 'disputes' && (
{activeTab === 'protests' && (
<Card>
<h2 className="text-xl font-semibold text-white mb-4">Disputes (Alpha)</h2>
<div className="space-y-4">
<p className="text-sm text-gray-400">
Demo-only view of potential protest and dispute workflow for this league.
</p>
<div className="rounded-lg border border-charcoal-outline bg-deep-graphite/70 p-4">
<h3 className="text-sm font-semibold text-white mb-1">Sample Protest</h3>
<p className="text-xs text-gray-400 mb-2">
Driver contact in Turn 3, Lap 12. Protest submitted by a driver against another
competitor for avoidable contact.
</p>
<p className="text-xs text-gray-500">
In the full product, this area would show protests, steward reviews, penalties, and appeals.
<div className="flex items-center justify-between mb-6">
<div>
<h2 className="text-xl font-semibold text-white">Protests</h2>
<p className="text-sm text-gray-400 mt-1">
Review protests filed by drivers and manage steward decisions
</p>
</div>
<p className="text-xs text-gray-500">
For the alpha, this tab is static and read-only and does not affect any race or league state.
</p>
<div className="flex items-center gap-2 px-3 py-1.5 rounded-full bg-warning-amber/10 border border-warning-amber/30">
<AlertTriangle className="w-4 h-4 text-warning-amber" />
<span className="text-xs font-medium text-warning-amber">Alpha Preview</span>
</div>
</div>
{protestsLoading ? (
<div className="text-center py-12 text-gray-400">
<div className="animate-pulse">Loading protests...</div>
</div>
) : protests.length === 0 ? (
<div className="text-center py-12">
<div className="w-16 h-16 mx-auto mb-4 rounded-full bg-iron-gray/50 flex items-center justify-center">
<Flag className="w-8 h-8 text-gray-500" />
</div>
<h3 className="text-lg font-medium text-white mb-2">No Protests Filed</h3>
<p className="text-sm text-gray-400 max-w-md mx-auto">
When drivers file protests for incidents during races, they will appear here for steward review.
</p>
</div>
) : (
<div className="space-y-4">
{/* Stats summary */}
<div className="grid grid-cols-3 gap-4 mb-6">
<div className="rounded-lg bg-iron-gray/50 border border-charcoal-outline p-4">
<div className="flex items-center gap-2 text-warning-amber mb-1">
<Clock className="w-4 h-4" />
<span className="text-xs font-medium uppercase">Pending</span>
</div>
<div className="text-2xl font-bold text-white">
{protests.filter((p) => p.status === 'pending').length}
</div>
</div>
<div className="rounded-lg bg-iron-gray/50 border border-charcoal-outline p-4">
<div className="flex items-center gap-2 text-performance-green mb-1">
<CheckCircle className="w-4 h-4" />
<span className="text-xs font-medium uppercase">Resolved</span>
</div>
<div className="text-2xl font-bold text-white">
{protests.filter((p) => p.status === 'upheld' || p.status === 'dismissed').length}
</div>
</div>
<div className="rounded-lg bg-iron-gray/50 border border-charcoal-outline p-4">
<div className="flex items-center gap-2 text-primary-blue mb-1">
<Flag className="w-4 h-4" />
<span className="text-xs font-medium uppercase">Total</span>
</div>
<div className="text-2xl font-bold text-white">
{protests.length}
</div>
</div>
</div>
{/* Protest list */}
<div className="space-y-3">
{protests.map((protest) => {
const race = protestRaces[protest.raceId];
const filer = protestDriversById[protest.protestingDriverId];
const accused = protestDriversById[protest.accusedDriverId];
const statusConfig = {
pending: { color: 'text-warning-amber', bg: 'bg-warning-amber/10', border: 'border-warning-amber/30', icon: Clock, label: 'Pending Review' },
under_review: { color: 'text-primary-blue', bg: 'bg-primary-blue/10', border: 'border-primary-blue/30', icon: Flag, label: 'Under Review' },
upheld: { color: 'text-red-400', bg: 'bg-red-500/10', border: 'border-red-500/30', icon: AlertTriangle, label: 'Upheld' },
dismissed: { color: 'text-gray-400', bg: 'bg-gray-500/10', border: 'border-gray-500/30', icon: XCircle, label: 'Dismissed' },
withdrawn: { color: 'text-gray-500', bg: 'bg-gray-600/10', border: 'border-gray-600/30', icon: XCircle, label: 'Withdrawn' },
}[protest.status] ?? { color: 'text-gray-400', bg: 'bg-gray-500/10', border: 'border-gray-500/30', icon: Clock, label: protest.status };
const StatusIcon = statusConfig.icon;
return (
<div
key={protest.id}
className="rounded-lg border border-charcoal-outline bg-deep-graphite/70 p-4 hover:bg-iron-gray/30 transition-colors"
>
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-3 mb-2">
<div className={`flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium ${statusConfig.bg} ${statusConfig.border} ${statusConfig.color} border`}>
<StatusIcon className="w-3 h-3" />
{statusConfig.label}
</div>
{race && (
<span className="text-xs text-gray-500 flex items-center gap-1">
<Calendar className="w-3 h-3" />
{race.track} {new Date(race.scheduledAt).toLocaleDateString()}
</span>
)}
</div>
<h3 className="text-sm font-semibold text-white mb-1 capitalize">
Incident at Lap {protest.incident.lap}
</h3>
<p className="text-xs text-gray-400 mb-3 line-clamp-2">
{protest.incident.description}
</p>
<div className="flex items-center gap-4 text-xs">
<div className="flex items-center gap-1.5">
<User className="w-3 h-3 text-gray-500" />
<span className="text-gray-400">Filed by:</span>
<span className="text-white font-medium">{filer?.name ?? 'Unknown'}</span>
</div>
<div className="flex items-center gap-1.5">
<AlertTriangle className="w-3 h-3 text-warning-amber" />
<span className="text-gray-400">Against:</span>
<span className="text-warning-amber font-medium">{accused?.name ?? 'Unknown'}</span>
</div>
</div>
</div>
{protest.status === 'pending' && (
<div className="flex gap-2 shrink-0">
<Button variant="secondary" disabled>
Review
</Button>
</div>
)}
</div>
{protest.comment && (
<div className="mt-3 pt-3 border-t border-charcoal-outline/50">
<span className="text-xs text-gray-500">
Driver comment: "{protest.comment}"
</span>
</div>
)}
</div>
);
})}
</div>
<div className="mt-6 p-4 rounded-lg bg-iron-gray/30 border border-charcoal-outline/50">
<p className="text-xs text-gray-500">
<strong className="text-gray-400">Alpha Note:</strong> Protest review and penalty application is demonstration-only.
In the full product, stewards can review evidence, apply penalties, and manage appeals.
</p>
</div>
</div>
)}
</Card>
)}

View File

@@ -5,7 +5,6 @@ import Link from 'next/link';
import Image from 'next/image';
import MembershipStatus from '@/components/leagues/MembershipStatus';
import FeatureLimitationTooltip from '@/components/alpha/FeatureLimitationTooltip';
import { getLeagueCoverClasses } from '@/lib/leagueCovers';
import {
getDriverRepository,
getDriverStats,
@@ -32,7 +31,6 @@ export default function LeagueHeader({
ownerName,
}: LeagueHeaderProps) {
const imageService = getImageService();
const coverUrl = imageService.getLeagueCover(leagueId);
const logoUrl = imageService.getLeagueLogo(leagueId);
const [ownerDriver, setOwnerDriver] = useState<DriverDTO | null>(null);
@@ -100,35 +98,27 @@ export default function LeagueHeader({
return (
<div className="mb-8">
<div className="mb-4">
<div className={getLeagueCoverClasses(leagueId)} aria-hidden="true">
<div className="relative w-full h-full">
{/* League header with logo - no cover image */}
<div className="flex items-center justify-between mb-6">
<div className="flex items-center gap-4">
<div className="h-16 w-16 rounded-xl overflow-hidden border-2 border-charcoal-outline bg-iron-gray shadow-lg">
<Image
src={coverUrl}
alt="League cover placeholder"
fill
className="object-cover opacity-80"
sizes="100vw"
src={logoUrl}
alt={`${leagueName} logo`}
width={64}
height={64}
className="w-full h-full object-cover"
/>
<div className="absolute left-6 bottom-4 flex items-center">
<div className="h-16 w-16 rounded-full overflow-hidden border-2 border-charcoal-outline bg-deep-graphite/95 shadow-[0_0_18px_rgba(0,0,0,0.7)]">
<Image
src={logoUrl}
alt={`${leagueName} logo`}
width={64}
height={64}
className="w-full h-full object-cover"
/>
</div>
</div>
</div>
</div>
</div>
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-3">
<h1 className="text-3xl font-bold text-white">{leagueName}</h1>
<MembershipStatus leagueId={leagueId} />
<div>
<div className="flex items-center gap-3 mb-1">
<h1 className="text-2xl font-bold text-white">{leagueName}</h1>
<MembershipStatus leagueId={leagueId} />
</div>
{description && (
<p className="text-gray-400 text-sm max-w-xl">{description}</p>
)}
</div>
</div>
<FeatureLimitationTooltip message="Multi-league memberships coming in production">
<span className="px-2 py-1 text-xs font-medium bg-primary-blue/10 text-primary-blue rounded border border-primary-blue/30">
@@ -137,30 +127,22 @@ export default function LeagueHeader({
</FeatureLimitationTooltip>
</div>
{description && (
<p className="text-gray-400 mb-2">{description}</p>
)}
<div className="mb-6 flex flex-col gap-2">
<span className="text-sm text-gray-400">Owner</span>
<div className="flex items-center gap-3">
<span className="text-sm text-gray-400">Owner:</span>
{ownerSummary ? (
<div className="inline-flex items-center gap-3">
<DriverSummaryPill
driver={ownerSummary.driver}
rating={ownerSummary.rating}
rank={ownerSummary.rank}
href={`/drivers/${ownerSummary.driver.id}?from=league&leagueId=${leagueId}`}
/>
</div>
<DriverSummaryPill
driver={ownerSummary.driver}
rating={ownerSummary.rating}
rank={ownerSummary.rank}
href={`/drivers/${ownerSummary.driver.id}?from=league&leagueId=${leagueId}`}
/>
) : (
<div className="text-sm text-gray-500">
<Link
href={`/drivers/${ownerId}?from=league&leagueId=${leagueId}`}
className="text-primary-blue hover:underline"
>
{ownerName}
</Link>
</div>
<Link
href={`/drivers/${ownerId}?from=league&leagueId=${leagueId}`}
className="text-sm text-primary-blue hover:underline"
>
{ownerName}
</Link>
)}
</div>
</div>

View File

@@ -0,0 +1,282 @@
'use client';
import { useState } from 'react';
import Modal from '@/components/ui/Modal';
import Button from '@/components/ui/Button';
import { getFileProtestUseCase, getDriverRepository } from '@/lib/di-container';
import type { Driver } from '@gridpilot/racing/domain/entities/Driver';
import type { ProtestIncident } from '@gridpilot/racing/domain/entities/Protest';
import {
AlertTriangle,
Video,
MessageSquare,
Hash,
Clock,
User,
FileText,
CheckCircle2,
} from 'lucide-react';
interface FileProtestModalProps {
isOpen: boolean;
onClose: () => void;
raceId: string;
leagueId?: string;
protestingDriverId: string;
participants: Driver[];
}
export default function FileProtestModal({
isOpen,
onClose,
raceId,
leagueId,
protestingDriverId,
participants,
}: FileProtestModalProps) {
const [step, setStep] = useState<'form' | 'submitting' | 'success' | 'error'>('form');
const [errorMessage, setErrorMessage] = useState<string | null>(null);
// Form state
const [accusedDriverId, setAccusedDriverId] = useState<string>('');
const [lap, setLap] = useState<string>('');
const [timeInRace, setTimeInRace] = useState<string>('');
const [description, setDescription] = useState<string>('');
const [comment, setComment] = useState<string>('');
const [proofVideoUrl, setProofVideoUrl] = useState<string>('');
const otherParticipants = participants.filter(p => p.id !== protestingDriverId);
const handleSubmit = async () => {
// Validation
if (!accusedDriverId) {
setErrorMessage('Please select the driver you are protesting against.');
return;
}
if (!lap || parseInt(lap, 10) < 0) {
setErrorMessage('Please enter a valid lap number.');
return;
}
if (!description.trim()) {
setErrorMessage('Please describe what happened.');
return;
}
setStep('submitting');
setErrorMessage(null);
try {
const useCase = getFileProtestUseCase();
const incident: ProtestIncident = {
lap: parseInt(lap, 10),
timeInRace: timeInRace ? parseInt(timeInRace, 10) : undefined,
description: description.trim(),
};
await useCase.execute({
raceId,
protestingDriverId,
accusedDriverId,
incident,
comment: comment.trim() || undefined,
proofVideoUrl: proofVideoUrl.trim() || undefined,
});
setStep('success');
} catch (err) {
setStep('error');
setErrorMessage(err instanceof Error ? err.message : 'Failed to file protest');
}
};
const handleClose = () => {
// Reset form state
setStep('form');
setErrorMessage(null);
setAccusedDriverId('');
setLap('');
setTimeInRace('');
setDescription('');
setComment('');
setProofVideoUrl('');
onClose();
};
if (step === 'success') {
return (
<Modal
isOpen={isOpen}
onOpenChange={handleClose}
title="Protest Filed Successfully"
>
<div className="flex flex-col items-center py-6 text-center">
<div className="p-4 bg-performance-green/20 rounded-full mb-4">
<CheckCircle2 className="w-8 h-8 text-performance-green" />
</div>
<p className="text-white font-medium mb-2">Your protest has been submitted</p>
<p className="text-sm text-gray-400 mb-6">
The stewards will review your protest and make a decision.
You'll be notified of the outcome.
</p>
<Button variant="primary" onClick={handleClose}>
Close
</Button>
</div>
</Modal>
);
}
return (
<Modal
isOpen={isOpen}
onOpenChange={handleClose}
title="File a Protest"
description="Report an incident to the stewards for review. Please provide as much detail as possible."
>
<div className="space-y-5">
{errorMessage && (
<div className="flex items-start gap-3 p-3 bg-warning-amber/10 border border-warning-amber/30 rounded-lg">
<AlertTriangle className="w-5 h-5 text-warning-amber flex-shrink-0 mt-0.5" />
<p className="text-sm text-warning-amber">{errorMessage}</p>
</div>
)}
{/* Driver Selection */}
<div>
<label className="flex items-center gap-2 text-sm font-medium text-gray-300 mb-2">
<User className="w-4 h-4 text-primary-blue" />
Driver involved *
</label>
<select
value={accusedDriverId}
onChange={(e) => setAccusedDriverId(e.target.value)}
disabled={step === 'submitting'}
className="w-full px-3 py-2.5 bg-deep-graphite border border-charcoal-outline rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary-blue/50 focus:border-primary-blue disabled:opacity-50"
>
<option value="">Select driver...</option>
{otherParticipants.map((driver) => (
<option key={driver.id} value={driver.id}>
{driver.name}
</option>
))}
</select>
</div>
{/* Lap and Time */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="flex items-center gap-2 text-sm font-medium text-gray-300 mb-2">
<Hash className="w-4 h-4 text-primary-blue" />
Lap number *
</label>
<input
type="number"
min="0"
value={lap}
onChange={(e) => setLap(e.target.value)}
disabled={step === 'submitting'}
placeholder="e.g. 5"
className="w-full px-3 py-2.5 bg-deep-graphite border border-charcoal-outline rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary-blue/50 focus:border-primary-blue disabled:opacity-50"
/>
</div>
<div>
<label className="flex items-center gap-2 text-sm font-medium text-gray-300 mb-2">
<Clock className="w-4 h-4 text-primary-blue" />
Time (seconds)
</label>
<input
type="number"
min="0"
value={timeInRace}
onChange={(e) => setTimeInRace(e.target.value)}
disabled={step === 'submitting'}
placeholder="Optional"
className="w-full px-3 py-2.5 bg-deep-graphite border border-charcoal-outline rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary-blue/50 focus:border-primary-blue disabled:opacity-50"
/>
</div>
</div>
{/* Incident Description */}
<div>
<label className="flex items-center gap-2 text-sm font-medium text-gray-300 mb-2">
<FileText className="w-4 h-4 text-primary-blue" />
What happened? *
</label>
<textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
disabled={step === 'submitting'}
placeholder="Describe the incident clearly and objectively..."
rows={3}
className="w-full px-3 py-2.5 bg-deep-graphite border border-charcoal-outline rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary-blue/50 focus:border-primary-blue disabled:opacity-50 resize-none"
/>
</div>
{/* Additional Comment */}
<div>
<label className="flex items-center gap-2 text-sm font-medium text-gray-300 mb-2">
<MessageSquare className="w-4 h-4 text-primary-blue" />
Additional comment
</label>
<textarea
value={comment}
onChange={(e) => setComment(e.target.value)}
disabled={step === 'submitting'}
placeholder="Any additional context for the stewards..."
rows={2}
className="w-full px-3 py-2.5 bg-deep-graphite border border-charcoal-outline rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary-blue/50 focus:border-primary-blue disabled:opacity-50 resize-none"
/>
</div>
{/* Video Proof */}
<div>
<label className="flex items-center gap-2 text-sm font-medium text-gray-300 mb-2">
<Video className="w-4 h-4 text-primary-blue" />
Video proof URL
</label>
<input
type="url"
value={proofVideoUrl}
onChange={(e) => setProofVideoUrl(e.target.value)}
disabled={step === 'submitting'}
placeholder="https://youtube.com/... or https://streamable.com/..."
className="w-full px-3 py-2.5 bg-deep-graphite border border-charcoal-outline rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary-blue/50 focus:border-primary-blue disabled:opacity-50"
/>
<p className="mt-1.5 text-xs text-gray-500">
Providing video evidence significantly helps the stewards review your protest.
</p>
</div>
{/* Info Box */}
<div className="p-3 bg-iron-gray rounded-lg border border-charcoal-outline">
<p className="text-xs text-gray-400">
<strong className="text-gray-300">Note:</strong> Filing a protest does not guarantee action.
The stewards will review the incident and may apply penalties ranging from time penalties
to grid penalties for future races, depending on the severity.
</p>
</div>
{/* Actions */}
<div className="flex gap-3 pt-2">
<Button
variant="secondary"
onClick={handleClose}
disabled={step === 'submitting'}
className="flex-1"
>
Cancel
</Button>
<Button
variant="primary"
onClick={handleSubmit}
disabled={step === 'submitting'}
className="flex-1"
>
{step === 'submitting' ? 'Submitting...' : 'Submit Protest'}
</Button>
</div>
</div>
</Modal>
);
}

View File

@@ -0,0 +1,79 @@
'use client';
import Link from 'next/link';
import { ChevronRight } from 'lucide-react';
import { Race } from '@gridpilot/racing/domain/entities/Race';
import { Result } from '@gridpilot/racing/domain/entities/Result';
import { League } from '@gridpilot/racing/domain/entities/League';
interface RaceResultCardProps {
race: Race;
result: Result;
league?: League;
showLeague?: boolean;
}
export default function RaceResultCard({
race,
result,
league,
showLeague = true,
}: RaceResultCardProps) {
const getPositionColor = (position: number) => {
if (position === 1) return 'bg-green-400/20 text-green-400';
if (position === 2) return 'bg-gray-400/20 text-gray-400';
if (position === 3) return 'bg-warning-amber/20 text-warning-amber';
return 'bg-charcoal-outline text-gray-400';
};
return (
<Link
href={`/races/${race.id}`}
className="block p-4 rounded bg-deep-graphite border border-charcoal-outline hover:border-primary-blue/50 transition-colors group"
>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-3">
<div className={`w-8 h-8 rounded flex items-center justify-center font-bold text-sm ${getPositionColor(result.position)}`}>
P{result.position}
</div>
<div>
<div className="text-white font-medium group-hover:text-primary-blue transition-colors">
{race.track}
</div>
<div className="text-sm text-gray-400">{race.car}</div>
</div>
</div>
<div className="flex items-center gap-3">
<div className="text-right">
<div className="text-sm text-gray-400">
{race.scheduledAt.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
})}
</div>
{showLeague && league && (
<div className="text-xs text-gray-500">{league.name}</div>
)}
</div>
<ChevronRight className="w-5 h-5 text-gray-500 group-hover:text-primary-blue transition-colors" />
</div>
</div>
<div className="flex items-center gap-4 text-xs text-gray-500">
<span>Started P{result.startPosition}</span>
<span></span>
<span className={result.incidents === 0 ? 'text-green-400' : result.incidents > 2 ? 'text-red-400' : ''}>
{result.incidents}x incidents
</span>
{result.position < result.startPosition && (
<>
<span></span>
<span className="text-green-400">
+{result.startPosition - result.position} positions
</span>
</>
)}
</div>
</Link>
);
}

View File

@@ -1,21 +1,55 @@
'use client';
import Link from 'next/link';
import { Result } from '@gridpilot/racing/domain/entities/Result';
import { Driver } from '@gridpilot/racing/domain/entities/Driver';
import type { PenaltyType } from '@gridpilot/racing/domain/entities/Penalty';
import { AlertTriangle, ExternalLink } from 'lucide-react';
/**
* Penalty data for display (can be domain Penalty or RacePenaltyDTO)
*/
interface PenaltyData {
driverId: string;
type: PenaltyType;
value?: number;
}
interface ResultsTableProps {
results: Result[];
drivers: Driver[];
pointsSystem: Record<number, number>;
fastestLapTime?: number;
penalties?: PenaltyData[];
currentDriverId?: string;
}
export default function ResultsTable({ results, drivers, pointsSystem, fastestLapTime }: ResultsTableProps) {
export default function ResultsTable({ results, drivers, pointsSystem, fastestLapTime, penalties = [], currentDriverId }: ResultsTableProps) {
const getDriver = (driverId: string): Driver | undefined => {
return drivers.find(d => d.id === driverId);
};
const getDriverName = (driverId: string): string => {
const driver = drivers.find(d => d.id === driverId);
const driver = getDriver(driverId);
return driver?.name || 'Unknown Driver';
};
const getDriverPenalties = (driverId: string): PenaltyData[] => {
return penalties.filter(p => p.driverId === driverId);
};
const getPenaltyDescription = (penalty: PenaltyData): string => {
const descriptions: Record<string, string> = {
time_penalty: `+${penalty.value}s time penalty`,
grid_penalty: `${penalty.value} place grid penalty`,
points_deduction: `-${penalty.value} points`,
disqualification: 'Disqualified',
warning: 'Warning',
license_points: `${penalty.value} license points`,
};
return descriptions[penalty.type] || penalty.type;
};
const formatLapTime = (seconds: number): string => {
const minutes = Math.floor(seconds / 60);
const secs = (seconds % 60).toFixed(3);
@@ -57,23 +91,70 @@ export default function ResultsTable({ results, drivers, pointsSystem, fastestLa
<th className="text-left py-3 px-4 text-sm font-semibold text-gray-400">Incidents</th>
<th className="text-left py-3 px-4 text-sm font-semibold text-gray-400">Points</th>
<th className="text-left py-3 px-4 text-sm font-semibold text-gray-400">+/-</th>
<th className="text-left py-3 px-4 text-sm font-semibold text-gray-400">Penalties</th>
</tr>
</thead>
<tbody>
{results.map((result) => {
const positionChange = result.getPositionChange();
const isFastestLap = fastestLapTime && result.fastestLap === fastestLapTime;
const driverPenalties = getDriverPenalties(result.driverId);
const driver = getDriver(result.driverId);
const isCurrentUser = currentDriverId === result.driverId;
const isPodium = result.position <= 3;
return (
<tr
<tr
key={result.id}
className="border-b border-charcoal-outline/50 hover:bg-iron-gray/20 transition-colors"
className={`
border-b border-charcoal-outline/50 transition-colors
${isCurrentUser
? 'bg-gradient-to-r from-primary-blue/20 via-primary-blue/10 to-transparent hover:from-primary-blue/30'
: 'hover:bg-iron-gray/20'}
`}
>
<td className="py-3 px-4">
<span className="text-white font-semibold">{result.position}</span>
<div className={`
inline-flex items-center justify-center w-8 h-8 rounded-lg font-bold text-sm
${result.position === 1 ? 'bg-yellow-500/20 text-yellow-400' :
result.position === 2 ? 'bg-gray-400/20 text-gray-300' :
result.position === 3 ? 'bg-amber-600/20 text-amber-500' :
'text-white'}
`}>
{result.position}
</div>
</td>
<td className="py-3 px-4">
<span className="text-white">{getDriverName(result.driverId)}</span>
<div className="flex items-center gap-3">
{driver ? (
<>
<div className={`
w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold flex-shrink-0
${isCurrentUser ? 'bg-primary-blue/30 text-primary-blue ring-2 ring-primary-blue/50' : 'bg-iron-gray text-gray-400'}
`}>
{driver.name.charAt(0)}
</div>
<Link
href={`/drivers/${driver.id}`}
className={`
flex items-center gap-1.5 group
${isCurrentUser ? 'text-primary-blue font-semibold' : 'text-white hover:text-primary-blue'}
transition-colors
`}
>
<span className="group-hover:underline">{driver.name}</span>
{isCurrentUser && (
<span className="px-1.5 py-0.5 text-[10px] font-bold bg-primary-blue text-white rounded-full uppercase">
You
</span>
)}
<ExternalLink className="w-3 h-3 opacity-0 group-hover:opacity-100 transition-opacity" />
</Link>
</>
) : (
<span className="text-white">{getDriverName(result.driverId)}</span>
)}
</div>
</td>
<td className="py-3 px-4">
<span className={isFastestLap ? 'text-performance-green font-medium' : 'text-white'}>
@@ -93,6 +174,23 @@ export default function ResultsTable({ results, drivers, pointsSystem, fastestLa
{getPositionChangeText(positionChange)}
</span>
</td>
<td className="py-3 px-4">
{driverPenalties.length > 0 ? (
<div className="flex flex-col gap-1">
{driverPenalties.map((penalty, idx) => (
<div
key={idx}
className="flex items-center gap-1.5 text-xs text-red-400"
>
<AlertTriangle className="w-3 h-3" />
<span>{getPenaltyDescription(penalty)}</span>
</div>
))}
</div>
) : (
<span className="text-gray-500"></span>
)}
</td>
</tr>
);
})}

View File

@@ -5,6 +5,8 @@
* Allows easy swapping to persistent repositories later.
*/
import { Penalty } from '@gridpilot/racing/domain/entities/Penalty';
import { Protest } from '@gridpilot/racing/domain/entities/Protest';
import { Driver } from '@gridpilot/racing/domain/entities/Driver';
import { League } from '@gridpilot/racing/domain/entities/League';
import { Race } from '@gridpilot/racing/domain/entities/Race';
@@ -21,6 +23,7 @@ import type { IRaceRepository } from '@gridpilot/racing/domain/repositories/IRac
import type { IResultRepository } from '@gridpilot/racing/domain/repositories/IResultRepository';
import type { IStandingRepository } from '@gridpilot/racing/domain/repositories/IStandingRepository';
import type { IPenaltyRepository } from '@gridpilot/racing/domain/repositories/IPenaltyRepository';
import type { IProtestRepository } from '@gridpilot/racing/domain/repositories/IProtestRepository';
import type { IGameRepository } from '@gridpilot/racing/domain/repositories/IGameRepository';
import type { ISeasonRepository } from '@gridpilot/racing/domain/repositories/ISeasonRepository';
import type { ILeagueScoringConfigRepository } from '@gridpilot/racing/domain/repositories/ILeagueScoringConfigRepository';
@@ -43,6 +46,7 @@ import { InMemoryRaceRepository } from '@gridpilot/racing/infrastructure/reposit
import { InMemoryResultRepository } from '@gridpilot/racing/infrastructure/repositories/InMemoryResultRepository';
import { InMemoryStandingRepository } from '@gridpilot/racing/infrastructure/repositories/InMemoryStandingRepository';
import { InMemoryPenaltyRepository } from '@gridpilot/racing/infrastructure/repositories/InMemoryPenaltyRepository';
import { InMemoryProtestRepository } from '@gridpilot/racing/infrastructure/repositories/InMemoryProtestRepository';
import { InMemoryTrackRepository } from '@gridpilot/racing/infrastructure/repositories/InMemoryTrackRepository';
import { InMemoryCarRepository } from '@gridpilot/racing/infrastructure/repositories/InMemoryCarRepository';
import {
@@ -83,6 +87,11 @@ import {
GetLeagueFullConfigQuery,
GetRaceWithSOFQuery,
GetLeagueStatsQuery,
FileProtestUseCase,
ReviewProtestUseCase,
ApplyPenaltyUseCase,
GetRaceProtestsQuery,
GetRacePenaltiesQuery,
} from '@gridpilot/racing/application';
import type { DriverRatingProvider } from '@gridpilot/racing/application';
import {
@@ -170,6 +179,7 @@ class DIContainer {
private _resultRepository: IResultRepository;
private _standingRepository: IStandingRepository;
private _penaltyRepository: IPenaltyRepository;
private _protestRepository: IProtestRepository;
private _teamRepository: ITeamRepository;
private _teamMembershipRepository: ITeamMembershipRepository;
private _raceRegistrationRepository: IRaceRegistrationRepository;
@@ -204,6 +214,12 @@ class DIContainer {
private _getLeagueStatsQuery: GetLeagueStatsQuery;
private _driverRatingProvider: DriverRatingProvider;
private _fileProtestUseCase: FileProtestUseCase;
private _reviewProtestUseCase: ReviewProtestUseCase;
private _applyPenaltyUseCase: ApplyPenaltyUseCase;
private _getRaceProtestsQuery: GetRaceProtestsQuery;
private _getRacePenaltiesQuery: GetRacePenaltiesQuery;
private _createTeamUseCase: CreateTeamUseCase;
private _joinTeamUseCase: JoinTeamUseCase;
private _leaveTeamUseCase: LeaveTeamUseCase;
@@ -267,9 +283,123 @@ class DIContainer {
}
this._raceRegistrationRepository = new InMemoryRaceRegistrationRepository(seedRaceRegistrations);
// Penalties (seeded in-memory adapter)
this._penaltyRepository = new InMemoryPenaltyRepository();
// Seed sample penalties and protests for completed races across different leagues
// Group completed races by league, then take 1-2 from each league to ensure coverage
const completedRaces = seedData.races.filter(r => r.status === 'completed');
const racesByLeague = new Map<string, typeof completedRaces>();
for (const race of completedRaces) {
const existing = racesByLeague.get(race.leagueId) || [];
existing.push(race);
racesByLeague.set(race.leagueId, existing);
}
// Get up to 2 races per league for protest seeding
const racesForProtests: Array<{ race: typeof completedRaces[0]; leagueIndex: number }> = [];
let leagueIndex = 0;
for (const [, leagueRaces] of racesByLeague) {
// Sort by scheduled date, take earliest 2
const sorted = [...leagueRaces].sort((a, b) => a.scheduledAt.getTime() - b.scheduledAt.getTime());
for (const race of sorted.slice(0, 2)) {
racesForProtests.push({ race, leagueIndex });
}
leagueIndex++;
}
const seededPenalties: Penalty[] = [];
const seededProtests: Protest[] = [];
racesForProtests.forEach(({ race, leagueIndex: leagueIdx }, raceIndex) => {
// Get results for this race to find drivers involved
const raceResults = seedData.results.filter(r => r.raceId === race.id);
if (raceResults.length < 4) return;
// Create 1-2 protests per race
const protestCount = Math.min(2, raceResults.length - 2);
for (let i = 0; i < protestCount; i++) {
const protestingResult = raceResults[i + 2]; // Driver who finished 3rd or 4th
const accusedResult = raceResults[i]; // Driver who finished 1st or 2nd
if (!protestingResult || !accusedResult) continue;
const protestStatuses: Array<'pending' | 'under_review' | 'upheld' | 'dismissed'> = ['pending', 'under_review', 'upheld', 'dismissed'];
const status = protestStatuses[(raceIndex + i) % protestStatuses.length];
const protest = Protest.create({
id: `protest-${race.id}-${i}`,
raceId: race.id,
protestingDriverId: protestingResult.driverId,
accusedDriverId: accusedResult.driverId,
incident: {
lap: 5 + i * 3,
description: i === 0
? 'Unsafe rejoining to the track after going off, causing contact'
: 'Aggressive defending, pushing competitor off track',
},
comment: i === 0
? 'Driver rejoined directly into my racing line, causing contact and damaging my front wing.'
: 'Driver moved under braking multiple times, forcing me off the circuit.',
status,
filedAt: new Date(Date.now() - (raceIndex + 1) * 24 * 60 * 60 * 1000),
reviewedBy: status !== 'pending' ? primaryDriverId : undefined,
decisionNotes: status === 'upheld'
? 'After reviewing the evidence, the accused driver is found at fault. Penalty applied.'
: status === 'dismissed'
? 'No clear fault found. Racing incident.'
: undefined,
reviewedAt: status !== 'pending' ? new Date(Date.now() - raceIndex * 24 * 60 * 60 * 1000) : undefined,
});
seededProtests.push(protest);
// If protest was upheld, create a penalty
if (status === 'upheld') {
const penaltyTypes: Array<'time_penalty' | 'points_deduction' | 'warning'> = ['time_penalty', 'points_deduction', 'warning'];
const penaltyType = penaltyTypes[i % penaltyTypes.length];
const penalty = Penalty.create({
id: `penalty-${race.id}-${i}`,
raceId: race.id,
driverId: accusedResult.driverId,
type: penaltyType,
value: penaltyType === 'time_penalty' ? 5 : penaltyType === 'points_deduction' ? 3 : undefined,
reason: protest.incident.description,
protestId: protest.id,
issuedBy: primaryDriverId,
status: 'applied',
issuedAt: new Date(Date.now() - raceIndex * 24 * 60 * 60 * 1000),
appliedAt: new Date(Date.now() - raceIndex * 24 * 60 * 60 * 1000),
});
seededPenalties.push(penalty);
}
}
// Add a direct penalty (not from protest) for some races
if (raceIndex % 2 === 0 && raceResults.length > 5) {
const penalizedResult = raceResults[4];
if (penalizedResult) {
const penalty = Penalty.create({
id: `penalty-direct-${race.id}`,
raceId: race.id,
driverId: penalizedResult.driverId,
type: 'time_penalty',
value: 10,
reason: 'Track limits violation - gained lasting advantage',
issuedBy: primaryDriverId,
status: 'applied',
issuedAt: new Date(Date.now() - (raceIndex + 1) * 12 * 60 * 60 * 1000),
appliedAt: new Date(Date.now() - (raceIndex + 1) * 12 * 60 * 60 * 1000),
});
seededPenalties.push(penalty);
}
}
});
// Penalties and protests with seeded data
this._penaltyRepository = new InMemoryPenaltyRepository(seededPenalties);
this._protestRepository = new InMemoryProtestRepository(seededProtests);
// Scoring preset provider and seeded game/season/scoring config repositories
this._leagueScoringPresetProvider = new InMemoryLeagueScoringPresetProvider();
@@ -396,22 +526,34 @@ class DIContainer {
});
}
// Seed a few pending join requests for demo leagues
// Seed a few pending join requests for demo leagues (expanded to more leagues)
const seededJoinRequests: JoinRequest[] = [];
const demoLeagues = seedData.leagues.slice(0, 2);
const extraDrivers = seedData.drivers.slice(3, 8);
const demoLeagues = seedData.leagues.slice(0, 6); // Expanded from 2 to 6 leagues
const extraDrivers = seedData.drivers.slice(5, 12); // More drivers for requests
demoLeagues.forEach((league) => {
extraDrivers.forEach((driver, index) => {
demoLeagues.forEach((league, leagueIndex) => {
// Skip leagues where these drivers are already members
const memberDriverIds = seededMemberships
.filter(m => m.leagueId === league.id)
.map(m => m.driverId);
const availableDrivers = extraDrivers.filter(d => !memberDriverIds.includes(d.id));
const driversForThisLeague = availableDrivers.slice(0, 3 + (leagueIndex % 3)); // 3-5 requests per league
driversForThisLeague.forEach((driver, index) => {
const messages = [
'Would love to race in this series!',
'Looking to join for the upcoming season.',
'Heard great things about this league. Can I join?',
'Experienced driver looking for competitive racing.',
'My friend recommended this league. Hope to race with you!',
];
seededJoinRequests.push({
id: `join-${league.id}-${driver.id}`,
leagueId: league.id,
driverId: driver.id,
requestedAt: new Date(Date.now() - (index + 1) * 24 * 60 * 60 * 1000),
message:
index % 2 === 0
? 'Would love to race in this series!'
: 'Looking to join for the upcoming season.',
requestedAt: new Date(Date.now() - (index + 1 + leagueIndex) * 24 * 60 * 60 * 1000),
message: messages[(index + leagueIndex) % messages.length],
});
});
});
@@ -467,6 +609,7 @@ class DIContainer {
this._standingRepository,
this._resultRepository,
this._penaltyRepository,
this._raceRepository,
{
getRating: (driverId: string) => {
const stats = driverStats[driverId];
@@ -595,6 +738,32 @@ class DIContainer {
this._teamMembershipRepository,
);
// Stewarding use cases and queries
this._fileProtestUseCase = new FileProtestUseCase(
this._protestRepository,
this._raceRepository,
this._leagueMembershipRepository,
);
this._reviewProtestUseCase = new ReviewProtestUseCase(
this._protestRepository,
this._raceRepository,
this._leagueMembershipRepository,
);
this._applyPenaltyUseCase = new ApplyPenaltyUseCase(
this._penaltyRepository,
this._protestRepository,
this._raceRepository,
this._leagueMembershipRepository,
);
this._getRaceProtestsQuery = new GetRaceProtestsQuery(
this._protestRepository,
this._driverRepository,
);
this._getRacePenaltiesQuery = new GetRacePenaltiesQuery(
this._penaltyRepository,
this._driverRepository,
);
// Social and feed adapters backed by static seed
this._feedRepository = new InMemoryFeedRepository(seedData);
this._socialRepository = new InMemorySocialGraphRepository(seedData);
@@ -825,6 +994,10 @@ class DIContainer {
return this._penaltyRepository;
}
get protestRepository(): IProtestRepository {
return this._protestRepository;
}
get raceRegistrationRepository(): IRaceRegistrationRepository {
return this._raceRegistrationRepository;
}
@@ -989,6 +1162,26 @@ class DIContainer {
get carRepository(): ICarRepository {
return this._carRepository;
}
get fileProtestUseCase(): FileProtestUseCase {
return this._fileProtestUseCase;
}
get reviewProtestUseCase(): ReviewProtestUseCase {
return this._reviewProtestUseCase;
}
get applyPenaltyUseCase(): ApplyPenaltyUseCase {
return this._applyPenaltyUseCase;
}
get getRaceProtestsQuery(): GetRaceProtestsQuery {
return this._getRaceProtestsQuery;
}
get getRacePenaltiesQuery(): GetRacePenaltiesQuery {
return this._getRacePenaltiesQuery;
}
}
/**
@@ -1018,6 +1211,10 @@ export function getPenaltyRepository(): IPenaltyRepository {
return DIContainer.getInstance().penaltyRepository;
}
export function getProtestRepository(): IProtestRepository {
return DIContainer.getInstance().protestRepository;
}
export function getRaceRegistrationRepository(): IRaceRegistrationRepository {
return DIContainer.getInstance().raceRegistrationRepository;
}
@@ -1167,6 +1364,26 @@ export function getCarRepository(): ICarRepository {
return DIContainer.getInstance().carRepository;
}
export function getFileProtestUseCase(): FileProtestUseCase {
return DIContainer.getInstance().fileProtestUseCase;
}
export function getReviewProtestUseCase(): ReviewProtestUseCase {
return DIContainer.getInstance().reviewProtestUseCase;
}
export function getApplyPenaltyUseCase(): ApplyPenaltyUseCase {
return DIContainer.getInstance().applyPenaltyUseCase;
}
export function getGetRaceProtestsQuery(): GetRaceProtestsQuery {
return DIContainer.getInstance().getRaceProtestsQuery;
}
export function getGetRacePenaltiesQuery(): GetRacePenaltiesQuery {
return DIContainer.getInstance().getRacePenaltiesQuery;
}
/**
* Reset function for testing
*/