website refactor
This commit is contained in:
42
apps/website/app/actions/logoutAction.ts
Normal file
42
apps/website/app/actions/logoutAction.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
'use server';
|
||||
|
||||
import { redirect } from 'next/navigation';
|
||||
import { AuthApiClient } from '@/lib/api/auth/AuthApiClient';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
|
||||
/**
|
||||
* Server action for logout
|
||||
*
|
||||
* Performs the logout mutation by calling the API and redirects to login.
|
||||
* Follows the write boundary contract: all writes enter through server actions.
|
||||
*/
|
||||
export async function logoutAction(): Promise<void> {
|
||||
try {
|
||||
// Create required dependencies for API client
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: false,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
|
||||
// Get API base URL from environment
|
||||
const baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || 'http://localhost:3001';
|
||||
|
||||
// Create API client instance
|
||||
const apiClient = new AuthApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Call the logout API endpoint
|
||||
await apiClient.logout();
|
||||
|
||||
// Redirect to login page after successful logout
|
||||
redirect('/auth/login');
|
||||
} catch (error) {
|
||||
// Log error for debugging
|
||||
console.error('Logout action failed:', error);
|
||||
|
||||
// Still redirect even if logout fails - user should be able to leave
|
||||
redirect('/auth/login');
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useState, useEffect, FormEvent, type ChangeEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useForgotPassword } from '@/hooks/auth/useForgotPassword';
|
||||
import { useForgotPassword } from "@/lib/hooks/auth/useForgotPassword";
|
||||
import Link from 'next/link';
|
||||
import { motion } from 'framer-motion';
|
||||
import {
|
||||
|
||||
@@ -20,7 +20,7 @@ import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useLogin } from '@/hooks/auth/useLogin';
|
||||
import { useLogin } from "@/lib/hooks/auth/useLogin";
|
||||
import AuthWorkflowMockup from '@/components/auth/AuthWorkflowMockup';
|
||||
import UserRolesPreview from '@/components/auth/UserRolesPreview';
|
||||
import { EnhancedFormError } from '@/components/errors/EnhancedFormError';
|
||||
|
||||
@@ -20,7 +20,7 @@ import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useResetPassword } from '@/hooks/auth/useResetPassword';
|
||||
import { useResetPassword } from "@/lib/hooks/auth/useResetPassword";
|
||||
|
||||
interface FormErrors {
|
||||
newPassword?: string;
|
||||
|
||||
@@ -27,7 +27,7 @@ import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useSignup } from '@/hooks/auth/useSignup';
|
||||
import { useSignup } from "@/lib/hooks/auth/useSignup";
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
|
||||
interface FormErrors {
|
||||
|
||||
@@ -1,95 +1,23 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import type { DashboardViewData } from './DashboardViewData';
|
||||
import type { DashboardOverviewViewModelData } from '@/lib/view-models/DashboardOverviewViewModelData';
|
||||
import { DashboardOverviewViewModel } from '@/lib/view-models/DashboardOverviewViewModel';
|
||||
import React from 'react';
|
||||
import type { DashboardViewData } from '@/templates/view-data/DashboardViewData';
|
||||
import type { DashboardPageDto } from '@/lib/page-queries/page-dtos/DashboardPageDto';
|
||||
import { DashboardPresenter } from '@/lib/presenters/DashboardPresenter';
|
||||
import { DashboardTemplate } from '@/templates/DashboardTemplate';
|
||||
|
||||
interface DashboardPageClientProps {
|
||||
initialViewData: DashboardViewData;
|
||||
dto: DashboardOverviewViewModelData;
|
||||
pageDto: DashboardPageDto;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashboard Page Client Component
|
||||
*
|
||||
* Two-phase render:
|
||||
* 1. Initial SSR: Uses ViewData built directly from DTO (no ViewModel)
|
||||
* 2. Post-hydration: Instantiates ViewModel and re-renders with enhanced data
|
||||
*
|
||||
* Uses Presenter to transform Page DTO into ViewData
|
||||
* Presenter is deterministic and side-effect free
|
||||
*/
|
||||
export function DashboardPageClient({ initialViewData, dto }: DashboardPageClientProps) {
|
||||
const [viewData, setViewData] = useState<DashboardViewData>(initialViewData);
|
||||
|
||||
useEffect(() => {
|
||||
// Phase 2: After hydration, instantiate ViewModel and enhance data
|
||||
const viewModel = new DashboardOverviewViewModel(dto);
|
||||
|
||||
const enhancedViewData: DashboardViewData = {
|
||||
currentDriver: {
|
||||
name: viewModel.currentDriverName,
|
||||
avatarUrl: viewModel.currentDriverAvatarUrl,
|
||||
country: viewModel.currentDriverCountry,
|
||||
rating: viewModel.currentDriverRating,
|
||||
rank: viewModel.currentDriverRank,
|
||||
totalRaces: viewModel.currentDriverTotalRaces,
|
||||
wins: viewModel.currentDriverWins,
|
||||
podiums: viewModel.currentDriverPodiums,
|
||||
consistency: viewModel.currentDriverConsistency,
|
||||
},
|
||||
nextRace: viewModel.nextRace ? {
|
||||
id: viewModel.nextRace.id,
|
||||
track: viewModel.nextRace.track,
|
||||
car: viewModel.nextRace.car,
|
||||
scheduledAt: viewModel.nextRace.scheduledAt,
|
||||
formattedDate: viewModel.nextRace.formattedDate,
|
||||
formattedTime: viewModel.nextRace.formattedTime,
|
||||
timeUntil: viewModel.nextRace.timeUntil,
|
||||
isMyLeague: viewModel.nextRace.isMyLeague,
|
||||
} : null,
|
||||
upcomingRaces: viewModel.upcomingRaces.map((race) => ({
|
||||
id: race.id,
|
||||
track: race.track,
|
||||
car: race.car,
|
||||
scheduledAt: race.scheduledAt,
|
||||
formattedDate: race.formattedDate,
|
||||
formattedTime: race.formattedTime,
|
||||
timeUntil: race.timeUntil,
|
||||
isMyLeague: race.isMyLeague,
|
||||
})),
|
||||
leagueStandings: viewModel.leagueStandings.map((standing) => ({
|
||||
leagueId: standing.leagueId,
|
||||
leagueName: standing.leagueName,
|
||||
position: standing.position,
|
||||
points: standing.points,
|
||||
totalDrivers: standing.totalDrivers,
|
||||
})),
|
||||
feedItems: viewModel.feedItems.map((item) => ({
|
||||
id: item.id,
|
||||
type: item.type,
|
||||
headline: item.headline,
|
||||
body: item.body,
|
||||
timestamp: item.timestamp,
|
||||
formattedTime: item.formattedTime,
|
||||
ctaHref: item.ctaHref,
|
||||
ctaLabel: item.ctaLabel,
|
||||
})),
|
||||
friends: viewModel.friends.map((friend) => ({
|
||||
id: friend.id,
|
||||
name: friend.name,
|
||||
avatarUrl: friend.avatarUrl,
|
||||
country: friend.country,
|
||||
})),
|
||||
activeLeaguesCount: viewModel.activeLeaguesCount,
|
||||
friendCount: viewModel.friendCount,
|
||||
hasUpcomingRaces: viewModel.hasUpcomingRaces,
|
||||
hasLeagueStandings: viewModel.hasLeagueStandings,
|
||||
hasFeedItems: viewModel.hasFeedItems,
|
||||
hasFriends: viewModel.hasFriends,
|
||||
};
|
||||
|
||||
setViewData(enhancedViewData);
|
||||
}, [dto]);
|
||||
export function DashboardPageClient({ pageDto }: DashboardPageClientProps) {
|
||||
const viewData: DashboardViewData = DashboardPresenter.createViewData(pageDto);
|
||||
|
||||
return <DashboardTemplate data={viewData} />;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
/**
|
||||
* Dashboard ViewData
|
||||
*
|
||||
* SSR-safe data structure that can be built directly from DTO
|
||||
* without ViewModel instantiation. Contains formatted values
|
||||
* for display and ISO string timestamps for JSON serialization.
|
||||
*/
|
||||
|
||||
export interface DashboardViewData {
|
||||
currentDriver: {
|
||||
name: string;
|
||||
avatarUrl: string;
|
||||
country: string;
|
||||
rating: string;
|
||||
rank: string;
|
||||
totalRaces: string;
|
||||
wins: string;
|
||||
podiums: string;
|
||||
consistency: string;
|
||||
};
|
||||
nextRace: {
|
||||
id: string;
|
||||
track: string;
|
||||
car: string;
|
||||
scheduledAt: string; // ISO string
|
||||
formattedDate: string;
|
||||
formattedTime: string;
|
||||
timeUntil: string;
|
||||
isMyLeague: boolean;
|
||||
} | null;
|
||||
upcomingRaces: Array<{
|
||||
id: string;
|
||||
track: string;
|
||||
car: string;
|
||||
scheduledAt: string; // ISO string
|
||||
formattedDate: string;
|
||||
formattedTime: string;
|
||||
timeUntil: string;
|
||||
isMyLeague: boolean;
|
||||
}>;
|
||||
leagueStandings: Array<{
|
||||
leagueId: string;
|
||||
leagueName: string;
|
||||
position: string;
|
||||
points: string;
|
||||
totalDrivers: string;
|
||||
}>;
|
||||
feedItems: Array<{
|
||||
id: string;
|
||||
type: string;
|
||||
headline: string;
|
||||
body?: string;
|
||||
timestamp: string; // ISO string
|
||||
formattedTime: string;
|
||||
ctaHref?: string;
|
||||
ctaLabel?: string;
|
||||
}>;
|
||||
friends: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
avatarUrl: string;
|
||||
country: string;
|
||||
}>;
|
||||
activeLeaguesCount: string;
|
||||
friendCount: string;
|
||||
hasUpcomingRaces: boolean;
|
||||
hasLeagueStandings: boolean;
|
||||
hasFeedItems: boolean;
|
||||
hasFriends: boolean;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import type { DashboardOverviewViewModelData } from '@/lib/view-models/DashboardOverviewViewModelData';
|
||||
import type { DashboardViewData } from './DashboardViewData';
|
||||
import {
|
||||
formatDashboardDate,
|
||||
formatRating,
|
||||
formatRank,
|
||||
formatConsistency,
|
||||
formatRaceCount,
|
||||
formatFriendCount,
|
||||
formatLeaguePosition,
|
||||
formatPoints,
|
||||
formatTotalDrivers,
|
||||
} from '@/lib/display-objects/DashboardDisplay';
|
||||
|
||||
/**
|
||||
* Build DashboardViewData directly from ViewModelData
|
||||
* Used for SSR phase - no ViewModel instantiation
|
||||
*/
|
||||
export function buildDashboardViewData(viewModelData: DashboardOverviewViewModelData): DashboardViewData {
|
||||
return {
|
||||
currentDriver: {
|
||||
name: viewModelData.currentDriver?.name || '',
|
||||
avatarUrl: viewModelData.currentDriver?.avatarUrl || '',
|
||||
country: viewModelData.currentDriver?.country || '',
|
||||
rating: viewModelData.currentDriver ? formatRating(viewModelData.currentDriver.rating) : '0.0',
|
||||
rank: viewModelData.currentDriver ? formatRank(viewModelData.currentDriver.globalRank) : '0',
|
||||
totalRaces: viewModelData.currentDriver ? formatRaceCount(viewModelData.currentDriver.totalRaces) : '0',
|
||||
wins: viewModelData.currentDriver ? formatRaceCount(viewModelData.currentDriver.wins) : '0',
|
||||
podiums: viewModelData.currentDriver ? formatRaceCount(viewModelData.currentDriver.podiums) : '0',
|
||||
consistency: viewModelData.currentDriver ? formatConsistency(viewModelData.currentDriver.consistency) : '0%',
|
||||
},
|
||||
nextRace: viewModelData.nextRace ? (() => {
|
||||
const dateInfo = formatDashboardDate(new Date(viewModelData.nextRace.scheduledAt));
|
||||
return {
|
||||
id: viewModelData.nextRace.id,
|
||||
track: viewModelData.nextRace.track,
|
||||
car: viewModelData.nextRace.car,
|
||||
scheduledAt: viewModelData.nextRace.scheduledAt,
|
||||
formattedDate: dateInfo.date,
|
||||
formattedTime: dateInfo.time,
|
||||
timeUntil: dateInfo.relative,
|
||||
isMyLeague: viewModelData.nextRace.isMyLeague,
|
||||
};
|
||||
})() : null,
|
||||
upcomingRaces: viewModelData.upcomingRaces.map((race) => {
|
||||
const dateInfo = formatDashboardDate(new Date(race.scheduledAt));
|
||||
return {
|
||||
id: race.id,
|
||||
track: race.track,
|
||||
car: race.car,
|
||||
scheduledAt: race.scheduledAt,
|
||||
formattedDate: dateInfo.date,
|
||||
formattedTime: dateInfo.time,
|
||||
timeUntil: dateInfo.relative,
|
||||
isMyLeague: race.isMyLeague,
|
||||
};
|
||||
}),
|
||||
leagueStandings: viewModelData.leagueStandingsSummaries.map((standing) => ({
|
||||
leagueId: standing.leagueId,
|
||||
leagueName: standing.leagueName,
|
||||
position: formatLeaguePosition(standing.position),
|
||||
points: formatPoints(standing.points),
|
||||
totalDrivers: formatTotalDrivers(standing.totalDrivers),
|
||||
})),
|
||||
feedItems: viewModelData.feedSummary.items.map((item) => ({
|
||||
id: item.id,
|
||||
type: item.type,
|
||||
headline: item.headline,
|
||||
body: item.body,
|
||||
timestamp: item.timestamp,
|
||||
formattedTime: formatDashboardDate(new Date(item.timestamp)).relative,
|
||||
ctaHref: item.ctaHref,
|
||||
ctaLabel: item.ctaLabel,
|
||||
})),
|
||||
friends: viewModelData.friends.map((friend) => ({
|
||||
id: friend.id,
|
||||
name: friend.name,
|
||||
avatarUrl: friend.avatarUrl,
|
||||
country: friend.country,
|
||||
})),
|
||||
activeLeaguesCount: formatRaceCount(viewModelData.activeLeaguesCount),
|
||||
friendCount: formatFriendCount(viewModelData.friends.length),
|
||||
hasUpcomingRaces: viewModelData.upcomingRaces.length > 0,
|
||||
hasLeagueStandings: viewModelData.leagueStandingsSummaries.length > 0,
|
||||
hasFeedItems: viewModelData.feedSummary.items.length > 0,
|
||||
hasFriends: viewModelData.friends.length > 0,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { notFound, redirect } from 'next/navigation';
|
||||
import { DashboardPageQuery } from '@/lib/page-queries/DashboardPageQuery';
|
||||
import { DashboardPageQuery } from '@/lib/page-queries/page-queries/DashboardPageQuery';
|
||||
import { DashboardPageClient } from './DashboardPageClient';
|
||||
import { buildDashboardViewData } from './DashboardViewDataBuilder';
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const result = await DashboardPageQuery.execute();
|
||||
@@ -9,23 +8,18 @@ export default async function DashboardPage() {
|
||||
// Handle result based on status
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
const viewModelData = result.data;
|
||||
|
||||
// Build SSR ViewData directly from ViewModelData
|
||||
const ssrViewData = buildDashboardViewData(viewModelData);
|
||||
|
||||
// Pass both ViewData (for SSR) and ViewModelData (for client enhancement)
|
||||
return <DashboardPageClient initialViewData={ssrViewData} dto={viewModelData} />;
|
||||
// Pass Page DTO to client component
|
||||
return <DashboardPageClient pageDto={result.dto} />;
|
||||
|
||||
case 'notFound':
|
||||
notFound();
|
||||
|
||||
case 'redirect':
|
||||
redirect(result.destination);
|
||||
redirect(result.to);
|
||||
|
||||
case 'error':
|
||||
// For now, treat as notFound. Could also show error page
|
||||
console.error('Dashboard error:', result.error);
|
||||
console.error('Dashboard error:', result.errorId);
|
||||
notFound();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
import { DriverProfileTemplate } from '@/templates/DriverProfileTemplate';
|
||||
import { useDriverProfilePageData } from '@/hooks/driver/useDriverProfilePageData';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { useDriverProfilePageData } from "@/lib/hooks/driver/useDriverProfilePageData";
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
|
||||
|
||||
@@ -19,9 +19,9 @@ export default async function DriverLeaderboardPage() {
|
||||
);
|
||||
|
||||
// Prepare data for template
|
||||
const data: DriverLeaderboardViewModel | null = driverData as DriverLeaderboardViewModel | null;
|
||||
const data: DriverLeaderboardViewModel | null = driverData;
|
||||
|
||||
const hasData = (driverData as any)?.drivers?.length > 0;
|
||||
const hasData = (driverData?.drivers?.length ?? 0) > 0;
|
||||
|
||||
// Handle loading state (should be fast since we're using async/await)
|
||||
const isLoading = false;
|
||||
|
||||
@@ -37,11 +37,11 @@ export default async function LeaderboardsPage() {
|
||||
|
||||
// Prepare data for template
|
||||
const data: LeaderboardsPageData = {
|
||||
drivers: driverData as DriverLeaderboardViewModel | null,
|
||||
teams: teamsData as TeamSummaryViewModel[] | null,
|
||||
drivers: driverData,
|
||||
teams: teamsData,
|
||||
};
|
||||
|
||||
const hasData = (driverData as any)?.drivers?.length > 0 || (teamsData as any)?.length > 0;
|
||||
const hasData = (driverData?.drivers?.length ?? 0) > 0 || (teamsData?.length ?? 0) > 0;
|
||||
|
||||
// Handle loading state (should be fast since we're using async/await)
|
||||
const isLoading = false;
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
import Breadcrumbs from '@/components/layout/Breadcrumbs';
|
||||
import LeagueHeader from '@/components/leagues/LeagueHeader';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { useLeagueDetail } from '@/hooks/league/useLeagueDetail';
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { useLeagueDetail } from "@/lib/hooks/league/useLeagueDetail";
|
||||
import { useParams, usePathname, useRouter } from 'next/navigation';
|
||||
import React from 'react';
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
useRejectJoinRequest,
|
||||
useUpdateMemberRole,
|
||||
useRemoveMember,
|
||||
} from '@/hooks/league/useLeagueRosterAdmin';
|
||||
} from "@/lib/hooks/league/useLeagueRosterAdmin";
|
||||
|
||||
const ROLE_OPTIONS: MembershipRole[] = ['owner', 'admin', 'steward', 'member'];
|
||||
|
||||
|
||||
@@ -8,8 +8,8 @@ import {
|
||||
useLeagueAdminStatus,
|
||||
useLeagueSeasons,
|
||||
useLeagueAdminSchedule
|
||||
} from '@/hooks/league/useLeagueScheduleAdminPageData';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
} from "@/lib/hooks/league/useLeagueScheduleAdminPageData";
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useInject } from '@/lib/di/hooks/useInject';
|
||||
import { LEAGUE_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
|
||||
@@ -10,12 +10,39 @@ import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporte
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
import { notFound } from 'next/navigation';
|
||||
import type { LeagueScheduleViewModel } from '@/lib/view-models/LeagueScheduleViewModel';
|
||||
import { LeagueScheduleViewModel, LeagueScheduleRaceViewModel } from '@/lib/view-models/LeagueScheduleViewModel';
|
||||
import type { LeagueScheduleDTO } from '@/lib/types/generated/LeagueScheduleDTO';
|
||||
import type { RaceDTO } from '@/lib/types/generated/RaceDTO';
|
||||
|
||||
interface Props {
|
||||
params: { id: string };
|
||||
}
|
||||
|
||||
function mapRaceDtoToViewModel(race: RaceDTO): LeagueScheduleRaceViewModel {
|
||||
const scheduledAt = race.date ? new Date(race.date) : new Date(0);
|
||||
const now = new Date();
|
||||
const isPast = scheduledAt.getTime() < now.getTime();
|
||||
const isUpcoming = !isPast;
|
||||
|
||||
return {
|
||||
id: race.id,
|
||||
name: race.name,
|
||||
scheduledAt,
|
||||
isPast,
|
||||
isUpcoming,
|
||||
status: isPast ? 'completed' : 'scheduled',
|
||||
track: undefined,
|
||||
car: undefined,
|
||||
sessionType: undefined,
|
||||
isRegistered: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function mapScheduleDtoToViewModel(dto: LeagueScheduleDTO): LeagueScheduleViewModel {
|
||||
const races = dto.races.map(mapRaceDtoToViewModel);
|
||||
return new LeagueScheduleViewModel(races);
|
||||
}
|
||||
|
||||
export default async function Page({ params }: Props) {
|
||||
// Validate params
|
||||
if (!params.id) {
|
||||
@@ -52,7 +79,7 @@ export default async function Page({ params }: Props) {
|
||||
if (!result) {
|
||||
throw new Error('League schedule not found');
|
||||
}
|
||||
return result;
|
||||
return mapScheduleDtoToViewModel(result);
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
import { ReadonlyLeagueInfo } from '@/components/leagues/ReadonlyLeagueInfo';
|
||||
import LeagueOwnershipTransfer from '@/components/leagues/LeagueOwnershipTransfer';
|
||||
import Card from '@/components/ui/Card';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
|
||||
// Shared state components
|
||||
import { StateContainer } from '@/components/shared/state/StateContainer';
|
||||
import { LoadingWrapper } from '@/components/shared/state/LoadingWrapper';
|
||||
import { useLeagueAdminStatus } from '@/hooks/league/useLeagueAdminStatus';
|
||||
import { useLeagueSettings } from '@/hooks/league/useLeagueSettings';
|
||||
import { useLeagueAdminStatus } from "@/lib/hooks/league/useLeagueAdminStatus";
|
||||
import { useLeagueSettings } from "@/lib/hooks/league/useLeagueSettings";
|
||||
import { useInject } from '@/lib/di/hooks/useInject';
|
||||
import { LEAGUE_SETTINGS_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import { AlertTriangle, Settings } from 'lucide-react';
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
import { LeagueSponsorshipsSection } from '@/components/leagues/LeagueSponsorshipsSection';
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';
|
||||
import { useLeagueSponsorshipsPageData } from '@/hooks/league/useLeagueSponsorshipsPageData';
|
||||
import { useLeagueSponsorshipsPageData } from "@/lib/hooks/league/useLeagueSponsorshipsPageData";
|
||||
import { ApiError } from '@/lib/api/base/ApiError';
|
||||
import { Building } from 'lucide-react';
|
||||
import { useParams } from 'next/navigation';
|
||||
|
||||
@@ -10,9 +10,11 @@ import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporte
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
import { notFound } from 'next/navigation';
|
||||
import type { LeagueStandingsViewModel } from '@/lib/view-models/LeagueStandingsViewModel';
|
||||
import { StandingEntryViewModel } from '@/lib/view-models/StandingEntryViewModel';
|
||||
import { DriverViewModel } from '@/lib/view-models/DriverViewModel';
|
||||
import type { LeagueMembership } from '@/lib/types/LeagueMembership';
|
||||
import type { LeagueStandingDTO } from '@/lib/types/generated/LeagueStandingDTO';
|
||||
import type { LeagueMemberDTO } from '@/lib/types/generated/LeagueMemberDTO';
|
||||
|
||||
interface Props {
|
||||
params: { id: string };
|
||||
@@ -49,45 +51,72 @@ export default async function Page({ params }: Props) {
|
||||
racesApiClient
|
||||
);
|
||||
|
||||
// Fetch data - using empty string for currentDriverId since this is SSR without session
|
||||
const result = await service.getLeagueStandings(params.id, '');
|
||||
if (!result) {
|
||||
// Fetch data
|
||||
const standingsDto = await service.getLeagueStandings(params.id);
|
||||
if (!standingsDto) {
|
||||
throw new Error('League standings not found');
|
||||
}
|
||||
return result;
|
||||
|
||||
// Get memberships for transformation
|
||||
const membershipsDto = await service.getLeagueMemberships(params.id);
|
||||
|
||||
// Transform standings to StandingEntryViewModel[]
|
||||
const standings: LeagueStandingDTO[] = standingsDto.standings || [];
|
||||
const leaderPoints = standings[0]?.points || 0;
|
||||
const standingViewModels = standings.map((entry, index) => {
|
||||
const nextPoints = standings[index + 1]?.points || entry.points;
|
||||
return new StandingEntryViewModel(entry, leaderPoints, nextPoints, '', undefined);
|
||||
});
|
||||
|
||||
// Extract unique drivers from standings and convert to DriverViewModel[]
|
||||
const driverMap = new Map<string, DriverViewModel>();
|
||||
standings.forEach(standing => {
|
||||
if (standing.driver && !driverMap.has(standing.driver.id)) {
|
||||
const driver = standing.driver;
|
||||
driverMap.set(driver.id, new DriverViewModel({
|
||||
id: driver.id,
|
||||
name: driver.name,
|
||||
avatarUrl: null, // DriverDTO doesn't have avatarUrl
|
||||
iracingId: driver.iracingId,
|
||||
rating: undefined, // DriverDTO doesn't have rating
|
||||
country: driver.country,
|
||||
}));
|
||||
}
|
||||
});
|
||||
const drivers = Array.from(driverMap.values());
|
||||
|
||||
// Transform memberships
|
||||
const memberships: LeagueMembership[] = (membershipsDto.members || []).map((m: LeagueMemberDTO) => ({
|
||||
driverId: m.driverId,
|
||||
leagueId: params.id,
|
||||
role: (m.role as LeagueMembership['role']) ?? 'member',
|
||||
joinedAt: m.joinedAt,
|
||||
status: 'active' as const,
|
||||
}));
|
||||
|
||||
return {
|
||||
standings: standingViewModels,
|
||||
drivers,
|
||||
memberships,
|
||||
};
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// Transform data for template
|
||||
const standings = data.standings ?? [];
|
||||
const drivers: DriverViewModel[] = data.drivers?.map((d) =>
|
||||
new DriverViewModel({
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
avatarUrl: d.avatarUrl || null,
|
||||
iracingId: d.iracingId,
|
||||
rating: d.rating,
|
||||
country: d.country,
|
||||
})
|
||||
) ?? [];
|
||||
const memberships: LeagueMembership[] = data.memberships ?? [];
|
||||
|
||||
// Create a wrapper component that passes data to the template
|
||||
const TemplateWrapper = () => {
|
||||
return (
|
||||
<LeagueStandingsTemplate
|
||||
standings={standings}
|
||||
drivers={drivers}
|
||||
memberships={memberships}
|
||||
standings={data.standings}
|
||||
drivers={data.drivers}
|
||||
memberships={data.memberships}
|
||||
leagueId={params.id}
|
||||
currentDriverId={null}
|
||||
isAdmin={false}
|
||||
onRemoveMember={() => {}}
|
||||
onUpdateRole={() => {}}
|
||||
loading={false}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -6,7 +6,7 @@ import { ReviewProtestModal } from '@/components/leagues/ReviewProtestModal';
|
||||
import StewardingStats from '@/components/leagues/StewardingStats';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Card from '@/components/ui/Card';
|
||||
import { useLeagueStewardingMutations } from '@/hooks/league/useLeagueStewardingMutations';
|
||||
import { useLeagueStewardingMutations } from "@/lib/hooks/league/useLeagueStewardingMutations";
|
||||
import {
|
||||
AlertCircle,
|
||||
AlertTriangle,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useCurrentDriver } from '@/hooks/driver/useCurrentDriver';
|
||||
import { useLeagueAdminStatus } from '@/hooks/league/useLeagueAdminStatus';
|
||||
import { useLeagueStewardingData } from '@/hooks/league/useLeagueStewardingData';
|
||||
import { useLeagueStewardingMutations } from '@/hooks/league/useLeagueStewardingMutations';
|
||||
import { useCurrentDriver } from "@/lib/hooks/driver/useCurrentDriver";
|
||||
import { useLeagueAdminStatus } from "@/lib/hooks/league/useLeagueAdminStatus";
|
||||
import { useLeagueStewardingData } from "@/lib/hooks/league/useLeagueStewardingData";
|
||||
import { useLeagueStewardingMutations } from "@/lib/hooks/league/useLeagueStewardingMutations";
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
import { StewardingTemplate } from './StewardingTemplate';
|
||||
import { LoadingWrapper } from '@/components/shared/state/LoadingWrapper';
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import Button from '@/components/ui/Button';
|
||||
import Card from '@/components/ui/Card';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';
|
||||
import { useInject } from '@/lib/di/hooks/useInject';
|
||||
import { PROTEST_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
@@ -38,8 +38,8 @@ import { useMemo, useState } from 'react';
|
||||
// Shared state components
|
||||
import { StateContainer } from '@/components/shared/state/StateContainer';
|
||||
import { LoadingWrapper } from '@/components/shared/state/LoadingWrapper';
|
||||
import { useLeagueAdminStatus } from '@/hooks/league/useLeagueAdminStatus';
|
||||
import { useProtestDetail } from '@/hooks/league/useProtestDetail';
|
||||
import { useLeagueAdminStatus } from "@/lib/hooks/league/useLeagueAdminStatus";
|
||||
import { useProtestDetail } from "@/lib/hooks/league/useProtestDetail";
|
||||
|
||||
// Timeline event types
|
||||
interface TimelineEvent {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useLeagueWalletPageData, useLeagueWalletWithdrawal } from '@/hooks/league/useLeagueWalletPageData';
|
||||
import { useLeagueWalletPageData, useLeagueWalletWithdrawal } from "@/lib/hooks/league/useLeagueWalletPageData";
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { WalletTemplate } from './WalletTemplate';
|
||||
import { Wallet } from 'lucide-react';
|
||||
|
||||
@@ -7,7 +7,7 @@ import OnboardingWizard from '@/components/onboarding/OnboardingWizard';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
|
||||
// Shared state components
|
||||
import { useCurrentDriver } from '@/hooks/driver/useCurrentDriver';
|
||||
import { useCurrentDriver } from "@/lib/hooks/driver/useCurrentDriver";
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
|
||||
// Template component that accepts data
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
'use client';
|
||||
|
||||
import type { ProfileLeaguesPageDto } from '@/lib/page-queries/page-queries/ProfileLeaguesPageQuery';
|
||||
import { ProfileLeaguesPresenter } from '@/lib/presenters/ProfileLeaguesPresenter';
|
||||
import { ProfileLeaguesTemplate } from '@/templates/ProfileLeaguesTemplate';
|
||||
|
||||
interface ProfileLeaguesPageClientProps {
|
||||
pageDto: ProfileLeaguesPageDto;
|
||||
}
|
||||
|
||||
export function ProfileLeaguesPageClient({ pageDto }: ProfileLeaguesPageClientProps) {
|
||||
// Convert Page DTO to ViewData using Presenter
|
||||
const viewData = ProfileLeaguesPresenter.toViewData(pageDto);
|
||||
|
||||
// Render Template with ViewData
|
||||
return <ProfileLeaguesTemplate viewData={viewData} />;
|
||||
}
|
||||
@@ -1,205 +1,23 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { LEAGUE_SERVICE_TOKEN, LEAGUE_MEMBERSHIP_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import type { LeagueService } from '@/lib/services/leagues/LeagueService';
|
||||
import type { LeagueMembershipService } from '@/lib/services/leagues/LeagueMembershipService';
|
||||
import type { LeagueSummaryViewModel } from '@/lib/view-models/LeagueSummaryViewModel';
|
||||
import type { LeagueMembership } from '@/lib/types/LeagueMembership';
|
||||
import { SessionGateway } from '@/lib/gateways/SessionGateway';
|
||||
import { ContainerManager } from '@/lib/di/container';
|
||||
|
||||
interface LeagueWithRole {
|
||||
league: LeagueSummaryViewModel;
|
||||
membership: LeagueMembership;
|
||||
}
|
||||
|
||||
interface ProfileLeaguesData {
|
||||
ownedLeagues: LeagueWithRole[];
|
||||
memberLeagues: LeagueWithRole[];
|
||||
}
|
||||
|
||||
async function fetchProfileLeaguesData(): Promise<ProfileLeaguesData | null> {
|
||||
try {
|
||||
// Get current driver ID from session
|
||||
const sessionGateway = new SessionGateway();
|
||||
const session = await sessionGateway.getSession();
|
||||
|
||||
if (!session?.user?.primaryDriverId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentDriverId = session.user.primaryDriverId;
|
||||
|
||||
// Fetch leagues using PageDataFetcher
|
||||
const leagues = await PageDataFetcher.fetch<LeagueService, 'getAllLeagues'>(
|
||||
LEAGUE_SERVICE_TOKEN,
|
||||
'getAllLeagues'
|
||||
);
|
||||
|
||||
if (!leagues) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get membership service from container
|
||||
const container = ContainerManager.getInstance().getContainer();
|
||||
const membershipService = container.get<LeagueMembershipService>(LEAGUE_MEMBERSHIP_SERVICE_TOKEN);
|
||||
|
||||
// Fetch memberships for each league
|
||||
const memberships = await Promise.all(
|
||||
leagues.map(async (league) => {
|
||||
await membershipService.fetchLeagueMemberships(league.id);
|
||||
const membership = membershipService.getMembership(league.id, currentDriverId);
|
||||
|
||||
return membership ? { league, membership } : null;
|
||||
})
|
||||
);
|
||||
|
||||
// Filter and categorize leagues
|
||||
const owned: LeagueWithRole[] = [];
|
||||
const member: LeagueWithRole[] = [];
|
||||
|
||||
for (const entry of memberships) {
|
||||
if (!entry || !entry.membership || entry.membership.status !== 'active') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.membership.role === 'owner') {
|
||||
owned.push(entry);
|
||||
} else {
|
||||
member.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
return { ownedLeagues: owned, memberLeagues: member };
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch profile leagues data:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Template component
|
||||
function ProfileLeaguesTemplate({ data }: { data: ProfileLeaguesData }) {
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto space-y-8">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold text-white mb-2">Manage leagues</h1>
|
||||
<p className="text-gray-400 text-sm">
|
||||
View leagues you own and participate in, and jump into league admin tools.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Leagues You Own */}
|
||||
<div className="bg-charcoal rounded-lg border border-charcoal-outline p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-xl font-semibold text-white">Leagues you own</h2>
|
||||
{data.ownedLeagues.length > 0 && (
|
||||
<span className="text-xs text-gray-400">
|
||||
{data.ownedLeagues.length} {data.ownedLeagues.length === 1 ? 'league' : 'leagues'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{data.ownedLeagues.length === 0 ? (
|
||||
<p className="text-sm text-gray-400">
|
||||
You don't own any leagues yet in this session.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{data.ownedLeagues.map(({ league }) => (
|
||||
<div
|
||||
key={league.id}
|
||||
className="flex items-center justify-between p-4 rounded-lg bg-deep-graphite border border-charcoal-outline"
|
||||
>
|
||||
<div>
|
||||
<h3 className="text-white font-medium">{league.name}</h3>
|
||||
<p className="text-xs text-gray-400 mt-1 line-clamp-2">
|
||||
{league.description}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<a
|
||||
href={`/leagues/${league.id}`}
|
||||
className="text-sm text-gray-300 hover:text-white underline-offset-2 hover:underline"
|
||||
>
|
||||
View
|
||||
</a>
|
||||
<a href={`/leagues/${league.id}?tab=admin`}>
|
||||
<button className="bg-primary hover:bg-primary/90 text-white text-xs px-3 py-1.5 rounded transition-colors">
|
||||
Manage
|
||||
</button>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Leagues You're In */}
|
||||
<div className="bg-charcoal rounded-lg border border-charcoal-outline p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-xl font-semibold text-white">Leagues you're in</h2>
|
||||
{data.memberLeagues.length > 0 && (
|
||||
<span className="text-xs text-gray-400">
|
||||
{data.memberLeagues.length} {data.memberLeagues.length === 1 ? 'league' : 'leagues'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{data.memberLeagues.length === 0 ? (
|
||||
<p className="text-sm text-gray-400">
|
||||
You're not a member of any other leagues yet.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{data.memberLeagues.map(({ league, membership }) => (
|
||||
<div
|
||||
key={league.id}
|
||||
className="flex items-center justify-between p-4 rounded-lg bg-deep-graphite border border-charcoal-outline"
|
||||
>
|
||||
<div>
|
||||
<h3 className="text-white font-medium">{league.name}</h3>
|
||||
<p className="text-xs text-gray-400 mt-1 line-clamp-2">
|
||||
{league.description}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Your role:{' '}
|
||||
{membership.role.charAt(0).toUpperCase() + membership.role.slice(1)}
|
||||
</p>
|
||||
</div>
|
||||
<a
|
||||
href={`/leagues/${league.id}`}
|
||||
className="text-sm text-gray-300 hover:text-white underline-offset-2 hover:underline"
|
||||
>
|
||||
View league
|
||||
</a>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
import { ProfileLeaguesPageQuery } from '@/lib/page-queries/ProfileLeaguesPageQuery';
|
||||
import { ProfileLeaguesPageClient } from './ProfileLeaguesPageClient';
|
||||
|
||||
export default async function ProfileLeaguesPage() {
|
||||
const data = await fetchProfileLeaguesData();
|
||||
const result = await ProfileLeaguesPageQuery.execute();
|
||||
|
||||
if (!data) {
|
||||
notFound();
|
||||
switch (result.status) {
|
||||
case 'notFound':
|
||||
notFound();
|
||||
case 'redirect':
|
||||
// Note: In Next.js, redirect would be imported from next/navigation
|
||||
// For now, we'll handle this case by returning notFound
|
||||
// In a full implementation, you'd use: redirect(result.to);
|
||||
notFound();
|
||||
case 'error':
|
||||
// For now, treat errors as notFound
|
||||
// In a full implementation, you might render an error page
|
||||
notFound();
|
||||
case 'ok':
|
||||
return <ProfileLeaguesPageClient pageDto={result.dto} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<PageWrapper
|
||||
data={data}
|
||||
Template={ProfileLeaguesTemplate}
|
||||
loading={{ variant: 'skeleton', message: 'Loading your leagues...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
empty={{
|
||||
title: 'No leagues found',
|
||||
description: 'You are not a member of any leagues yet.',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import ProfileSettings from '@/components/drivers/ProfileSettings';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { useDriverProfile } from '@/hooks/driver/useDriverProfile';
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { useDriverProfile } from "@/lib/hooks/driver/useDriverProfile";
|
||||
import { useInject } from '@/lib/di/hooks/useInject';
|
||||
import { DRIVER_SERVICE_TOKEN, MEDIA_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import type {
|
||||
|
||||
@@ -5,8 +5,8 @@ import { SponsorshipRequestsTemplate } from '@/templates/SponsorshipRequestsTemp
|
||||
import {
|
||||
useSponsorshipRequestsPageData,
|
||||
useSponsorshipRequestMutations
|
||||
} from '@/hooks/sponsor/useSponsorshipRequestsPageData';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
} from "@/lib/hooks/sponsor/useSponsorshipRequestsPageData";
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
|
||||
export default function SponsorshipRequestsPage() {
|
||||
const currentDriverId = useEffectiveDriverId();
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
import { RaceResultsTemplate } from '@/templates/RaceResultsTemplate';
|
||||
import { useRaceResultsPageData } from '@/hooks/race/useRaceResultsPageData';
|
||||
import { useRaceResultsPageData } from "@/lib/hooks/race/useRaceResultsPageData";
|
||||
import { RaceResultsDataTransformer } from '@/lib/view-models/RaceResultsDataTransformer';
|
||||
import { useLeagueMemberships } from '@/hooks/league/useLeagueMemberships';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { useLeagueMemberships } from "@/lib/hooks/league/useLeagueMemberships";
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { useState } from 'react';
|
||||
import { notFound, useRouter } from 'next/navigation';
|
||||
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';
|
||||
|
||||
@@ -8,10 +8,11 @@ import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { RACE_STEWARDING_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import { RaceStewardingService } from '@/lib/services/races/RaceStewardingService';
|
||||
import type { RaceStewardingViewModel } from '@/lib/view-models/RaceStewardingViewModel';
|
||||
import { useLeagueMemberships } from '@/hooks/league/useLeagueMemberships';
|
||||
import { useEffectiveDriverId } from '@/hooks/useEffectiveDriverId';
|
||||
import { useLeagueMemberships } from "@/lib/hooks/league/useLeagueMemberships";
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';
|
||||
import { Gavel } from 'lucide-react';
|
||||
import type { LeagueMembershipsDTO } from '@/lib/types/generated/LeagueMembershipsDTO';
|
||||
|
||||
export default function RaceStewardingPage() {
|
||||
const router = useRouter();
|
||||
@@ -61,7 +62,7 @@ export default function RaceStewardingPage() {
|
||||
|
||||
// Fetch membership
|
||||
const { data: membershipsData } = useLeagueMemberships(pageData?.league?.id || '', currentDriverId || '');
|
||||
const currentMembership = membershipsData?.memberships.find(m => m.driverId === currentDriverId);
|
||||
const currentMembership = membershipsData?.members.find(m => m.driverId === currentDriverId);
|
||||
const isAdmin = currentMembership ? LeagueRoleUtility.isLeagueAdminOrHigherRole(currentMembership.role) : false;
|
||||
|
||||
// Actions
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
import { RacesAllTemplate, StatusFilter } from '@/templates/RacesAllTemplate';
|
||||
import { useAllRacesPageData } from '@/hooks/race/useAllRacesPageData';
|
||||
import { useAllRacesPageData } from "@/lib/hooks/race/useAllRacesPageData";
|
||||
import { Flag } from 'lucide-react';
|
||||
|
||||
const ITEMS_PER_PAGE = 10;
|
||||
|
||||
@@ -10,7 +10,7 @@ import StatusBadge from '@/components/ui/StatusBadge';
|
||||
import InfoBanner from '@/components/ui/InfoBanner';
|
||||
import PageHeader from '@/components/ui/PageHeader';
|
||||
import { siteConfig } from '@/lib/siteConfig';
|
||||
import { useSponsorBilling } from '@/hooks/sponsor/useSponsorBilling';
|
||||
import { useSponsorBilling } from "@/lib/hooks/sponsor/useSponsorBilling";
|
||||
import { useInject } from '@/lib/di/hooks/useInject';
|
||||
import { SPONSOR_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import {
|
||||
|
||||
@@ -8,7 +8,7 @@ import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import StatusBadge from '@/components/ui/StatusBadge';
|
||||
import InfoBanner from '@/components/ui/InfoBanner';
|
||||
import { useSponsorSponsorships } from '@/hooks/sponsor/useSponsorSponsorships';
|
||||
import { useSponsorSponsorships } from "@/lib/hooks/sponsor/useSponsorSponsorships";
|
||||
import {
|
||||
Megaphone,
|
||||
Trophy,
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
Smartphone,
|
||||
AlertCircle
|
||||
} from 'lucide-react';
|
||||
import { logoutAction } from '@/app/actions/logoutAction';
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
@@ -174,10 +175,8 @@ export default function SponsorSettingsPage() {
|
||||
|
||||
const handleDeleteAccount = () => {
|
||||
if (confirm('Are you sure you want to delete your sponsor account? This action cannot be undone. All sponsorship data will be permanently removed.')) {
|
||||
// Call logout API to clear session
|
||||
fetch('/api/auth/logout', { method: 'POST' }).finally(() => {
|
||||
router.push('/');
|
||||
});
|
||||
// Call the logout action directly
|
||||
logoutAction();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
91
apps/website/app/teams/TeamsPageClient.tsx
Normal file
91
apps/website/app/teams/TeamsPageClient.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import type { TeamsPageDto } from '@/lib/page-queries/page-queries/TeamsPageQuery';
|
||||
import { TeamsPresenter } from '@/lib/presenters/TeamsPresenter';
|
||||
import { TeamsTemplate } from '@/templates/TeamsTemplate';
|
||||
import type { TeamSummaryData } from '@/templates/view-data/TeamsViewData';
|
||||
|
||||
interface TeamsPageClientProps {
|
||||
pageDto: TeamsPageDto;
|
||||
}
|
||||
|
||||
export function TeamsPageClient({ pageDto }: TeamsPageClientProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// Use presenter to create ViewData
|
||||
const viewData = TeamsPresenter.createViewData(pageDto);
|
||||
|
||||
// UI state
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
|
||||
// Filter teams based on search query
|
||||
const filteredTeams = useMemo(() => {
|
||||
if (!searchQuery) return viewData.teams;
|
||||
|
||||
const query = searchQuery.toLowerCase();
|
||||
return viewData.teams.filter((team: TeamSummaryData) =>
|
||||
team.teamName.toLowerCase().includes(query) ||
|
||||
team.leagueName.toLowerCase().includes(query)
|
||||
);
|
||||
}, [viewData.teams, searchQuery]);
|
||||
|
||||
// Update viewData with filtered teams
|
||||
const templateViewData = {
|
||||
...viewData,
|
||||
teams: filteredTeams,
|
||||
};
|
||||
|
||||
// Event handlers
|
||||
const handleSearchChange = (query: string) => {
|
||||
setSearchQuery(query);
|
||||
};
|
||||
|
||||
const handleShowCreateForm = () => {
|
||||
setShowCreateForm(true);
|
||||
};
|
||||
|
||||
const handleHideCreateForm = () => {
|
||||
setShowCreateForm(false);
|
||||
};
|
||||
|
||||
const handleTeamClick = (teamId: string) => {
|
||||
router.push(`/teams/${teamId}`);
|
||||
};
|
||||
|
||||
const handleCreateSuccess = (teamId: string) => {
|
||||
setShowCreateForm(false);
|
||||
router.push(`/teams/${teamId}`);
|
||||
};
|
||||
|
||||
const handleBrowseTeams = () => {
|
||||
const element = document.getElementById('teams-list');
|
||||
if (element) {
|
||||
element.scrollIntoView({ behavior: 'smooth' });
|
||||
}
|
||||
};
|
||||
|
||||
const handleSkillLevelClick = (level: string) => {
|
||||
const element = document.getElementById(`level-${level}`);
|
||||
if (element) {
|
||||
element.scrollIntoView({ behavior: 'smooth' });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<TeamsTemplate
|
||||
teams={templateViewData.teams}
|
||||
searchQuery={searchQuery}
|
||||
showCreateForm={showCreateForm}
|
||||
onSearchChange={handleSearchChange}
|
||||
onShowCreateForm={handleShowCreateForm}
|
||||
onHideCreateForm={handleHideCreateForm}
|
||||
onTeamClick={handleTeamClick}
|
||||
onCreateSuccess={handleCreateSuccess}
|
||||
onBrowseTeams={handleBrowseTeams}
|
||||
onSkillLevelClick={handleSkillLevelClick}
|
||||
/>
|
||||
);
|
||||
}
|
||||
68
apps/website/app/teams/[id]/TeamDetailPageClient.tsx
Normal file
68
apps/website/app/teams/[id]/TeamDetailPageClient.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import type { TeamDetailPageDto } from '@/lib/page-queries/page-queries/TeamDetailPageQuery';
|
||||
import { TeamDetailPresenter } from '@/lib/presenters/TeamDetailPresenter';
|
||||
import TeamDetailTemplate from '@/templates/TeamDetailTemplate';
|
||||
|
||||
type Tab = 'overview' | 'roster' | 'standings' | 'admin';
|
||||
|
||||
interface TeamDetailPageClientProps {
|
||||
pageDto: TeamDetailPageDto;
|
||||
}
|
||||
|
||||
export function TeamDetailPageClient({ pageDto }: TeamDetailPageClientProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// Use presenter to create ViewData
|
||||
const viewData = TeamDetailPresenter.createViewData(pageDto);
|
||||
|
||||
// UI state
|
||||
const [activeTab, setActiveTab] = useState<Tab>('overview');
|
||||
const [loading] = useState(false);
|
||||
|
||||
// Event handlers
|
||||
const handleTabChange = (tab: Tab) => {
|
||||
setActiveTab(tab);
|
||||
};
|
||||
|
||||
const handleUpdate = () => {
|
||||
// Trigger a refresh by reloading the page
|
||||
router.refresh();
|
||||
};
|
||||
|
||||
const handleRemoveMember = (driverId: string) => {
|
||||
// This would call an API to remove the member
|
||||
// For now, just log
|
||||
console.log('Remove member:', driverId);
|
||||
// In a real implementation, you'd have a mutation hook here
|
||||
alert('Remove member functionality would be implemented here');
|
||||
};
|
||||
|
||||
const handleChangeRole = (driverId: string, newRole: 'owner' | 'admin' | 'member') => {
|
||||
// This would call an API to change the role
|
||||
console.log('Change role:', driverId, newRole);
|
||||
// In a real implementation, you'd have a mutation hook here
|
||||
alert('Change role functionality would be implemented here');
|
||||
};
|
||||
|
||||
const handleGoBack = () => {
|
||||
router.back();
|
||||
};
|
||||
|
||||
return (
|
||||
<TeamDetailTemplate
|
||||
team={viewData.team}
|
||||
memberships={viewData.memberships}
|
||||
activeTab={activeTab}
|
||||
loading={loading}
|
||||
isAdmin={viewData.isAdmin}
|
||||
onTabChange={handleTabChange}
|
||||
onUpdate={handleUpdate}
|
||||
onRemoveMember={handleRemoveMember}
|
||||
onChangeRole={handleChangeRole}
|
||||
onGoBack={handleGoBack}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,102 +1,22 @@
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { TeamService } from '@/lib/services/teams/TeamService';
|
||||
import { TeamsApiClient } from '@/lib/api/teams/TeamsApiClient';
|
||||
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { TeamDetailsViewModel } from '@/lib/view-models/TeamDetailsViewModel';
|
||||
import { TeamMemberViewModel } from '@/lib/view-models/TeamMemberViewModel';
|
||||
import TeamDetailTemplate from '@/templates/TeamDetailTemplate';
|
||||
|
||||
// Template wrapper to adapt TeamDetailTemplate for SSR
|
||||
interface TeamDetailData {
|
||||
team: TeamDetailsViewModel;
|
||||
memberships: TeamMemberViewModel[];
|
||||
isAdmin: boolean;
|
||||
}
|
||||
|
||||
function TeamDetailTemplateWrapper({ data }: { data: TeamDetailData }) {
|
||||
return (
|
||||
<TeamDetailTemplate
|
||||
team={data.team}
|
||||
memberships={data.memberships}
|
||||
activeTab="overview"
|
||||
loading={false}
|
||||
isAdmin={data.isAdmin}
|
||||
// Event handlers are no-ops for SSR (client will handle real interactions)
|
||||
onTabChange={() => {}}
|
||||
onUpdate={() => {}}
|
||||
onRemoveMember={() => {}}
|
||||
onChangeRole={() => {}}
|
||||
onGoBack={() => {}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
import { TeamDetailPageQuery } from '@/lib/page-queries/TeamDetailPageQuery';
|
||||
import TeamDetailPageClient from './TeamDetailPageClient';
|
||||
|
||||
export default async function Page({ params }: { params: { id: string } }) {
|
||||
// Validate params
|
||||
if (!params.id) {
|
||||
notFound();
|
||||
}
|
||||
const result = await TeamDetailPageQuery.execute(params.id);
|
||||
|
||||
// Fetch data using PageDataFetcher.fetchManual
|
||||
const data = await PageDataFetcher.fetchManual(async () => {
|
||||
// Manual dependency creation
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: true,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
|
||||
// Create API client
|
||||
const teamsApiClient = new TeamsApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Create service
|
||||
const service = new TeamService(teamsApiClient);
|
||||
|
||||
// For server-side, we need a current driver ID
|
||||
// This would typically come from session, but for server components we'll use a placeholder
|
||||
const currentDriverId = ''; // Placeholder - would need session handling
|
||||
|
||||
// Fetch team details
|
||||
const teamData = await service.getTeamDetails(params.id, currentDriverId);
|
||||
|
||||
if (!teamData) {
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
return <TeamDetailPageClient pageDto={result.dto} />;
|
||||
case 'notFound':
|
||||
notFound();
|
||||
case 'redirect':
|
||||
// This would typically use redirect() from next/navigation
|
||||
// but we need to handle it at the page level
|
||||
return null;
|
||||
}
|
||||
|
||||
// Fetch team members
|
||||
const membersData = await service.getTeamMembers(params.id, currentDriverId, teamData.ownerId || '');
|
||||
|
||||
// Determine admin status
|
||||
const isAdmin = teamData.isOwner ||
|
||||
(membersData || []).some((m: any) => m.driverId === currentDriverId && (m.role === 'manager' || m.role === 'owner'));
|
||||
|
||||
return {
|
||||
team: teamData,
|
||||
memberships: membersData || [],
|
||||
isAdmin,
|
||||
};
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
notFound();
|
||||
case 'error':
|
||||
// For now, treat errors as not found
|
||||
// In production, you might want a proper error page
|
||||
notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<PageWrapper
|
||||
data={data}
|
||||
Template={TeamDetailTemplateWrapper}
|
||||
loading={{ variant: 'skeleton', message: 'Loading team details...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
empty={{
|
||||
title: 'Team not found',
|
||||
description: 'The team you are looking for does not exist or has been removed.',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -19,9 +19,9 @@ export default async function TeamLeaderboardPage() {
|
||||
);
|
||||
|
||||
// Prepare data for template
|
||||
const data: TeamSummaryViewModel[] | null = teamsData as TeamSummaryViewModel[] | null;
|
||||
const data: TeamSummaryViewModel[] | null = teamsData;
|
||||
|
||||
const hasData = (teamsData as any)?.length > 0;
|
||||
const hasData = (teamsData?.length ?? 0) > 0;
|
||||
|
||||
// Handle loading state (should be fast since we're using async/await)
|
||||
const isLoading = false;
|
||||
|
||||
@@ -1,97 +1,22 @@
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import TeamsTemplate from '@/templates/TeamsTemplate';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { TeamService } from '@/lib/services/teams/TeamService';
|
||||
import { TeamsApiClient } from '@/lib/api/teams/TeamsApiClient';
|
||||
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
import { notFound } from 'next/navigation';
|
||||
import type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';
|
||||
|
||||
// Helper to compute derived data for SSR
|
||||
function computeDerivedData(teams: TeamSummaryViewModel[]) {
|
||||
// Group teams by performance level (skill level)
|
||||
const teamsByLevel = teams.reduce((acc, team) => {
|
||||
const level = team.performanceLevel || 'intermediate';
|
||||
if (!acc[level]) {
|
||||
acc[level] = [];
|
||||
}
|
||||
acc[level].push(team);
|
||||
return acc;
|
||||
}, {} as Record<string, TeamSummaryViewModel[]>);
|
||||
|
||||
// Get top teams (by rating, descending)
|
||||
const topTeams = [...teams]
|
||||
.filter(t => t.rating !== undefined)
|
||||
.sort((a, b) => (b.rating || 0) - (a.rating || 0))
|
||||
.slice(0, 5);
|
||||
|
||||
// Count recruiting teams
|
||||
const recruitingCount = teams.filter(t => t.isRecruiting).length;
|
||||
|
||||
// For SSR, filtered teams = all teams (no search filter applied server-side)
|
||||
const filteredTeams = teams;
|
||||
|
||||
return {
|
||||
teamsByLevel,
|
||||
topTeams,
|
||||
recruitingCount,
|
||||
filteredTeams,
|
||||
};
|
||||
}
|
||||
|
||||
// Template wrapper for SSR
|
||||
function TeamsTemplateWrapper({ data }: { data: TeamSummaryViewModel[] }) {
|
||||
const derived = computeDerivedData(data);
|
||||
|
||||
// Provide default values for SSR
|
||||
// The template will handle client-side state management
|
||||
return (
|
||||
<TeamsTemplate
|
||||
teams={data}
|
||||
isLoading={false}
|
||||
searchQuery=""
|
||||
showCreateForm={false}
|
||||
teamsByLevel={derived.teamsByLevel}
|
||||
topTeams={derived.topTeams}
|
||||
recruitingCount={derived.recruitingCount}
|
||||
filteredTeams={derived.filteredTeams}
|
||||
// No-op handlers for SSR (client will override)
|
||||
onSearchChange={() => {}}
|
||||
onShowCreateForm={() => {}}
|
||||
onHideCreateForm={() => {}}
|
||||
onTeamClick={() => {}}
|
||||
onCreateSuccess={() => {}}
|
||||
onBrowseTeams={() => {}}
|
||||
onSkillLevelClick={() => {}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
import { TeamsPageQuery } from '@/lib/page-queries/TeamsPageQuery';
|
||||
import TeamsPageClient from './TeamsPageClient';
|
||||
|
||||
export default async function Page() {
|
||||
const data = await PageDataFetcher.fetchManual(async () => {
|
||||
// Manual dependency creation
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: true,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
const result = await TeamsPageQuery.execute();
|
||||
|
||||
// Create API client
|
||||
const teamsApiClient = new TeamsApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Create service
|
||||
const service = new TeamService(teamsApiClient);
|
||||
|
||||
return await service.getAllTeams();
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
notFound();
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
return <TeamsPageClient pageDto={result.dto} />;
|
||||
case 'notFound':
|
||||
notFound();
|
||||
case 'redirect':
|
||||
// This would typically use redirect() from next/navigation
|
||||
// but we need to handle it at the page level
|
||||
return null;
|
||||
case 'error':
|
||||
// For now, treat errors as not found
|
||||
// In production, you might want a proper error page
|
||||
notFound();
|
||||
}
|
||||
|
||||
return <PageWrapper data={data} Template={TeamsTemplateWrapper} />;
|
||||
}
|
||||
Reference in New Issue
Block a user