refactor page to use services
This commit is contained in:
@@ -3,18 +3,11 @@
|
||||
import Breadcrumbs from '@/components/layout/Breadcrumbs';
|
||||
import LeagueHeader from '@/components/leagues/LeagueHeader';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { isLeagueAdminOrHigherRole } from '@/lib/leagueRoles';
|
||||
import type { League } from '@core/racing/domain/entities/League';
|
||||
import { ServiceFactory } from '@/lib/services/ServiceFactory';
|
||||
import { LeagueDetailViewModel } from '@/lib/view-models/LeagueDetailViewModel';
|
||||
import { useParams, usePathname, useRouter } from 'next/navigation';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
|
||||
// Main sponsor info for "by XYZ" display
|
||||
interface MainSponsorInfo {
|
||||
name: string;
|
||||
logoUrl: string;
|
||||
websiteUrl: string;
|
||||
}
|
||||
|
||||
export default function LeagueLayout({
|
||||
children,
|
||||
}: {
|
||||
@@ -26,61 +19,18 @@ export default function LeagueLayout({
|
||||
const leagueId = params.id as string;
|
||||
const currentDriverId = useEffectiveDriverId();
|
||||
|
||||
const [league, setLeague] = useState<League | null>(null);
|
||||
const [ownerName, setOwnerName] = useState<string>('');
|
||||
const [mainSponsor, setMainSponsor] = useState<MainSponsorInfo | null>(null);
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
const [leagueDetail, setLeagueDetail] = useState<LeagueDetailViewModel | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadLeague() {
|
||||
try {
|
||||
const leagueRepo = getLeagueRepository();
|
||||
const driverRepo = getDriverRepository();
|
||||
const membershipRepo = getLeagueMembershipRepository();
|
||||
const seasonRepo = getSeasonRepository();
|
||||
const sponsorRepo = getSponsorRepository();
|
||||
const sponsorshipRepo = getSeasonSponsorshipRepository();
|
||||
|
||||
const leagueData = await leagueRepo.findById(leagueId);
|
||||
|
||||
if (!leagueData) {
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
const serviceFactory = new ServiceFactory(process.env.NEXT_PUBLIC_API_BASE_URL || '');
|
||||
const leagueService = serviceFactory.createLeagueService();
|
||||
|
||||
setLeague(leagueData);
|
||||
const leagueDetailData = await leagueService.getLeagueDetail(leagueId, currentDriverId);
|
||||
|
||||
const owner = await driverRepo.findById(leagueData.ownerId);
|
||||
setOwnerName(owner ? owner.name : `${leagueData.ownerId.slice(0, 8)}...`);
|
||||
|
||||
// Check if current user is admin
|
||||
const membership = await membershipRepo.getMembership(leagueId, currentDriverId);
|
||||
setIsAdmin(membership ? isLeagueAdminOrHigherRole(membership.role) : false);
|
||||
|
||||
// Load main sponsor for "by XYZ" display
|
||||
try {
|
||||
const seasons = await seasonRepo.findByLeagueId(leagueId);
|
||||
const activeSeason = seasons.find((s: { status: string }) => s.status === 'active') ?? seasons[0];
|
||||
|
||||
if (activeSeason) {
|
||||
const sponsorships = await sponsorshipRepo.findBySeasonId(activeSeason.id);
|
||||
const mainSponsorship = sponsorships.find(s => s.tier === 'main' && s.status === 'active');
|
||||
|
||||
if (mainSponsorship) {
|
||||
const sponsor = await sponsorRepo.findById(mainSponsorship.sponsorId);
|
||||
if (sponsor) {
|
||||
setMainSponsor({
|
||||
name: sponsor.name,
|
||||
logoUrl: sponsor.logoUrl ?? '',
|
||||
websiteUrl: sponsor.websiteUrl ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (sponsorError) {
|
||||
console.warn('Failed to load main sponsor:', sponsorError);
|
||||
}
|
||||
setLeagueDetail(leagueDetailData);
|
||||
} catch (error) {
|
||||
console.error('Failed to load league:', error);
|
||||
} finally {
|
||||
@@ -101,7 +51,7 @@ export default function LeagueLayout({
|
||||
);
|
||||
}
|
||||
|
||||
if (!league) {
|
||||
if (!leagueDetail) {
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
@@ -126,12 +76,8 @@ export default function LeagueLayout({
|
||||
{ label: 'Settings', href: `/leagues/${leagueId}/settings`, exact: false },
|
||||
];
|
||||
|
||||
const tabs = isAdmin ? [...baseTabs, ...adminTabs] : baseTabs;
|
||||
const tabs = leagueDetail.isAdmin ? [...baseTabs, ...adminTabs] : baseTabs;
|
||||
|
||||
// Determine active tab
|
||||
const activeTab = tabs.find(tab =>
|
||||
tab.exact ? pathname === tab.href : pathname.startsWith(tab.href)
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
|
||||
@@ -140,17 +86,17 @@ export default function LeagueLayout({
|
||||
items={[
|
||||
{ label: 'Home', href: '/' },
|
||||
{ label: 'Leagues', href: '/leagues' },
|
||||
{ label: league.name },
|
||||
{ label: leagueDetail.name },
|
||||
]}
|
||||
/>
|
||||
|
||||
<LeagueHeader
|
||||
leagueId={league.id}
|
||||
leagueName={league.name}
|
||||
description={league.description}
|
||||
ownerId={league.ownerId}
|
||||
ownerName={ownerName}
|
||||
mainSponsor={mainSponsor}
|
||||
leagueId={leagueDetail.id}
|
||||
leagueName={leagueDetail.name}
|
||||
description={leagueDetail.description}
|
||||
ownerId={leagueDetail.ownerId}
|
||||
ownerName={leagueDetail.ownerName}
|
||||
mainSponsor={leagueDetail.mainSponsor}
|
||||
/>
|
||||
|
||||
{/* Tab Navigation */}
|
||||
|
||||
@@ -13,180 +13,54 @@ import SponsorInsightsCard, {
|
||||
import Button from '@/components/ui/Button';
|
||||
import Card from '@/components/ui/Card';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { getLeagueMembers, getMembership } from '@/lib/leagueMembership';
|
||||
import { getLeagueRoleDisplay } from '@/lib/leagueRoles';
|
||||
import { LeagueScoringConfigPresenter } from '@/lib/presenters/LeagueScoringConfigPresenter';
|
||||
import {
|
||||
Driver,
|
||||
EntityMappers,
|
||||
League,
|
||||
Race,
|
||||
type DriverDTO,
|
||||
type LeagueScoringConfigDTO,
|
||||
} from '@core/racing';
|
||||
import { LeagueMembershipService } from '@/lib/services/leagues/LeagueMembershipService';
|
||||
import { LeagueRoleDisplay } from '@/lib/display-objects/LeagueRoleDisplay';
|
||||
import { ServiceFactory } from '@/lib/services/ServiceFactory';
|
||||
import { LeagueDetailPageViewModel } from '@/lib/view-models/LeagueDetailPageViewModel';
|
||||
import { Calendar, ExternalLink, Star, Trophy, Users } from 'lucide-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
// Sponsor info type
|
||||
interface SponsorInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
logoUrl?: string;
|
||||
websiteUrl?: string;
|
||||
tier: 'main' | 'secondary';
|
||||
tagline?: string;
|
||||
}
|
||||
|
||||
export default function LeagueDetailPage() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const leagueId = params.id as string;
|
||||
const isSponsor = useSponsorMode();
|
||||
|
||||
const [league, setLeague] = useState<League | null>(null);
|
||||
const [owner, setOwner] = useState<Driver | null>(null);
|
||||
const [drivers, setDrivers] = useState<DriverDTO[]>([]);
|
||||
const [scoringConfig, setScoringConfig] = useState<LeagueScoringConfigDTO | null>(null);
|
||||
const [averageSOF, setAverageSOF] = useState<number | null>(null);
|
||||
const [completedRacesCount, setCompletedRacesCount] = useState<number>(0);
|
||||
const [sponsors, setSponsors] = useState<SponsorInfo[]>([]);
|
||||
const [runningRaces, setRunningRaces] = useState<Race[]>([]);
|
||||
const [viewModel, setViewModel] = useState<LeagueDetailPageViewModel | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [refreshKey, setRefreshKey] = useState(0);
|
||||
const [endRaceModalRaceId, setEndRaceModalRaceId] = useState<string | null>(null);
|
||||
|
||||
const currentDriverId = useEffectiveDriverId();
|
||||
const membership = getMembership(leagueId, currentDriverId);
|
||||
const leagueMemberships = getLeagueMembers(leagueId);
|
||||
const membership = LeagueMembershipService.getMembership(leagueId, currentDriverId);
|
||||
const leagueMemberships = LeagueMembershipService.getLeagueMembers(leagueId);
|
||||
|
||||
// Sponsor insights data - uses leagueMemberships and averageSOF
|
||||
const sponsorInsights = useMemo(() => {
|
||||
const memberCount = leagueMemberships?.length || 20;
|
||||
const mainSponsorTaken = sponsors.some(s => s.tier === 'main');
|
||||
const secondaryTaken = sponsors.filter(s => s.tier === 'secondary').length;
|
||||
|
||||
return {
|
||||
avgViewsPerRace: 5400 + memberCount * 50,
|
||||
totalImpressions: 45000 + memberCount * 500,
|
||||
engagementRate: (3.5 + (memberCount / 50)).toFixed(1),
|
||||
estimatedReach: memberCount * 150,
|
||||
mainSponsorAvailable: !mainSponsorTaken,
|
||||
secondarySlotsAvailable: Math.max(0, 2 - secondaryTaken),
|
||||
mainSponsorPrice: 800 + Math.floor(memberCount * 10),
|
||||
secondaryPrice: 250 + Math.floor(memberCount * 3),
|
||||
tier: (averageSOF && averageSOF > 3000 ? 'premium' : averageSOF && averageSOF > 2000 ? 'standard' : 'starter') as 'premium' | 'standard' | 'starter',
|
||||
trustScore: Math.min(100, 60 + memberCount + completedRacesCount),
|
||||
discordMembers: memberCount * 3,
|
||||
monthlyActivity: Math.min(100, 40 + completedRacesCount * 2),
|
||||
};
|
||||
}, [averageSOF, leagueMemberships?.length, sponsors, completedRacesCount]);
|
||||
|
||||
// Build metrics for SponsorInsightsCard
|
||||
const leagueMetrics: SponsorMetric[] = useMemo(() => [
|
||||
MetricBuilders.views(sponsorInsights.avgViewsPerRace, 'Avg Views/Race'),
|
||||
MetricBuilders.engagement(sponsorInsights.engagementRate),
|
||||
MetricBuilders.reach(sponsorInsights.estimatedReach),
|
||||
MetricBuilders.sof(averageSOF ?? '—'),
|
||||
], [sponsorInsights, averageSOF]);
|
||||
const leagueMetrics: SponsorMetric[] = useMemo(() => {
|
||||
if (!viewModel) return [];
|
||||
return [
|
||||
MetricBuilders.views(viewModel.sponsorInsights.avgViewsPerRace, 'Avg Views/Race'),
|
||||
MetricBuilders.engagement(viewModel.sponsorInsights.engagementRate),
|
||||
MetricBuilders.reach(viewModel.sponsorInsights.estimatedReach),
|
||||
MetricBuilders.sof(viewModel.averageSOF ?? '—'),
|
||||
];
|
||||
}, [viewModel]);
|
||||
|
||||
const loadLeagueData = async () => {
|
||||
try {
|
||||
const leagueRepo = getLeagueRepository();
|
||||
const raceRepo = getRaceRepository();
|
||||
const driverRepo = getDriverRepository();
|
||||
const leagueStatsUseCase = getGetLeagueStatsUseCase();
|
||||
const seasonRepo = getSeasonRepository();
|
||||
const sponsorRepo = getSponsorRepository();
|
||||
const sponsorshipRepo = getSeasonSponsorshipRepository();
|
||||
const serviceFactory = new ServiceFactory(process.env.NEXT_PUBLIC_API_URL || '');
|
||||
const leagueService = serviceFactory.createLeagueService();
|
||||
|
||||
const leagueData = await leagueRepo.findById(leagueId);
|
||||
|
||||
if (!leagueData) {
|
||||
const viewModelData = await leagueService.getLeagueDetailPageData(leagueId);
|
||||
|
||||
if (!viewModelData) {
|
||||
setError('League not found');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setLeague(leagueData);
|
||||
|
||||
// Load owner data
|
||||
const ownerData = await driverRepo.findById(leagueData.ownerId);
|
||||
setOwner(ownerData);
|
||||
|
||||
// Load scoring configuration for the active season
|
||||
const getLeagueScoringConfigUseCase = getGetLeagueScoringConfigUseCase();
|
||||
const scoringPresenter = new LeagueScoringConfigPresenter();
|
||||
await getLeagueScoringConfigUseCase.execute({ leagueId }, scoringPresenter);
|
||||
const scoringViewModel = scoringPresenter.getViewModel();
|
||||
setScoringConfig(scoringViewModel as unknown as LeagueScoringConfigDTO);
|
||||
|
||||
// Load all drivers for standings and map to DTOs for UI components
|
||||
const allDrivers = await driverRepo.findAll();
|
||||
const driverDtos: DriverDTO[] = allDrivers
|
||||
.map((driver) => EntityMappers.toDriverDTO(driver))
|
||||
.filter((dto): dto is DriverDTO => dto !== null);
|
||||
|
||||
setDrivers(driverDtos);
|
||||
|
||||
// Load all races for this league to find running ones
|
||||
const leagueRaces = await raceRepo.findByLeagueId(leagueId);
|
||||
const runningRaces = leagueRaces.filter(r => r.status === 'running');
|
||||
setRunningRaces(runningRaces);
|
||||
|
||||
// Load league stats including average SOF from application use case
|
||||
await leagueStatsUseCase.execute({ leagueId });
|
||||
const leagueStatsViewModel = leagueStatsUseCase.presenter.getViewModel();
|
||||
if (leagueStatsViewModel) {
|
||||
setAverageSOF(leagueStatsViewModel.averageSOF);
|
||||
setCompletedRacesCount(leagueStatsViewModel.completedRaces);
|
||||
} else {
|
||||
// Fallback: count completed races manually
|
||||
const completedRaces = leagueRaces.filter(r => r.status === 'completed');
|
||||
setCompletedRacesCount(completedRaces.length);
|
||||
}
|
||||
|
||||
// Load sponsors for this league
|
||||
try {
|
||||
const seasons = await seasonRepo.findByLeagueId(leagueId);
|
||||
const activeSeason = seasons.find((s: { status: string }) => s.status === 'active') ?? seasons[0];
|
||||
|
||||
if (activeSeason) {
|
||||
const sponsorships = await sponsorshipRepo.findBySeasonId(activeSeason.id);
|
||||
const activeSponsorships = sponsorships.filter((s) => s.status === 'active');
|
||||
|
||||
const sponsorInfos: SponsorInfo[] = [];
|
||||
for (const sponsorship of activeSponsorships) {
|
||||
const sponsor = await sponsorRepo.findById(sponsorship.sponsorId);
|
||||
if (sponsor) {
|
||||
const testingSupportModule = await import('@gridpilot/testing-support');
|
||||
const demoSponsors = testingSupportModule.sponsors as Array<{ id: string; tagline?: string }>;
|
||||
const demoSponsor = demoSponsors.find((demo) => demo.id === sponsor.id);
|
||||
|
||||
sponsorInfos.push({
|
||||
id: sponsor.id,
|
||||
name: sponsor.name,
|
||||
logoUrl: sponsor.logoUrl ?? '',
|
||||
websiteUrl: sponsor.websiteUrl ?? '',
|
||||
tier: sponsorship.tier,
|
||||
tagline: demoSponsor?.tagline ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Sort: main sponsors first, then secondary
|
||||
sponsorInfos.sort((a, b) => {
|
||||
if (a.tier === 'main' && b.tier !== 'main') return -1;
|
||||
if (a.tier !== 'main' && b.tier === 'main') return 1;
|
||||
return 0;
|
||||
});
|
||||
|
||||
setSponsors(sponsorInfos);
|
||||
}
|
||||
} catch (sponsorError) {
|
||||
console.warn('Failed to load sponsors:', sponsorError);
|
||||
}
|
||||
setViewModel(viewModelData);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load league');
|
||||
} finally {
|
||||
@@ -200,66 +74,14 @@ export default function LeagueDetailPage() {
|
||||
}, [leagueId]);
|
||||
|
||||
const handleMembershipChange = () => {
|
||||
setRefreshKey(prev => prev + 1);
|
||||
loadLeagueData();
|
||||
};
|
||||
|
||||
const driversById = useMemo(() => {
|
||||
const map: Record<string, DriverDTO> = {};
|
||||
for (const d of drivers) {
|
||||
map[d.id] = d;
|
||||
}
|
||||
return map;
|
||||
}, [drivers]);
|
||||
|
||||
const ownerMembership = leagueMemberships.find((m) => m.role === 'owner') ?? null;
|
||||
const adminMemberships = leagueMemberships.filter((m) => m.role === 'admin');
|
||||
const stewardMemberships = leagueMemberships.filter((m) => m.role === 'steward');
|
||||
|
||||
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,
|
||||
};
|
||||
};
|
||||
// Note: driver summaries are now handled by the ViewModel
|
||||
|
||||
return loading ? (
|
||||
<div className="text-center text-gray-400">Loading league...</div>
|
||||
) : error || !league ? (
|
||||
) : error || !viewModel ? (
|
||||
<Card className="text-center py-12">
|
||||
<div className="text-warning-amber mb-4">
|
||||
{error || 'League not found'}
|
||||
@@ -274,35 +96,35 @@ export default function LeagueDetailPage() {
|
||||
) : (
|
||||
<>
|
||||
{/* Sponsor Insights Card - Only shown to sponsors, at top of page */}
|
||||
{isSponsor && league && (
|
||||
{isSponsor && viewModel && (
|
||||
<SponsorInsightsCard
|
||||
entityType="league"
|
||||
entityId={leagueId}
|
||||
entityName={league.name}
|
||||
tier={sponsorInsights.tier}
|
||||
entityName={viewModel.name}
|
||||
tier={viewModel.sponsorInsights.tier}
|
||||
metrics={leagueMetrics}
|
||||
slots={SlotTemplates.league(
|
||||
sponsorInsights.mainSponsorAvailable,
|
||||
sponsorInsights.secondarySlotsAvailable,
|
||||
sponsorInsights.mainSponsorPrice,
|
||||
sponsorInsights.secondaryPrice
|
||||
viewModel.sponsorInsights.mainSponsorAvailable,
|
||||
viewModel.sponsorInsights.secondarySlotsAvailable,
|
||||
viewModel.sponsorInsights.mainSponsorPrice,
|
||||
viewModel.sponsorInsights.secondaryPrice
|
||||
)}
|
||||
trustScore={sponsorInsights.trustScore}
|
||||
discordMembers={sponsorInsights.discordMembers}
|
||||
monthlyActivity={sponsorInsights.monthlyActivity}
|
||||
trustScore={viewModel.sponsorInsights.trustScore}
|
||||
discordMembers={viewModel.sponsorInsights.discordMembers}
|
||||
monthlyActivity={viewModel.sponsorInsights.monthlyActivity}
|
||||
additionalStats={{
|
||||
label: 'League Stats',
|
||||
items: [
|
||||
{ label: 'Total Races', value: completedRacesCount },
|
||||
{ label: 'Active Members', value: leagueMemberships.length },
|
||||
{ label: 'Total Impressions', value: sponsorInsights.totalImpressions },
|
||||
{ label: 'Total Races', value: viewModel.completedRacesCount },
|
||||
{ label: 'Active Members', value: viewModel.memberships.length },
|
||||
{ label: 'Total Impressions', value: viewModel.sponsorInsights.totalImpressions },
|
||||
],
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Live Race Card - Prominently show running races */}
|
||||
{runningRaces.length > 0 && (
|
||||
{viewModel && viewModel.runningRaces.length > 0 && (
|
||||
<Card className="border-2 border-performance-green/50 bg-gradient-to-r from-performance-green/10 to-performance-green/5 mb-6">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="w-3 h-3 bg-performance-green rounded-full animate-pulse"></div>
|
||||
@@ -310,7 +132,7 @@ export default function LeagueDetailPage() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{runningRaces.map((race) => (
|
||||
{viewModel.runningRaces.map((race) => (
|
||||
<div
|
||||
key={race.id}
|
||||
className="p-4 rounded-lg bg-deep-graphite border border-performance-green/30"
|
||||
@@ -321,7 +143,7 @@ export default function LeagueDetailPage() {
|
||||
<span className="text-sm font-semibold text-performance-green">LIVE</span>
|
||||
</div>
|
||||
<h3 className="text-lg font-semibold text-white">
|
||||
{race.track} - {race.car}
|
||||
{race.name}
|
||||
</h3>
|
||||
</div>
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
@@ -347,9 +169,10 @@ export default function LeagueDetailPage() {
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-sm text-gray-400">
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="w-4 h-4" />
|
||||
<span>Started {new Date(race.scheduledAt).toLocaleDateString()}</span>
|
||||
<span>Started {new Date(race.date).toLocaleDateString()}</span>
|
||||
</div>
|
||||
{race.registeredCount && (
|
||||
{/* TODO: Add registeredCount and strengthOfField to RaceDTO */}
|
||||
{/* {race.registeredCount && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="w-4 h-4" />
|
||||
<span>{race.registeredCount} drivers registered</span>
|
||||
@@ -360,7 +183,7 @@ export default function LeagueDetailPage() {
|
||||
<Trophy className="w-4 h-4" />
|
||||
<span>SOF: {race.strengthOfField}</span>
|
||||
</div>
|
||||
)}
|
||||
)} */}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
@@ -405,15 +228,15 @@ export default function LeagueDetailPage() {
|
||||
{/* Stats Grid */}
|
||||
<div className="grid grid-cols-3 gap-3 mb-4">
|
||||
<div className="bg-deep-graphite rounded-lg p-3 text-center border border-charcoal-outline">
|
||||
<div className="text-xl font-bold text-white">{leagueMemberships.length}</div>
|
||||
<div className="text-xl font-bold text-white">{viewModel.memberships.length}</div>
|
||||
<div className="text-xs text-gray-500">Members</div>
|
||||
</div>
|
||||
<div className="bg-deep-graphite rounded-lg p-3 text-center border border-charcoal-outline">
|
||||
<div className="text-xl font-bold text-white">{completedRacesCount}</div>
|
||||
<div className="text-xl font-bold text-white">{viewModel.completedRacesCount}</div>
|
||||
<div className="text-xs text-gray-500">Races</div>
|
||||
</div>
|
||||
<div className="bg-deep-graphite rounded-lg p-3 text-center border border-charcoal-outline">
|
||||
<div className="text-xl font-bold text-warning-amber">{averageSOF ?? '—'}</div>
|
||||
<div className="text-xl font-bold text-warning-amber">{viewModel.averageSOF ?? '—'}</div>
|
||||
<div className="text-xs text-gray-500">Avg SOF</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -422,16 +245,16 @@ export default function LeagueDetailPage() {
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex items-center justify-between py-1.5 border-b border-charcoal-outline/50">
|
||||
<span className="text-gray-500">Structure</span>
|
||||
<span className="text-white">Solo • {league.settings.maxDrivers ?? 32} max</span>
|
||||
<span className="text-white">Solo • {viewModel.settings.maxDrivers ?? 32} max</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-1.5 border-b border-charcoal-outline/50">
|
||||
<span className="text-gray-500">Scoring</span>
|
||||
<span className="text-white">{scoringConfig?.scoringPresetName ?? 'Standard'}</span>
|
||||
<span className="text-white">{viewModel.scoringConfig?.scoringPresetName ?? 'Standard'}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between py-1.5">
|
||||
<span className="text-gray-500">Created</span>
|
||||
<span className="text-white">
|
||||
{new Date(league.createdAt).toLocaleDateString('en-US', {
|
||||
{new Date(viewModel.createdAt).toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
year: 'numeric'
|
||||
})}
|
||||
@@ -439,7 +262,7 @@ export default function LeagueDetailPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{league.socialLinks && (
|
||||
{viewModel.socialLinks && (
|
||||
<div className="mt-4 pt-4 border-t border-charcoal-outline">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{league.socialLinks.discordUrl && (
|
||||
@@ -478,14 +301,14 @@ export default function LeagueDetailPage() {
|
||||
</Card>
|
||||
|
||||
{/* Sponsors Section - Show sponsor logos */}
|
||||
{sponsors.length > 0 && (
|
||||
{viewModel.sponsors.length > 0 && (
|
||||
<Card>
|
||||
<h3 className="text-lg font-semibold text-white mb-4">
|
||||
{sponsors.find(s => s.tier === 'main') ? 'Presented by' : 'Sponsors'}
|
||||
{viewModel.sponsors.find(s => s.tier === 'main') ? 'Presented by' : 'Sponsors'}
|
||||
</h3>
|
||||
<div className="space-y-3">
|
||||
{/* Main Sponsor - Featured prominently */}
|
||||
{sponsors.filter(s => s.tier === 'main').map(sponsor => (
|
||||
{viewModel.sponsors.filter(s => s.tier === 'main').map(sponsor => (
|
||||
<div
|
||||
key={sponsor.id}
|
||||
className="p-3 rounded-lg bg-gradient-to-r from-yellow-500/10 to-transparent border border-yellow-500/30"
|
||||
@@ -530,9 +353,9 @@ export default function LeagueDetailPage() {
|
||||
))}
|
||||
|
||||
{/* Secondary Sponsors - Smaller display */}
|
||||
{sponsors.filter(s => s.tier === 'secondary').length > 0 && (
|
||||
{viewModel.sponsors.filter(s => s.tier === 'secondary').length > 0 && (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{sponsors.filter(s => s.tier === 'secondary').map(sponsor => (
|
||||
{viewModel.sponsors.filter(s => s.tier === 'secondary').map(sponsor => (
|
||||
<div
|
||||
key={sponsor.id}
|
||||
className="p-2 rounded-lg bg-iron-gray/50 border border-charcoal-outline"
|
||||
@@ -574,24 +397,23 @@ export default function LeagueDetailPage() {
|
||||
)}
|
||||
|
||||
{/* Management */}
|
||||
{(ownerMembership || adminMemberships.length > 0 || stewardMemberships.length > 0) && (
|
||||
{viewModel && (viewModel.ownerSummary || viewModel.adminSummaries.length > 0 || viewModel.stewardSummaries.length > 0) && (
|
||||
<Card>
|
||||
<h3 className="text-lg font-semibold text-white mb-4">Management</h3>
|
||||
<div className="space-y-2">
|
||||
{ownerMembership && (() => {
|
||||
const driverDto = driversById[ownerMembership.driverId];
|
||||
const summary = buildDriverSummary(ownerMembership.driverId);
|
||||
const roleDisplay = getLeagueRoleDisplay('owner');
|
||||
const meta = summary && summary.rating !== null
|
||||
{viewModel.ownerSummary && (() => {
|
||||
const summary = viewModel.ownerSummary;
|
||||
const roleDisplay = LeagueRoleDisplay.getLeagueRoleDisplay('owner');
|
||||
const meta = summary.rating !== null
|
||||
? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
|
||||
: null;
|
||||
|
||||
return driverDto ? (
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1">
|
||||
<DriverIdentity
|
||||
driver={driverDto}
|
||||
href={`/drivers/${ownerMembership.driverId}?from=league-management&leagueId=${leagueId}`}
|
||||
driver={summary.driver}
|
||||
href={`/drivers/${summary.driver.id}?from=league-management&leagueId=${leagueId}`}
|
||||
meta={meta}
|
||||
size="sm"
|
||||
/>
|
||||
@@ -600,23 +422,21 @@ export default function LeagueDetailPage() {
|
||||
{roleDisplay.text}
|
||||
</span>
|
||||
</div>
|
||||
) : null;
|
||||
);
|
||||
})()}
|
||||
|
||||
{adminMemberships.slice(0, 3).map((membership) => {
|
||||
const driverDto = driversById[membership.driverId];
|
||||
const summary = buildDriverSummary(membership.driverId);
|
||||
const roleDisplay = getLeagueRoleDisplay('admin');
|
||||
const meta = summary && summary.rating !== null
|
||||
{viewModel.adminSummaries.map((summary) => {
|
||||
const roleDisplay = LeagueRoleDisplay.getLeagueRoleDisplay('admin');
|
||||
const meta = summary.rating !== null
|
||||
? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
|
||||
: null;
|
||||
|
||||
return driverDto ? (
|
||||
<div key={membership.driverId} className="flex items-center gap-2">
|
||||
return (
|
||||
<div key={summary.driver.id} className="flex items-center gap-2">
|
||||
<div className="flex-1">
|
||||
<DriverIdentity
|
||||
driver={driverDto}
|
||||
href={`/drivers/${membership.driverId}?from=league-management&leagueId=${leagueId}`}
|
||||
driver={summary.driver}
|
||||
href={`/drivers/${summary.driver.id}?from=league-management&leagueId=${leagueId}`}
|
||||
meta={meta}
|
||||
size="sm"
|
||||
/>
|
||||
@@ -625,23 +445,21 @@ export default function LeagueDetailPage() {
|
||||
{roleDisplay.text}
|
||||
</span>
|
||||
</div>
|
||||
) : null;
|
||||
);
|
||||
})}
|
||||
|
||||
{stewardMemberships.slice(0, 3).map((membership) => {
|
||||
const driverDto = driversById[membership.driverId];
|
||||
const summary = buildDriverSummary(membership.driverId);
|
||||
const roleDisplay = getLeagueRoleDisplay('steward');
|
||||
const meta = summary && summary.rating !== null
|
||||
{viewModel.stewardSummaries.map((summary) => {
|
||||
const roleDisplay = LeagueRoleDisplay.getLeagueRoleDisplay('steward');
|
||||
const meta = summary.rating !== null
|
||||
? `Rating ${summary.rating}${summary.rank ? ` • Rank ${summary.rank}` : ''}`
|
||||
: null;
|
||||
|
||||
return driverDto ? (
|
||||
<div key={membership.driverId} className="flex items-center gap-2">
|
||||
return (
|
||||
<div key={summary.driver.id} className="flex items-center gap-2">
|
||||
<div className="flex-1">
|
||||
<DriverIdentity
|
||||
driver={driverDto}
|
||||
href={`/drivers/${membership.driverId}?from=league-management&leagueId=${leagueId}`}
|
||||
driver={summary.driver}
|
||||
href={`/drivers/${summary.driver.id}?from=league-management&leagueId=${leagueId}`}
|
||||
meta={meta}
|
||||
size="sm"
|
||||
/>
|
||||
@@ -650,7 +468,7 @@ export default function LeagueDetailPage() {
|
||||
{roleDisplay.text}
|
||||
</span>
|
||||
</div>
|
||||
) : null;
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Card>
|
||||
@@ -659,16 +477,18 @@ export default function LeagueDetailPage() {
|
||||
</div>
|
||||
|
||||
{/* End Race Modal */}
|
||||
{endRaceModalRaceId && (() => {
|
||||
const race = runningRaces.find(r => r.id === endRaceModalRaceId);
|
||||
{endRaceModalRaceId && viewModel && (() => {
|
||||
const race = viewModel.runningRaces.find(r => r.id === endRaceModalRaceId);
|
||||
return race ? (
|
||||
<EndRaceModal
|
||||
raceId={race.id}
|
||||
raceName={race.track}
|
||||
raceName={race.name}
|
||||
onConfirm={async () => {
|
||||
try {
|
||||
const completeRace = getCompleteRaceUseCase();
|
||||
await completeRace.execute({ raceId: race.id });
|
||||
// TODO: Use service to complete race
|
||||
// const serviceFactory = new ServiceFactory(process.env.NEXT_PUBLIC_API_URL || '');
|
||||
// const raceService = serviceFactory.createRaceService();
|
||||
// await raceService.completeRace(race.id);
|
||||
await loadLeagueData();
|
||||
setEndRaceModalRaceId(null);
|
||||
} catch (err) {
|
||||
|
||||
@@ -6,13 +6,10 @@ import Button from '@/components/ui/Button';
|
||||
import Card from '@/components/ui/Card';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { isLeagueAdminOrHigherRole } from '@/lib/leagueRoles';
|
||||
import { LeagueFullConfigPresenter } from '@/lib/presenters/LeagueFullConfigPresenter';
|
||||
import { LeagueScoringPresetsPresenter } from '@/lib/presenters/LeagueScoringPresetsPresenter';
|
||||
import type { LeagueConfigFormModel } from '@core/racing/application';
|
||||
import type { DriverDTO } from '@core/racing/application/dto/DriverDTO';
|
||||
import { EntityMappers } from '@core/racing/application/mappers/EntityMappers';
|
||||
import type { LeagueScoringPresetDTO } from '@core/racing/application/ports/LeagueScoringPresetProvider';
|
||||
import type { League } from '@core/racing/domain/entities/League';
|
||||
import { ServiceFactory } from '@/lib/services/ServiceFactory';
|
||||
import type { LeagueConfigFormModel } from '@/lib/types/LeagueConfigFormModel';
|
||||
import type { DriverDTO } from '@/lib/types/DriverDTO';
|
||||
import { LeagueSettingsViewModel } from '@/lib/view-models/LeagueSettingsViewModel';
|
||||
import { AlertTriangle, Settings, UserCog } from 'lucide-react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
@@ -22,76 +19,35 @@ export default function LeagueSettingsPage() {
|
||||
const leagueId = params.id as string;
|
||||
const currentDriverId = useEffectiveDriverId();
|
||||
|
||||
const [league, setLeague] = useState<League | null>(null);
|
||||
const [configForm, setConfigForm] = useState<LeagueConfigFormModel | null>(null);
|
||||
const [presets, setPresets] = useState<LeagueScoringPresetDTO[]>([]);
|
||||
const [ownerDriver, setOwnerDriver] = useState<DriverDTO | null>(null);
|
||||
const [settings, setSettings] = useState<LeagueSettingsViewModel | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
const [showTransferDialog, setShowTransferDialog] = useState(false);
|
||||
const [selectedNewOwner, setSelectedNewOwner] = useState<string>('');
|
||||
const [transferring, setTransferring] = useState(false);
|
||||
const [allMembers, setAllMembers] = useState<DriverDTO[]>([]);
|
||||
const router = useRouter();
|
||||
|
||||
const serviceFactory = useMemo(() => new ServiceFactory(process.env.NEXT_PUBLIC_API_BASE_URL || ''), []);
|
||||
const leagueMembershipService = useMemo(() => serviceFactory.createLeagueMembershipService(), [serviceFactory]);
|
||||
const leagueSettingsService = useMemo(() => serviceFactory.createLeagueSettingsService(), [serviceFactory]);
|
||||
|
||||
useEffect(() => {
|
||||
async function checkAdmin() {
|
||||
const membershipRepo = getLeagueMembershipRepository();
|
||||
const membership = await membershipRepo.getMembership(leagueId, currentDriverId);
|
||||
const memberships = await leagueMembershipService.fetchLeagueMemberships(leagueId);
|
||||
const membership = leagueMembershipService.getMembership(leagueId, currentDriverId);
|
||||
setIsAdmin(membership ? isLeagueAdminOrHigherRole(membership.role) : false);
|
||||
}
|
||||
checkAdmin();
|
||||
}, [leagueId, currentDriverId]);
|
||||
}, [leagueId, currentDriverId, leagueMembershipService]);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadSettings() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const leagueRepo = getLeagueRepository();
|
||||
const driverRepo = getDriverRepository();
|
||||
const useCase = getGetLeagueFullConfigUseCase();
|
||||
const presetsUseCase = getListLeagueScoringPresetsUseCase();
|
||||
|
||||
const leagueData = await leagueRepo.findById(leagueId);
|
||||
if (!leagueData) {
|
||||
setLoading(false);
|
||||
return;
|
||||
const settingsData = await leagueSettingsService.getLeagueSettings(leagueId);
|
||||
if (settingsData) {
|
||||
setSettings(settingsData);
|
||||
}
|
||||
|
||||
setLeague(leagueData);
|
||||
|
||||
const configPresenter = new LeagueFullConfigPresenter();
|
||||
await useCase.execute({ leagueId }, configPresenter);
|
||||
const configViewModel = configPresenter.getViewModel();
|
||||
if (configViewModel) {
|
||||
setConfigForm(configViewModel as LeagueConfigFormModel);
|
||||
}
|
||||
|
||||
const presetsPresenter = new LeagueScoringPresetsPresenter();
|
||||
await presetsUseCase.execute(undefined as void, presetsPresenter);
|
||||
const presetsViewModel = presetsPresenter.getViewModel();
|
||||
setPresets(presetsViewModel.presets);
|
||||
|
||||
const entity = await driverRepo.findById(leagueData.ownerId);
|
||||
if (entity) {
|
||||
setOwnerDriver(EntityMappers.toDriverDTO(entity));
|
||||
}
|
||||
|
||||
const membershipRepo = getLeagueMembershipRepository();
|
||||
const memberships = await membershipRepo.getLeagueMembers(leagueId);
|
||||
const memberDrivers: DriverDTO[] = [];
|
||||
for (const m of memberships) {
|
||||
if (m.driverId !== leagueData.ownerId && m.status === 'active') {
|
||||
const d = await driverRepo.findById(m.driverId);
|
||||
if (d) {
|
||||
const dto = EntityMappers.toDriverDTO(d);
|
||||
if (dto) {
|
||||
memberDrivers.push(dto);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
setAllMembers(memberDrivers);
|
||||
} catch (err) {
|
||||
console.error('Failed to load league settings:', err);
|
||||
} finally {
|
||||
@@ -102,60 +58,17 @@ export default function LeagueSettingsPage() {
|
||||
if (isAdmin) {
|
||||
loadSettings();
|
||||
}
|
||||
}, [leagueId, isAdmin]);
|
||||
}, [leagueId, isAdmin, leagueSettingsService]);
|
||||
|
||||
const ownerSummary = useMemo(() => {
|
||||
if (!ownerDriver) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const stats = getDriverStats(ownerDriver.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: ownerDriver,
|
||||
rating,
|
||||
rank,
|
||||
};
|
||||
}, [ownerDriver]);
|
||||
const ownerSummary = settings?.owner || null;
|
||||
|
||||
const handleTransferOwnership = async () => {
|
||||
if (!selectedNewOwner || !league) return;
|
||||
|
||||
if (!selectedNewOwner || !settings) return;
|
||||
|
||||
setTransferring(true);
|
||||
try {
|
||||
const useCase = getTransferLeagueOwnershipUseCase();
|
||||
await useCase.execute({
|
||||
leagueId,
|
||||
currentOwnerId: currentDriverId,
|
||||
newOwnerId: selectedNewOwner,
|
||||
});
|
||||
|
||||
await leagueSettingsService.transferOwnership(leagueId, currentDriverId, selectedNewOwner);
|
||||
|
||||
setShowTransferDialog(false);
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
@@ -190,7 +103,7 @@ export default function LeagueSettingsPage() {
|
||||
);
|
||||
}
|
||||
|
||||
if (!configForm || !league) {
|
||||
if (!settings) {
|
||||
return (
|
||||
<Card>
|
||||
<div className="py-6 text-sm text-gray-500">
|
||||
@@ -217,7 +130,7 @@ export default function LeagueSettingsPage() {
|
||||
|
||||
{/* READONLY INFORMATION SECTION - Compact */}
|
||||
<div className="space-y-4">
|
||||
<ReadonlyLeagueInfo league={league} configForm={configForm} />
|
||||
<ReadonlyLeagueInfo league={settings.league} configForm={settings.config} />
|
||||
|
||||
{/* League Owner - Compact */}
|
||||
<div className="rounded-xl border border-charcoal-outline bg-gradient-to-br from-iron-gray/40 to-iron-gray/20 p-5">
|
||||
@@ -234,7 +147,7 @@ export default function LeagueSettingsPage() {
|
||||
</div>
|
||||
|
||||
{/* Transfer Ownership - Owner Only */}
|
||||
{league.ownerId === currentDriverId && allMembers.length > 0 && (
|
||||
{settings.league.ownerId === currentDriverId && settings.members.length > 0 && (
|
||||
<div className="rounded-xl border border-charcoal-outline bg-gradient-to-br from-iron-gray/40 to-iron-gray/20 p-5">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<UserCog className="w-4 h-4 text-gray-400" />
|
||||
@@ -243,7 +156,7 @@ export default function LeagueSettingsPage() {
|
||||
<p className="text-xs text-gray-500 mb-4">
|
||||
Transfer league ownership to another active member. You will become an admin.
|
||||
</p>
|
||||
|
||||
|
||||
{!showTransferDialog ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
@@ -259,13 +172,13 @@ export default function LeagueSettingsPage() {
|
||||
className="w-full rounded-lg border border-charcoal-outline bg-charcoal-card px-3 py-2 text-sm text-white focus:border-primary-blue focus:outline-none"
|
||||
>
|
||||
<option value="">Select new owner...</option>
|
||||
{allMembers.map((member) => (
|
||||
{settings.members.map((member) => (
|
||||
<option key={member.id} value={member.id}>
|
||||
{member.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="primary"
|
||||
|
||||
@@ -4,11 +4,11 @@ import Button from '@/components/ui/Button';
|
||||
import Card from '@/components/ui/Card';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { isLeagueAdminOrHigherRole } from '@/lib/leagueRoles';
|
||||
import type { DriverDTO } from '@core/racing/application/dto/DriverDTO';
|
||||
import { EntityMappers } from '@core/racing/application/mappers/EntityMappers';
|
||||
import type { PenaltyType } from '@core/racing/domain/entities/Penalty';
|
||||
import type { Protest } from '@core/racing/domain/entities/Protest';
|
||||
import type { Race } from '@core/racing/domain/entities/Race';
|
||||
import { ServiceFactory } from '@/lib/services/ServiceFactory';
|
||||
import { ProtestViewModel } from '@/lib/view-models/ProtestViewModel';
|
||||
import { ProtestDecisionCommandModel, type PenaltyType } from '@/lib/command-models/protests/ProtestDecisionCommandModel';
|
||||
import type { DriverSummaryDTO } from '@/lib/types/generated/LeagueAdminProtestsDTO';
|
||||
import type { RaceDTO } from '@/lib/types/generated/RaceDTO';
|
||||
import {
|
||||
AlertCircle,
|
||||
AlertTriangle,
|
||||
@@ -115,10 +115,10 @@ export default function ProtestReviewPage() {
|
||||
const protestId = params.protestId as string;
|
||||
const currentDriverId = useEffectiveDriverId();
|
||||
|
||||
const [protest, setProtest] = useState<Protest | null>(null);
|
||||
const [race, setRace] = useState<Race | null>(null);
|
||||
const [protestingDriver, setProtestingDriver] = useState<DriverDTO | null>(null);
|
||||
const [accusedDriver, setAccusedDriver] = useState<DriverDTO | null>(null);
|
||||
const [protest, setProtest] = useState<ProtestViewModel | null>(null);
|
||||
const [race, setRace] = useState<RaceDTO | null>(null);
|
||||
const [protestingDriver, setProtestingDriver] = useState<DriverSummaryDTO | null>(null);
|
||||
const [accusedDriver, setAccusedDriver] = useState<DriverSummaryDTO | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
|
||||
@@ -146,27 +146,18 @@ export default function ProtestReviewPage() {
|
||||
async function loadProtest() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const protestRepo = getProtestRepository();
|
||||
const raceRepo = getRaceRepository();
|
||||
const driverRepo = getDriverRepository();
|
||||
const serviceFactory = new ServiceFactory(process.env.NEXT_PUBLIC_API_URL || '');
|
||||
const protestService = serviceFactory.createProtestService();
|
||||
|
||||
const protestEntity = await protestRepo.findById(protestId);
|
||||
if (!protestEntity) {
|
||||
const protestData = await protestService.getProtestById(leagueId, protestId);
|
||||
if (!protestData) {
|
||||
throw new Error('Protest not found');
|
||||
}
|
||||
setProtest(protestEntity);
|
||||
|
||||
const raceEntity = await raceRepo.findById(protestEntity.raceId);
|
||||
if (!raceEntity) {
|
||||
throw new Error('Race not found');
|
||||
}
|
||||
setRace(raceEntity);
|
||||
|
||||
const protestingDriverEntity = await driverRepo.findById(protestEntity.protestingDriverId);
|
||||
const accusedDriverEntity = await driverRepo.findById(protestEntity.accusedDriverId);
|
||||
|
||||
setProtestingDriver(protestingDriverEntity ? EntityMappers.toDriverDTO(protestingDriverEntity) : null);
|
||||
setAccusedDriver(accusedDriverEntity ? EntityMappers.toDriverDTO(accusedDriverEntity) : null);
|
||||
setProtest(protestData.protest);
|
||||
setRace(protestData.race);
|
||||
setProtestingDriver(protestData.protestingDriver);
|
||||
setAccusedDriver(protestData.accusedDriver);
|
||||
} catch (err) {
|
||||
console.error('Failed to load protest:', err);
|
||||
alert('Failed to load protest details');
|
||||
@@ -179,39 +170,39 @@ export default function ProtestReviewPage() {
|
||||
if (isAdmin) {
|
||||
loadProtest();
|
||||
}
|
||||
}, [protestId, leagueId, isAdmin, currentDriverId, router]);
|
||||
}, [protestId, leagueId, isAdmin, router]);
|
||||
|
||||
// Build timeline from protest data
|
||||
const timeline = useMemo((): TimelineEvent[] => {
|
||||
if (!protest) return [];
|
||||
|
||||
|
||||
const events: TimelineEvent[] = [
|
||||
{
|
||||
id: 'filed',
|
||||
type: 'protest_filed',
|
||||
timestamp: new Date(protest.filedAt),
|
||||
timestamp: new Date(protest.submittedAt),
|
||||
actor: protestingDriver,
|
||||
content: protest.incident.description,
|
||||
content: protest.description, // TODO: Add incident description when available
|
||||
metadata: {
|
||||
lap: protest.incident.lap,
|
||||
comment: protest.comment
|
||||
// lap: protest.incident?.lap,
|
||||
// comment: protest.comment
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
// Add decision event if resolved
|
||||
if (protest.status === 'upheld' || protest.status === 'dismissed') {
|
||||
events.push({
|
||||
id: 'decision',
|
||||
type: 'decision',
|
||||
timestamp: protest.reviewedAt ? new Date(protest.reviewedAt) : new Date(),
|
||||
actor: null, // Would need to load steward driver
|
||||
content: protest.decisionNotes || (protest.status === 'upheld' ? 'Protest upheld' : 'Protest dismissed'),
|
||||
metadata: {
|
||||
decision: protest.status
|
||||
}
|
||||
});
|
||||
}
|
||||
// TODO: Add decision event when status/decisions are available in DTO
|
||||
// if (protest.status === 'upheld' || protest.status === 'dismissed') {
|
||||
// events.push({
|
||||
// id: 'decision',
|
||||
// type: 'decision',
|
||||
// timestamp: protest.reviewedAt ? new Date(protest.reviewedAt) : new Date(),
|
||||
// actor: null, // Would need to load steward driver
|
||||
// content: protest.decisionNotes || (protest.status === 'upheld' ? 'Protest upheld' : 'Protest dismissed'),
|
||||
// metadata: {
|
||||
// decision: protest.status
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
return events.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
||||
}, [protest, protestingDriver]);
|
||||
@@ -221,38 +212,44 @@ export default function ProtestReviewPage() {
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const reviewUseCase = getReviewProtestUseCase();
|
||||
const penaltyUseCase = getApplyPenaltyUseCase();
|
||||
const serviceFactory = new ServiceFactory(process.env.NEXT_PUBLIC_API_URL || '');
|
||||
const protestService = serviceFactory.createProtestService();
|
||||
|
||||
if (decision === 'uphold') {
|
||||
await reviewUseCase.execute({
|
||||
protestId: protest.id,
|
||||
stewardId: currentDriverId,
|
||||
decision: 'uphold',
|
||||
decisionNotes: stewardNotes,
|
||||
const commandModel = new ProtestDecisionCommandModel({
|
||||
decision,
|
||||
penaltyType,
|
||||
penaltyValue,
|
||||
stewardNotes,
|
||||
});
|
||||
|
||||
const selectedPenalty = PENALTY_TYPES.find(p => p.type === penaltyType);
|
||||
const penaltyValueToUse =
|
||||
selectedPenalty && selectedPenalty.requiresValue ? penaltyValue : 0;
|
||||
const penaltyCommand = commandModel.toApplyPenaltyCommand(
|
||||
protest.raceId,
|
||||
protest.accusedDriverId,
|
||||
currentDriverId,
|
||||
protest.id
|
||||
);
|
||||
|
||||
await penaltyUseCase.execute({
|
||||
raceId: protest.raceId,
|
||||
driverId: protest.accusedDriverId,
|
||||
stewardId: currentDriverId,
|
||||
type: penaltyType,
|
||||
value: penaltyValueToUse,
|
||||
reason: protest.incident.description,
|
||||
protestId: protest.id,
|
||||
notes: stewardNotes,
|
||||
});
|
||||
await protestService.applyPenalty(penaltyCommand);
|
||||
} else {
|
||||
await reviewUseCase.execute({
|
||||
protestId: protest.id,
|
||||
stewardId: currentDriverId,
|
||||
decision: 'dismiss',
|
||||
decisionNotes: stewardNotes,
|
||||
// For dismiss, we might need a separate endpoint
|
||||
// For now, just apply a warning penalty with 0 value or create a separate endpoint
|
||||
const commandModel = new ProtestDecisionCommandModel({
|
||||
decision,
|
||||
penaltyType: 'warning',
|
||||
penaltyValue: 0,
|
||||
stewardNotes,
|
||||
});
|
||||
|
||||
const penaltyCommand = commandModel.toApplyPenaltyCommand(
|
||||
protest.raceId,
|
||||
protest.accusedDriverId,
|
||||
currentDriverId,
|
||||
protest.id
|
||||
);
|
||||
penaltyCommand.reason = 'Protest upheld'; // TODO: Make this configurable
|
||||
|
||||
await protestService.applyPenalty(penaltyCommand);
|
||||
}
|
||||
|
||||
router.push(`/leagues/${leagueId}/stewarding`);
|
||||
@@ -265,31 +262,17 @@ export default function ProtestReviewPage() {
|
||||
|
||||
const handleRequestDefense = async () => {
|
||||
if (!protest) return;
|
||||
|
||||
|
||||
try {
|
||||
const requestDefenseUseCase = getRequestProtestDefenseUseCase();
|
||||
const sendNotificationUseCase = getSendNotificationUseCase();
|
||||
|
||||
const serviceFactory = new ServiceFactory(process.env.NEXT_PUBLIC_API_URL || '');
|
||||
const protestService = serviceFactory.createProtestService();
|
||||
|
||||
// Request defense
|
||||
const result = await requestDefenseUseCase.execute({
|
||||
await protestService.requestDefense({
|
||||
protestId: protest.id,
|
||||
stewardId: currentDriverId,
|
||||
});
|
||||
|
||||
// Send notification to accused driver
|
||||
await sendNotificationUseCase.execute({
|
||||
recipientId: result.accusedDriverId,
|
||||
type: 'protest_filed',
|
||||
title: 'Defense Requested',
|
||||
body: `A steward has requested your defense for a protest filed against you.`,
|
||||
actionUrl: `/leagues/${leagueId}/stewarding/protests/${protest.id}`,
|
||||
data: {
|
||||
protestId: protest.id,
|
||||
raceId: protest.raceId,
|
||||
leagueId,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
// Reload page to show updated status
|
||||
window.location.reload();
|
||||
} catch (err) {
|
||||
@@ -340,10 +323,10 @@ export default function ProtestReviewPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const statusConfig = getStatusConfig(protest.status);
|
||||
const statusConfig = getStatusConfig('pending'); // TODO: Update when status is available
|
||||
const StatusIcon = statusConfig.icon;
|
||||
const isPending = protest.status === 'pending' || protest.status === 'under_review' || protest.status === 'awaiting_defense';
|
||||
const daysSinceFiled = Math.floor((Date.now() - new Date(protest.filedAt).getTime()) / (1000 * 60 * 60 * 24));
|
||||
const isPending = true; // TODO: Update when status is available
|
||||
const daysSinceFiled = Math.floor((Date.now() - new Date(protest.submittedAt).getTime()) / (1000 * 60 * 60 * 24));
|
||||
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
@@ -417,29 +400,30 @@ export default function ProtestReviewPage() {
|
||||
className="block mb-3 p-3 rounded-lg bg-deep-graphite border border-charcoal-outline hover:border-primary-blue/50 hover:bg-primary-blue/5 transition-colors"
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium text-white">{race.track}</span>
|
||||
<span className="text-sm font-medium text-white">{race.name}</span>
|
||||
<ExternalLink className="w-3 h-3 text-gray-500" />
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<MapPin className="w-4 h-4 text-gray-500" />
|
||||
<span className="text-gray-300">{race.track}</span>
|
||||
<span className="text-gray-300">{race.name}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Calendar className="w-4 h-4 text-gray-500" />
|
||||
<span className="text-gray-300">{race.scheduledAt.toLocaleDateString()}</span>
|
||||
<span className="text-gray-300">{new Date(race.date).toLocaleDateString()}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{/* TODO: Add lap info when available */}
|
||||
{/* <div className="flex items-center gap-2 text-sm">
|
||||
<Flag className="w-4 h-4 text-gray-500" />
|
||||
<span className="text-gray-300">Lap {protest.incident.lap}</span>
|
||||
</div>
|
||||
</div> */}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Evidence */}
|
||||
{protest.proofVideoUrl && (
|
||||
{/* TODO: Add evidence when available */}
|
||||
{/* {protest.proofVideoUrl && (
|
||||
<Card className="p-4">
|
||||
<h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">Evidence</h3>
|
||||
<a
|
||||
@@ -453,7 +437,7 @@ export default function ProtestReviewPage() {
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
</Card>
|
||||
)}
|
||||
)} */}
|
||||
|
||||
{/* Quick Stats */}
|
||||
<Card className="p-4">
|
||||
@@ -461,7 +445,7 @@ export default function ProtestReviewPage() {
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">Filed</span>
|
||||
<span className="text-gray-300">{new Date(protest.filedAt).toLocaleDateString()}</span>
|
||||
<span className="text-gray-300">{new Date(protest.submittedAt).toLocaleDateString()}</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-gray-500">Age</span>
|
||||
@@ -497,18 +481,19 @@ export default function ProtestReviewPage() {
|
||||
<span className="font-semibold text-white text-sm">{protestingDriver?.name || 'Unknown'}</span>
|
||||
<span className="text-xs text-blue-400 font-medium">filed protest</span>
|
||||
<span className="text-xs text-gray-500">•</span>
|
||||
<span className="text-xs text-gray-500">{new Date(protest.filedAt).toLocaleString()}</span>
|
||||
<span className="text-xs text-gray-500">{new Date(protest.submittedAt).toLocaleString()}</span>
|
||||
</div>
|
||||
|
||||
<div className="bg-deep-graphite rounded-lg p-4 border border-charcoal-outline">
|
||||
<p className="text-sm text-gray-300 mb-3">{protest.incident.description}</p>
|
||||
|
||||
{protest.comment && (
|
||||
<p className="text-sm text-gray-300 mb-3">{protest.description}</p>
|
||||
|
||||
{/* TODO: Add comment when available */}
|
||||
{/* {protest.comment && (
|
||||
<div className="mt-3 pt-3 border-t border-charcoal-outline/50">
|
||||
<p className="text-xs text-gray-500 mb-1">Additional details:</p>
|
||||
<p className="text-sm text-gray-400">{protest.comment}</p>
|
||||
</div>
|
||||
)}
|
||||
)} */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user