This commit is contained in:
2025-12-04 23:31:55 +01:00
parent 9fa21a488a
commit fb509607c1
96 changed files with 5839 additions and 1609 deletions

View File

@@ -1,7 +1,7 @@
'use client';
import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { useState, useEffect, useMemo } from 'react';
import { useRouter, useParams, useSearchParams } from 'next/navigation';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import JoinLeagueButton from '@/components/leagues/JoinLeagueButton';
@@ -9,11 +9,23 @@ import LeagueMembers from '@/components/leagues/LeagueMembers';
import LeagueSchedule from '@/components/leagues/LeagueSchedule';
import LeagueAdmin from '@/components/leagues/LeagueAdmin';
import StandingsTable from '@/components/leagues/StandingsTable';
import DriverIdentity from '@/components/drivers/DriverIdentity';
import DriverSummaryPill from '@/components/profile/DriverSummaryPill';
import { League } from '@gridpilot/racing/domain/entities/League';
import { Standing } from '@gridpilot/racing/domain/entities/Standing';
import { Driver } from '@gridpilot/racing/domain/entities/Driver';
import { getLeagueRepository, getRaceRepository, getDriverRepository, getStandingRepository } from '@/lib/di-container';
import { getMembership, isOwnerOrAdmin, getCurrentDriverId } from '@/lib/racingLegacyFacade';
import type { DriverDTO } from '@gridpilot/racing/application/dto/DriverDTO';
import type { LeagueDriverSeasonStatsDTO } from '@gridpilot/racing/application/dto/LeagueDriverSeasonStatsDTO';
import { EntityMappers } from '@gridpilot/racing/application/mappers/EntityMappers';
import {
getLeagueRepository,
getRaceRepository,
getDriverRepository,
getGetLeagueDriverSeasonStatsQuery,
getDriverStats,
getAllDriverRankings,
} from '@/lib/di-container';
import { getMembership, getLeagueMembers, isOwnerOrAdmin } from '@/lib/leagueMembership';
import { useEffectiveDriverId } from '@/lib/currentDriver';
export default function LeagueDetailPage() {
const router = useRouter();
@@ -22,16 +34,17 @@ export default function LeagueDetailPage() {
const [league, setLeague] = useState<League | null>(null);
const [owner, setOwner] = useState<Driver | null>(null);
const [standings, setStandings] = useState<Standing[]>([]);
const [drivers, setDrivers] = useState<Driver[]>([]);
const [standings, setStandings] = useState<LeagueDriverSeasonStatsDTO[]>([]);
const [drivers, setDrivers] = useState<DriverDTO[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<'overview' | 'schedule' | 'standings' | 'members' | 'admin'>('overview');
const [activeTab, setActiveTab] = useState<'overview' | 'schedule' | 'standings' | 'admin'>('overview');
const [refreshKey, setRefreshKey] = useState(0);
const currentDriverId = getCurrentDriverId();
const currentDriverId = useEffectiveDriverId();
const membership = getMembership(leagueId, currentDriverId);
const isAdmin = isOwnerOrAdmin(leagueId, currentDriverId);
const searchParams = useSearchParams();
const loadLeagueData = async () => {
try {
@@ -53,15 +66,18 @@ export default function LeagueDetailPage() {
const ownerData = await driverRepo.findById(leagueData.ownerId);
setOwner(ownerData);
// Load standings
const standingRepo = getStandingRepository();
const allStandings = await standingRepo.findAll();
const leagueStandings = allStandings.filter(s => s.leagueId === leagueId);
// Load standings via rich season stats query
const getLeagueDriverSeasonStatsQuery = getGetLeagueDriverSeasonStatsQuery();
const leagueStandings = await getLeagueDriverSeasonStatsQuery.execute({ leagueId });
setStandings(leagueStandings);
// Load all drivers for standings
// Load all drivers for standings and map to DTOs for UI components
const allDrivers = await driverRepo.findAll();
setDrivers(allDrivers);
const driverDtos: DriverDTO[] = allDrivers
.map((driver) => EntityMappers.toDriverDTO(driver))
.filter((dto): dto is DriverDTO => dto !== null);
setDrivers(driverDtos);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load league');
} finally {
@@ -74,34 +90,95 @@ export default function LeagueDetailPage() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [leagueId]);
if (loading) {
return (
<div className="text-center text-gray-400">Loading league...</div>
);
}
useEffect(() => {
const initialTab = searchParams?.get('tab');
if (!initialTab) {
return;
}
if (error || !league) {
return (
<Card className="text-center py-12">
<div className="text-warning-amber mb-4">
{error || 'League not found'}
</div>
<Button
variant="secondary"
onClick={() => router.push('/leagues')}
>
Back to Leagues
</Button>
</Card>
);
}
if (
initialTab === 'overview' ||
initialTab === 'schedule' ||
initialTab === 'standings' ||
initialTab === 'admin'
) {
setActiveTab(initialTab);
}
}, [searchParams]);
const handleMembershipChange = () => {
setRefreshKey(prev => prev + 1);
loadLeagueData();
};
return (
const driversById = useMemo(() => {
const map: Record<string, DriverDTO> = {};
for (const d of drivers) {
map[d.id] = d;
}
return map;
}, [drivers]);
const leagueMemberships = getLeagueMembers(leagueId);
const ownerMembership = leagueMemberships.find((m) => m.role === 'owner') ?? null;
const adminMemberships = leagueMemberships.filter((m) => m.role === 'admin');
const buildDriverSummary = (driverId: string) => {
const driverDto = driversById[driverId];
if (!driverDto) {
return null;
}
const stats = getDriverStats(driverDto.id);
const allRankings = getAllDriverRankings();
let rating: number | null = stats?.rating ?? null;
let rank: number | null = null;
if (stats) {
if (typeof stats.overallRank === 'number' && stats.overallRank > 0) {
rank = stats.overallRank;
} else {
const indexInGlobal = allRankings.findIndex(
(stat) => stat.driverId === stats.driverId,
);
if (indexInGlobal !== -1) {
rank = indexInGlobal + 1;
}
}
if (rating === null) {
const globalEntry = allRankings.find(
(stat) => stat.driverId === stats.driverId,
);
if (globalEntry) {
rating = globalEntry.rating;
}
}
}
return {
driver: driverDto,
rating,
rank,
};
};
return loading ? (
<div className="text-center text-gray-400">Loading league...</div>
) : error || !league ? (
<Card className="text-center py-12">
<div className="text-warning-amber mb-4">
{error || 'League not found'}
</div>
<Button
variant="secondary"
onClick={() => router.push('/leagues')}
>
Back to Leagues
</Button>
</Card>
) : (
<>
{/* Action Card */}
{!membership && (
@@ -154,16 +231,6 @@ export default function LeagueDetailPage() {
>
Standings
</button>
<button
onClick={() => setActiveTab('members')}
className={`px-3 py-1 text-xs font-medium rounded-full transition-colors ${
activeTab === 'members'
? 'bg-primary-blue text-white'
: 'text-gray-300 hover:text-white hover:bg-charcoal-outline/80'
}`}
>
Members
</button>
{isAdmin && (
<button
onClick={() => setActiveTab('admin')}
@@ -187,11 +254,6 @@ export default function LeagueDetailPage() {
<h2 className="text-xl font-semibold text-white mb-4">League Information</h2>
<div className="space-y-4">
<div>
<label className="text-sm text-gray-500">Owner</label>
<p className="text-white">{owner ? owner.name : `ID: ${league.ownerId.slice(0, 8)}...`}</p>
</div>
<div>
<label className="text-sm text-gray-500">Created</label>
<p className="text-white">
@@ -223,6 +285,107 @@ export default function LeagueDetailPage() {
</div>
</div>
</div>
{league.socialLinks && (
<div className="pt-4 border-t border-charcoal-outline">
<h3 className="text-white font-medium mb-3">Community & Social</h3>
<div className="flex flex-wrap gap-3 text-sm">
{league.socialLinks.discordUrl && (
<a
href={league.socialLinks.discordUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-full border border-primary-blue/40 bg-primary-blue/10 px-3 py-1 text-primary-blue hover:bg-primary-blue/20 transition-colors"
>
<span>Discord</span>
</a>
)}
{league.socialLinks.youtubeUrl && (
<a
href={league.socialLinks.youtubeUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-full border border-red-500/40 bg-red-500/10 px-3 py-1 text-red-400 hover:bg-red-500/20 transition-colors"
>
<span>YouTube</span>
</a>
)}
{league.socialLinks.websiteUrl && (
<a
href={league.socialLinks.websiteUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-full border border-charcoal-outline bg-iron-gray/70 px-3 py-1 text-gray-100 hover:bg-iron-gray transition-colors"
>
<span>Website</span>
</a>
)}
</div>
</div>
)}
<div className="pt-4 border-t border-charcoal-outline">
<h3 className="text-white font-medium mb-3">Management</h3>
<div className="space-y-4">
{ownerMembership && (
<div>
<label className="text-sm text-gray-500 block mb-2">Owner</label>
{buildDriverSummary(ownerMembership.driverId) ? (
<DriverSummaryPill
driver={buildDriverSummary(ownerMembership.driverId)!.driver}
rating={buildDriverSummary(ownerMembership.driverId)!.rating}
rank={buildDriverSummary(ownerMembership.driverId)!.rank}
/>
) : (
<p className="text-sm text-gray-500">
{owner ? owner.name : `ID: ${league.ownerId.slice(0, 8)}...`}
</p>
)}
</div>
)}
{adminMemberships.length > 0 && (
<div>
<label className="text-sm text-gray-500 block mb-2">Admins</label>
<div className="space-y-2">
{adminMemberships.map((membership) => {
const driverDto = driversById[membership.driverId];
const summary = buildDriverSummary(membership.driverId);
const meta =
summary && summary.rating !== null
? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
: null;
return (
<div
key={membership.driverId}
className="flex items-center justify-between gap-3"
>
{driverDto ? (
<DriverIdentity
driver={driverDto}
href={`/drivers/${membership.driverId}?from=league-management&leagueId=${leagueId}`}
contextLabel="Admin"
meta={meta}
size="sm"
/>
) : (
<span className="text-sm text-gray-400">Unknown admin</span>
)}
</div>
);
})}
</div>
</div>
)}
{adminMemberships.length === 0 && !ownerMembership && (
<p className="text-sm text-gray-500">
Management roles have not been configured for this league yet.
</p>
)}
</div>
</div>
</div>
</Card>
@@ -276,13 +439,6 @@ export default function LeagueDetailPage() {
</Card>
)}
{activeTab === 'members' && (
<Card>
<h2 className="text-xl font-semibold text-white mb-4">League Members</h2>
<LeagueMembers leagueId={leagueId} key={refreshKey} />
</Card>
)}
{activeTab === 'admin' && isAdmin && (
<LeagueAdmin
league={league}

View File

@@ -8,15 +8,17 @@ import FeatureLimitationTooltip from '@/components/alpha/FeatureLimitationToolti
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 { getRaceRepository, getLeagueRepository, getDriverRepository } from '@/lib/di-container';
import {
getMembership,
getCurrentDriverId,
isRegistered,
registerForRace,
withdrawFromRace,
getRegisteredDrivers,
} from '@/lib/racingLegacyFacade';
getRaceRepository,
getLeagueRepository,
getDriverRepository,
getGetRaceRegistrationsQuery,
getIsDriverRegisteredForRaceQuery,
getRegisterForRaceUseCase,
getWithdrawFromRaceUseCase,
} from '@/lib/di-container';
import { getMembership } from '@/lib/leagueMembership';
import { useEffectiveDriverId } from '@/lib/currentDriver';
import CompanionStatus from '@/components/alpha/CompanionStatus';
import CompanionInstructions from '@/components/alpha/CompanionInstructions';
@@ -36,7 +38,7 @@ export default function LeagueRaceDetailPage() {
const [isUserRegistered, setIsUserRegistered] = useState(false);
const [canRegister, setCanRegister] = useState(false);
const currentDriverId = getCurrentDriverId();
const currentDriverId = useEffectiveDriverId();
const loadRaceData = async () => {
try {
@@ -67,15 +69,19 @@ export default function LeagueRaceDetailPage() {
const loadEntryList = async (raceIdValue: string, leagueIdValue: string) => {
try {
const driverRepo = getDriverRepository();
const registeredDriverIds = getRegisteredDrivers(raceIdValue);
const drivers = await Promise.all(
registeredDriverIds.map((id: string) => driverRepo.findById(id))
);
setEntryList(
drivers.filter((d: Driver | null): d is Driver => d !== null)
);
const raceRegistrationsQuery = getGetRaceRegistrationsQuery();
const registeredDriverIds = await raceRegistrationsQuery.execute({ raceId: raceIdValue });
const userIsRegistered = isRegistered(raceIdValue, currentDriverId);
const drivers = await Promise.all(
registeredDriverIds.map((id: string) => driverRepo.findById(id)),
);
setEntryList(drivers.filter((d: Driver | null): d is Driver => d !== null));
const isRegisteredQuery = getIsDriverRegisteredForRaceQuery();
const userIsRegistered = await isRegisteredQuery.execute({
raceId: raceIdValue,
driverId: currentDriverId,
});
setIsUserRegistered(userIsRegistered);
const membership = getMembership(leagueIdValue, currentDriverId);
@@ -124,7 +130,12 @@ export default function LeagueRaceDetailPage() {
setRegistering(true);
try {
registerForRace(race.id, currentDriverId, league.id);
const useCase = getRegisterForRaceUseCase();
await useCase.execute({
raceId: race.id,
leagueId: league.id,
driverId: currentDriverId,
});
await loadEntryList(race.id, league.id);
} catch (err) {
alert(err instanceof Error ? err.message : 'Failed to register for race');
@@ -144,7 +155,11 @@ export default function LeagueRaceDetailPage() {
setRegistering(true);
try {
withdrawFromRace(race.id, currentDriverId);
const useCase = getWithdrawFromRaceUseCase();
await useCase.execute({
raceId: race.id,
driverId: currentDriverId,
});
await loadEntryList(race.id, league.id);
} catch (err) {
alert(err instanceof Error ? err.message : 'Failed to withdraw from race');

View File

@@ -3,29 +3,32 @@
import { useState, useEffect } from 'react';
import Card from '@/components/ui/Card';
import StandingsTable from '@/components/leagues/StandingsTable';
import type { Standing } from '@gridpilot/racing/domain/entities/Standing';
import type { Driver } from '@gridpilot/racing/domain/entities/Driver';
import { getStandingRepository, getDriverRepository } from '@/lib/di-container';
import type { DriverDTO } from '@gridpilot/racing/application/dto/DriverDTO';
import type { LeagueDriverSeasonStatsDTO } from '@gridpilot/racing/application/dto/LeagueDriverSeasonStatsDTO';
import { EntityMappers } from '@gridpilot/racing/application/mappers/EntityMappers';
import { getGetLeagueDriverSeasonStatsQuery, getDriverRepository } from '@/lib/di-container';
export default function LeagueStandingsPage({ params }: { params: { id: string } }) {
const leagueId = params.id;
const [standings, setStandings] = useState<Standing[]>([]);
const [drivers, setDrivers] = useState<Driver[]>([]);
const [standings, setStandings] = useState<LeagueDriverSeasonStatsDTO[]>([]);
const [drivers, setDrivers] = useState<DriverDTO[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const loadData = async () => {
try {
const standingRepo = getStandingRepository();
const getLeagueDriverSeasonStatsQuery = getGetLeagueDriverSeasonStatsQuery();
const driverRepo = getDriverRepository();
const allStandings = await standingRepo.findAll();
const leagueStandings = allStandings.filter((s) => s.leagueId === leagueId);
const leagueStandings = await getLeagueDriverSeasonStatsQuery.execute({ leagueId });
setStandings(leagueStandings);
const allDrivers = await driverRepo.findAll();
setDrivers(allDrivers);
const driverDtos: DriverDTO[] = allDrivers
.map((driver) => EntityMappers.toDriverDTO(driver))
.filter((dto): dto is DriverDTO => dto !== null);
setDrivers(driverDtos);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load standings');
} finally {

View File

@@ -7,12 +7,12 @@ import CreateLeagueForm from '@/components/leagues/CreateLeagueForm';
import Button from '@/components/ui/Button';
import Card from '@/components/ui/Card';
import Input from '@/components/ui/Input';
import { League } from '@gridpilot/racing/domain/entities/League';
import { getLeagueRepository } from '@/lib/di-container';
import type { LeagueDTO } from '@gridpilot/racing/application/dto/LeagueDTO';
import { getGetAllLeaguesWithCapacityQuery } from '@/lib/di-container';
export default function LeaguesPage() {
const router = useRouter();
const [leagues, setLeagues] = useState<League[]>([]);
const [leagues, setLeagues] = useState<LeagueDTO[]>([]);
const [loading, setLoading] = useState(true);
const [showCreateForm, setShowCreateForm] = useState(false);
const [searchQuery, setSearchQuery] = useState('');
@@ -24,8 +24,8 @@ export default function LeaguesPage() {
const loadLeagues = async () => {
try {
const leagueRepo = getLeagueRepository();
const allLeagues = await leagueRepo.findAll();
const query = getGetAllLeaguesWithCapacityQuery();
const allLeagues = await query.execute();
setLeagues(allLeagues);
} catch (error) {
console.error('Failed to load leagues:', error);