website refactor

This commit is contained in:
2026-01-14 16:28:39 +01:00
parent 85e09b6f4d
commit 4b7d82ab43
119 changed files with 2403 additions and 1615 deletions

View File

@@ -1,5 +1,5 @@
import { AdminDashboardPageQuery } from '@/lib/page-queries/AdminDashboardPageQuery'; import { AdminDashboardPageQuery } from '@/lib/page-queries/AdminDashboardPageQuery';
import { AdminDashboardTemplate } from '@/templates/AdminDashboardTemplate'; import { AdminDashboardWrapper } from '@/components/admin/AdminDashboardWrapper';
import { ErrorBanner } from '@/components/ui/ErrorBanner'; import { ErrorBanner } from '@/components/ui/ErrorBanner';
export default async function AdminPage() { export default async function AdminPage() {
@@ -27,7 +27,6 @@ export default async function AdminPage() {
const output = result.unwrap(); const output = result.unwrap();
// For now, use empty callbacks. In a real app, these would be Server Actions // Pass to client wrapper for UI interactions
// that trigger revalidation or navigation return <AdminDashboardWrapper initialViewData={output} />;
return <AdminDashboardTemplate adminDashboardViewData={output} onRefresh={() => {}} isLoading={false} />;
} }

View File

@@ -1,28 +1,10 @@
import { AdminUsersPageQuery } from '@/lib/page-queries/AdminUsersPageQuery'; import { AdminUsersPageQuery } from '@/lib/page-queries/AdminUsersPageQuery';
import { AdminUsersWrapper } from './AdminUsersWrapper'; import { AdminUsersWrapper } from '@/components/admin/AdminUsersWrapper';
import { ErrorBanner } from '@/components/ui/ErrorBanner'; import { ErrorBanner } from '@/components/ui/ErrorBanner';
interface AdminUsersPageProps { export default async function AdminUsersPage() {
searchParams?: {
search?: string;
role?: string;
status?: string;
page?: string;
};
}
export default async function AdminUsersPage({ searchParams }: AdminUsersPageProps) {
// Parse query parameters
const query = {
search: searchParams?.search,
role: searchParams?.role,
status: searchParams?.status,
page: searchParams?.page ? parseInt(searchParams.page, 10) : 1,
limit: 50,
};
// Execute PageQuery using static method // Execute PageQuery using static method
const result = await AdminUsersPageQuery.execute(query); const result = await AdminUsersPageQuery.execute();
// Handle errors // Handle errors
if (result.isErr()) { if (result.isErr()) {

View File

@@ -1,6 +1,6 @@
/** /**
* Forgot Password Client Component * Forgot Password Client Component
* *
* Handles client-side forgot password flow. * Handles client-side forgot password flow.
*/ */
@@ -12,6 +12,7 @@ import { ForgotPasswordTemplate } from '@/templates/auth/ForgotPasswordTemplate'
import { ForgotPasswordMutation } from '@/lib/mutations/auth/ForgotPasswordMutation'; import { ForgotPasswordMutation } from '@/lib/mutations/auth/ForgotPasswordMutation';
import { ForgotPasswordViewModelBuilder } from '@/lib/builders/view-models/ForgotPasswordViewModelBuilder'; import { ForgotPasswordViewModelBuilder } from '@/lib/builders/view-models/ForgotPasswordViewModelBuilder';
import { ForgotPasswordViewModel } from '@/lib/view-models/auth/ForgotPasswordViewModel'; import { ForgotPasswordViewModel } from '@/lib/view-models/auth/ForgotPasswordViewModel';
import { ForgotPasswordFormValidation } from '@/lib/utilities/authValidation';
interface ForgotPasswordClientProps { interface ForgotPasswordClientProps {
viewData: ForgotPasswordViewData; viewData: ForgotPasswordViewData;
@@ -19,24 +20,67 @@ interface ForgotPasswordClientProps {
export function ForgotPasswordClient({ viewData }: ForgotPasswordClientProps) { export function ForgotPasswordClient({ viewData }: ForgotPasswordClientProps) {
// Build ViewModel from ViewData // Build ViewModel from ViewData
const [viewModel, setViewModel] = useState<ForgotPasswordViewModel>(() => const [viewModel, setViewModel] = useState<ForgotPasswordViewModel>(() =>
ForgotPasswordViewModelBuilder.build(viewData) ForgotPasswordViewModelBuilder.build(viewData)
); );
const [formData, setFormData] = useState({ email: '' }); // Handle form field changes
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = e.target;
setViewModel(prev => {
const newFormState = {
...prev.formState,
fields: {
...prev.formState.fields,
[name]: {
...prev.formState.fields[name as keyof typeof prev.formState.fields],
value,
touched: true,
error: undefined,
},
},
};
return prev.withFormState(newFormState);
});
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
const formData = {
email: viewModel.formState.fields.email.value as string,
};
// Validate form
const validationErrors = ForgotPasswordFormValidation.validateForm(formData);
if (validationErrors.length > 0) {
setViewModel(prev => {
const newFormState = {
...prev.formState,
isValid: false,
submitCount: prev.formState.submitCount + 1,
fields: {
...prev.formState.fields,
email: {
...prev.formState.fields.email,
error: validationErrors.find(e => e.field === 'email')?.message,
touched: true,
},
},
};
return prev.withFormState(newFormState);
});
return;
}
// Update submitting state // Update submitting state
setViewModel(prev => prev.withMutationState(true, null)); setViewModel(prev => prev.withMutationState(true, null));
try { try {
// Execute forgot password mutation // Execute forgot password mutation
const mutation = new ForgotPasswordMutation(); const mutation = new ForgotPasswordMutation();
const result = await mutation.execute({ const result = await mutation.execute(formData);
email: formData.email,
});
if (result.isErr()) { if (result.isErr()) {
const error = result.getError(); const error = result.getError();
@@ -68,7 +112,7 @@ export function ForgotPasswordClient({ viewData }: ForgotPasswordClientProps) {
<ForgotPasswordTemplate <ForgotPasswordTemplate
viewData={templateViewData} viewData={templateViewData}
formActions={{ formActions={{
setFormData, handleChange,
handleSubmit, handleSubmit,
setShowSuccess: (show) => { setShowSuccess: (show) => {
if (!show) { if (!show) {

View File

@@ -1,6 +1,6 @@
/** /**
* Reset Password Client Component * Reset Password Client Component
* *
* Handles client-side reset password flow. * Handles client-side reset password flow.
*/ */
@@ -13,6 +13,7 @@ import { ResetPasswordTemplate } from '@/templates/auth/ResetPasswordTemplate';
import { ResetPasswordMutation } from '@/lib/mutations/auth/ResetPasswordMutation'; import { ResetPasswordMutation } from '@/lib/mutations/auth/ResetPasswordMutation';
import { ResetPasswordViewModelBuilder } from '@/lib/builders/view-models/ResetPasswordViewModelBuilder'; import { ResetPasswordViewModelBuilder } from '@/lib/builders/view-models/ResetPasswordViewModelBuilder';
import { ResetPasswordViewModel } from '@/lib/view-models/auth/ResetPasswordViewModel'; import { ResetPasswordViewModel } from '@/lib/view-models/auth/ResetPasswordViewModel';
import { ResetPasswordFormValidation } from '@/lib/utilities/authValidation';
import { routes } from '@/lib/routing/RouteConfig'; import { routes } from '@/lib/routing/RouteConfig';
interface ResetPasswordClientProps { interface ResetPasswordClientProps {
@@ -22,23 +23,63 @@ interface ResetPasswordClientProps {
export function ResetPasswordClient({ viewData }: ResetPasswordClientProps) { export function ResetPasswordClient({ viewData }: ResetPasswordClientProps) {
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
// Build ViewModel from ViewData // Build ViewModel from ViewData
const [viewModel, setViewModel] = useState<ResetPasswordViewModel>(() => const [viewModel, setViewModel] = useState<ResetPasswordViewModel>(() =>
ResetPasswordViewModelBuilder.build(viewData) ResetPasswordViewModelBuilder.build(viewData)
); );
const [formData, setFormData] = useState({ // Handle form field changes
newPassword: '', const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
confirmPassword: '' const { name, value } = e.target;
});
setViewModel(prev => {
const newFormState = {
...prev.formState,
fields: {
...prev.formState.fields,
[name]: {
...prev.formState.fields[name as keyof typeof prev.formState.fields],
value,
touched: true,
error: undefined,
},
},
};
return prev.withFormState(newFormState);
});
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
// Validate passwords match const formData = {
if (formData.newPassword !== formData.confirmPassword) { newPassword: viewModel.formState.fields.newPassword.value as string,
setViewModel(prev => prev.withMutationState(false, 'Passwords do not match')); confirmPassword: viewModel.formState.fields.confirmPassword.value as string,
};
// Validate form
const validationErrors = ResetPasswordFormValidation.validateForm(formData);
if (validationErrors.length > 0) {
setViewModel(prev => {
const newFormState = {
...prev.formState,
isValid: false,
submitCount: prev.formState.submitCount + 1,
fields: {
...prev.formState.fields,
...validationErrors.reduce((acc, error) => ({
...acc,
[error.field]: {
...prev.formState.fields[error.field],
error: error.message,
touched: true,
},
}), {}),
},
};
return prev.withFormState(newFormState);
});
return; return;
} }
@@ -68,7 +109,7 @@ export function ResetPasswordClient({ viewData }: ResetPasswordClientProps) {
// Success // Success
const data = result.unwrap(); const data = result.unwrap();
setViewModel(prev => prev.withSuccess(data.message)); setViewModel(prev => prev.withSuccess(data.message));
// Redirect to login after a delay // Redirect to login after a delay
setTimeout(() => { setTimeout(() => {
router.push(routes.auth.login); router.push(routes.auth.login);
@@ -116,7 +157,7 @@ export function ResetPasswordClient({ viewData }: ResetPasswordClientProps) {
submitError={templateViewData.submitError} submitError={templateViewData.submitError}
// Add the additional props // Add the additional props
formActions={{ formActions={{
setFormData, handleChange,
handleSubmit, handleSubmit,
setShowSuccess: (show) => { setShowSuccess: (show) => {
if (!show) { if (!show) {

View File

@@ -1,6 +1,6 @@
/** /**
* Signup Client Component * Signup Client Component
* *
* Handles client-side signup flow. * Handles client-side signup flow.
*/ */
@@ -14,6 +14,7 @@ import { SignupTemplate } from '@/templates/auth/SignupTemplate';
import { SignupMutation } from '@/lib/mutations/auth/SignupMutation'; import { SignupMutation } from '@/lib/mutations/auth/SignupMutation';
import { SignupViewModelBuilder } from '@/lib/builders/view-models/SignupViewModelBuilder'; import { SignupViewModelBuilder } from '@/lib/builders/view-models/SignupViewModelBuilder';
import { SignupViewModel } from '@/lib/view-models/auth/SignupViewModel'; import { SignupViewModel } from '@/lib/view-models/auth/SignupViewModel';
import { SignupFormValidation } from '@/lib/utilities/authValidation';
interface SignupClientProps { interface SignupClientProps {
viewData: SignupViewData; viewData: SignupViewData;
@@ -23,26 +24,66 @@ export function SignupClient({ viewData }: SignupClientProps) {
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const { refreshSession } = useAuth(); const { refreshSession } = useAuth();
// Build ViewModel from ViewData // Build ViewModel from ViewData
const [viewModel, setViewModel] = useState<SignupViewModel>(() => const [viewModel, setViewModel] = useState<SignupViewModel>(() =>
SignupViewModelBuilder.build(viewData) SignupViewModelBuilder.build(viewData)
); );
const [formData, setFormData] = useState({ // Handle form field changes
firstName: '', const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
lastName: '', const { name, value } = e.target;
email: '',
password: '', setViewModel(prev => {
confirmPassword: '' const newFormState = {
}); ...prev.formState,
fields: {
...prev.formState.fields,
[name]: {
...prev.formState.fields[name as keyof typeof prev.formState.fields],
value,
touched: true,
error: undefined,
},
},
};
return prev.withFormState(newFormState);
});
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); e.preventDefault();
// Validate passwords match const formData = {
if (formData.password !== formData.confirmPassword) { firstName: viewModel.formState.fields.firstName.value as string,
setViewModel(prev => prev.withMutationState(false, 'Passwords do not match')); lastName: viewModel.formState.fields.lastName.value as string,
email: viewModel.formState.fields.email.value as string,
password: viewModel.formState.fields.password.value as string,
confirmPassword: viewModel.formState.fields.confirmPassword.value as string,
};
// Validate form
const validationErrors = SignupFormValidation.validateForm(formData);
if (validationErrors.length > 0) {
setViewModel(prev => {
const newFormState = {
...prev.formState,
isValid: false,
submitCount: prev.formState.submitCount + 1,
fields: {
...prev.formState.fields,
...validationErrors.reduce((acc, error) => ({
...acc,
[error.field]: {
...prev.formState.fields[error.field],
error: error.message,
touched: true,
},
}), {}),
},
};
return prev.withFormState(newFormState);
});
return; return;
} }
@@ -50,15 +91,15 @@ export function SignupClient({ viewData }: SignupClientProps) {
setViewModel(prev => prev.withMutationState(true, null)); setViewModel(prev => prev.withMutationState(true, null));
try { try {
// Transform to DTO format // Generate display name
const displayName = `${formData.firstName} ${formData.lastName}`.trim(); const displayName = SignupFormValidation.generateDisplayName(formData.firstName, formData.lastName);
// Execute signup mutation // Execute signup mutation
const mutation = new SignupMutation(); const mutation = new SignupMutation();
const result = await mutation.execute({ const result = await mutation.execute({
email: formData.email, email: formData.email,
password: formData.password, password: formData.password,
displayName: displayName || formData.firstName || formData.lastName, displayName,
}); });
if (result.isErr()) { if (result.isErr()) {
@@ -69,7 +110,7 @@ export function SignupClient({ viewData }: SignupClientProps) {
// Success - refresh session and redirect // Success - refresh session and redirect
await refreshSession(); await refreshSession();
const returnTo = searchParams.get('returnTo') ?? '/onboarding'; const returnTo = searchParams.get('returnTo') ?? '/onboarding';
router.push(returnTo); router.push(returnTo);
} catch (error) { } catch (error) {
@@ -105,7 +146,7 @@ export function SignupClient({ viewData }: SignupClientProps) {
<SignupTemplate <SignupTemplate
viewData={templateViewData} viewData={templateViewData}
formActions={{ formActions={{
setFormData, handleChange,
handleSubmit, handleSubmit,
setShowPassword: togglePassword, setShowPassword: togglePassword,
setShowConfirmPassword: toggleConfirmPassword, setShowConfirmPassword: toggleConfirmPassword,

View File

@@ -4,43 +4,25 @@ import { DriverProfilePageQuery } from '@/lib/page-queries/page-queries/DriverPr
import { DriverProfilePageClient } from '@/components/drivers/DriverProfilePageClient'; import { DriverProfilePageClient } from '@/components/drivers/DriverProfilePageClient';
export default async function DriverProfilePage({ params }: { params: { id: string } }) { export default async function DriverProfilePage({ params }: { params: { id: string } }) {
// Execute the page query
const result = await DriverProfilePageQuery.execute(params.id); const result = await DriverProfilePageQuery.execute(params.id);
// Handle different result statuses if (result.isErr()) {
switch (result.status) { const error = result.getError();
case 'notFound': if (error === 'NotFound') {
redirect(routes.error.notFound); redirect(routes.error.notFound);
case 'redirect': }
redirect(result.to); return (
case 'error': <DriverProfilePageClient
// Pass error to client component pageDto={null}
return ( error={error}
<DriverProfilePageClient />
pageDto={null} );
error={result.errorId}
/>
);
case 'ok':
const viewModel = result.dto;
const hasData = !!viewModel.currentDriver;
if (!hasData) {
return (
<DriverProfilePageClient
pageDto={null}
empty={{
title: 'Driver not found',
description: 'The driver profile may not exist or you may not have access',
}}
/>
);
}
return (
<DriverProfilePageClient
pageDto={viewModel}
/>
);
} }
const viewData = result.unwrap();
return (
<DriverProfilePageClient
pageDto={viewData}
/>
);
} }

View File

@@ -4,43 +4,25 @@ import { DriversPageQuery } from '@/lib/page-queries/page-queries/DriversPageQue
import { DriversPageClient } from '@/components/drivers/DriversPageClient'; import { DriversPageClient } from '@/components/drivers/DriversPageClient';
export default async function Page() { export default async function Page() {
// Execute the page query
const result = await DriversPageQuery.execute(); const result = await DriversPageQuery.execute();
// Handle different result statuses if (result.isErr()) {
switch (result.status) { const error = result.getError();
case 'notFound': if (error === 'NotFound') {
redirect(routes.error.notFound); redirect(routes.error.notFound);
case 'redirect': }
redirect(result.to); return (
case 'error': <DriversPageClient
// Pass error to client component pageDto={null}
return ( error={error}
<DriversPageClient />
pageDto={null} );
error={result.errorId}
/>
);
case 'ok':
const viewModel = result.dto;
const hasData = (viewModel.drivers?.length ?? 0) > 0;
if (!hasData) {
return (
<DriversPageClient
pageDto={null}
empty={{
title: 'No drivers found',
description: 'There are no drivers in the system yet.',
}}
/>
);
}
return (
<DriversPageClient
pageDto={viewModel}
/>
);
} }
const viewData = result.unwrap();
return (
<DriversPageClient
pageDto={viewData}
/>
);
} }

View File

@@ -1,61 +0,0 @@
'use client';
import { useRouter } from 'next/navigation';
import { LeaderboardsTemplate } from '@/templates/LeaderboardsTemplate';
import type { LeaderboardsViewData } from '@/lib/view-data/LeaderboardsViewData';
import { routes } from '@/lib/routing/RouteConfig';
export function LeaderboardsPageWrapper({ data }: { data: LeaderboardsViewData | null }) {
const router = useRouter();
if (!data || (!data.drivers && !data.teams)) {
return null;
}
const handleDriverClick = (driverId: string) => {
router.push(routes.driver.detail(driverId));
};
const handleTeamClick = (teamId: string) => {
router.push(routes.team.detail(teamId));
};
const handleNavigateToDrivers = () => {
router.push(routes.leaderboards.drivers);
};
const handleNavigateToTeams = () => {
router.push(routes.team.leaderboard);
};
// Transform ViewData to template props (simple field mapping only)
const templateData = {
drivers: data.drivers.map(d => ({
id: d.id,
name: d.name,
rating: d.rating,
skillLevel: d.skillLevel,
nationality: d.nationality,
wins: d.wins,
rank: d.rank,
avatarUrl: d.avatarUrl,
position: d.position,
})),
teams: data.teams.map(t => ({
id: t.id,
name: t.name,
tag: t.tag,
memberCount: t.memberCount,
category: t.category,
totalWins: t.totalWins,
logoUrl: t.logoUrl,
position: t.position,
})),
onDriverClick: handleDriverClick,
onTeamClick: handleTeamClick,
onNavigateToDrivers: handleNavigateToDrivers,
onNavigateToTeams: handleNavigateToTeams,
};
return <LeaderboardsTemplate {...templateData} />;
}

View File

@@ -1,14 +1,14 @@
import { notFound, redirect } from 'next/navigation'; import { notFound, redirect } from 'next/navigation';
import { LeaderboardsPageQuery } from '@/lib/page-queries/page-queries/LeaderboardsPageQuery'; import { LeaderboardsPageQuery } from '@/lib/page-queries/page-queries/LeaderboardsPageQuery';
import { LeaderboardsPageWrapper } from './LeaderboardsPageWrapper'; import { LeaderboardsTemplate } from '@/templates/LeaderboardsTemplate';
import { routes } from '@/lib/routing/RouteConfig'; import { routes } from '@/lib/routing/RouteConfig';
export default async function LeaderboardsPage() { export default async function LeaderboardsPage() {
const result = await LeaderboardsPageQuery.execute(); const result = await LeaderboardsPageQuery.execute();
if (result.isErr()) { if (result.isErr()) {
const error = result.getError(); const error = result.getError();
// Handle different error types // Handle different error types
if (error === 'notFound') { if (error === 'notFound') {
notFound(); notFound();
@@ -20,8 +20,8 @@ export default async function LeaderboardsPage() {
notFound(); notFound();
} }
} }
// Success // Success
const viewData = result.unwrap(); const viewData = result.unwrap();
return <LeaderboardsPageWrapper data={viewData} />; return <LeaderboardsTemplate viewData={viewData} />;
} }

View File

@@ -1,6 +1,7 @@
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import { LeagueDetailPageQuery } from '@/lib/page-queries/page-queries/LeagueDetailPageQuery'; import { LeagueDetailPageQuery } from '@/lib/page-queries/page-queries/LeagueDetailPageQuery';
import { LeagueDetailTemplate } from '@/templates/LeagueDetailTemplate'; import { LeagueDetailTemplate } from '@/templates/LeagueDetailTemplate';
import { Text } from '@/ui/Text';
export default async function LeagueLayout({ export default async function LeagueLayout({
children, children,
@@ -27,7 +28,7 @@ export default async function LeagueLayout({
leagueDescription="Failed to load league" leagueDescription="Failed to load league"
tabs={[]} tabs={[]}
> >
<div className="text-center text-gray-400">Failed to load league</div> <Text align="center" className="text-gray-400">Failed to load league</Text>
</LeagueDetailTemplate> </LeagueDetailTemplate>
); );
} }

View File

@@ -2,6 +2,7 @@ import { notFound } from 'next/navigation';
import { LeagueDetailTemplate } from '@/templates/LeagueDetailTemplate'; import { LeagueDetailTemplate } from '@/templates/LeagueDetailTemplate';
import { LeagueDetailPageQuery } from '@/lib/page-queries/page-queries/LeagueDetailPageQuery'; import { LeagueDetailPageQuery } from '@/lib/page-queries/page-queries/LeagueDetailPageQuery';
import { LeagueDetailViewDataBuilder } from '@/lib/builders/view-data/LeagueDetailViewDataBuilder'; import { LeagueDetailViewDataBuilder } from '@/lib/builders/view-data/LeagueDetailViewDataBuilder';
import { ErrorBanner } from '@/components/ui/ErrorBanner';
interface Props { interface Props {
params: { id: string }; params: { id: string };
@@ -26,11 +27,11 @@ export default async function Page({ params }: Props) {
default: default:
// Return error state // Return error state
return ( return (
<div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8"> <ErrorBanner
<div className="max-w-6xl mx-auto"> title="Load Failed"
<div className="text-center text-gray-400">Failed to load league details</div> message="Failed to load league details"
</div> variant="error"
</div> />
); );
} }
} }

View File

@@ -1,5 +1,5 @@
import { notFound } from 'next/navigation'; import { notFound } from 'next/navigation';
import { LeaguesTemplate } from '@/templates/LeaguesTemplate'; import { LeaguesClient } from '@/components/leagues/LeaguesClient';
import { LeaguesPageQuery } from '@/lib/page-queries/page-queries/LeaguesPageQuery'; import { LeaguesPageQuery } from '@/lib/page-queries/page-queries/LeaguesPageQuery';
export default async function Page() { export default async function Page() {
@@ -20,11 +20,11 @@ export default async function Page() {
case 'UNKNOWN_ERROR': case 'UNKNOWN_ERROR':
default: default:
// Return error state - use LeaguesTemplate with empty data // Return error state - use LeaguesTemplate with empty data
return <LeaguesTemplate data={{ leagues: [] }} />; return <LeaguesClient viewData={{ leagues: [] }} />;
} }
} }
const viewData = result.unwrap(); const viewData = result.unwrap();
return <LeaguesTemplate data={viewData} />; return <LeaguesClient viewData={viewData} />;
} }

View File

@@ -18,8 +18,8 @@ export async function GET(
} }
const viewData = result.unwrap(); const viewData = result.unwrap();
return new NextResponse(viewData.buffer, { return new NextResponse(Buffer.from(viewData.buffer, 'base64'), {
headers: { headers: {
'Content-Type': viewData.contentType, 'Content-Type': viewData.contentType,
'Cache-Control': 'public, max-age=3600', 'Cache-Control': 'public, max-age=3600',

View File

@@ -18,8 +18,8 @@ export async function GET(
} }
const viewData = result.unwrap(); const viewData = result.unwrap();
return new NextResponse(viewData.buffer, { return new NextResponse(Buffer.from(viewData.buffer, 'base64'), {
headers: { headers: {
'Content-Type': viewData.contentType, 'Content-Type': viewData.contentType,
'Cache-Control': 'public, max-age=3600', 'Cache-Control': 'public, max-age=3600',

View File

@@ -18,8 +18,8 @@ export async function GET(
} }
const viewData = result.unwrap(); const viewData = result.unwrap();
return new NextResponse(viewData.buffer, { return new NextResponse(Buffer.from(viewData.buffer, 'base64'), {
headers: { headers: {
'Content-Type': viewData.contentType, 'Content-Type': viewData.contentType,
'Cache-Control': 'public, max-age=3600', 'Cache-Control': 'public, max-age=3600',

View File

@@ -18,8 +18,8 @@ export async function GET(
} }
const viewData = result.unwrap(); const viewData = result.unwrap();
return new NextResponse(viewData.buffer, { return new NextResponse(Buffer.from(viewData.buffer, 'base64'), {
headers: { headers: {
'Content-Type': viewData.contentType, 'Content-Type': viewData.contentType,
'Cache-Control': 'public, max-age=3600', 'Cache-Control': 'public, max-age=3600',

View File

@@ -18,8 +18,8 @@ export async function GET(
} }
const viewData = result.unwrap(); const viewData = result.unwrap();
return new NextResponse(viewData.buffer, { return new NextResponse(Buffer.from(viewData.buffer, 'base64'), {
headers: { headers: {
'Content-Type': viewData.contentType, 'Content-Type': viewData.contentType,
'Cache-Control': 'public, max-age=3600', 'Cache-Control': 'public, max-age=3600',

View File

@@ -18,8 +18,8 @@ export async function GET(
} }
const viewData = result.unwrap(); const viewData = result.unwrap();
return new NextResponse(viewData.buffer, { return new NextResponse(Buffer.from(viewData.buffer, 'base64'), {
headers: { headers: {
'Content-Type': viewData.contentType, 'Content-Type': viewData.contentType,
'Cache-Control': 'public, max-age=3600', 'Cache-Control': 'public, max-age=3600',

View File

@@ -18,8 +18,8 @@ export async function GET(
} }
const viewData = result.unwrap(); const viewData = result.unwrap();
return new NextResponse(viewData.buffer, { return new NextResponse(Buffer.from(viewData.buffer, 'base64'), {
headers: { headers: {
'Content-Type': viewData.contentType, 'Content-Type': viewData.contentType,
'Cache-Control': 'public, max-age=3600', 'Cache-Control': 'public, max-age=3600',

View File

@@ -1,5 +1,5 @@
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
import { OnboardingWizardClient } from './OnboardingWizardClient'; import { OnboardingWizardClient } from '@/components/onboarding/OnboardingWizardClient';
import { OnboardingPageQuery } from '@/lib/page-queries/page-queries/OnboardingPageQuery'; import { OnboardingPageQuery } from '@/lib/page-queries/page-queries/OnboardingPageQuery';
import { SearchParamBuilder } from '@/lib/routing/search-params/SearchParamBuilder'; import { SearchParamBuilder } from '@/lib/routing/search-params/SearchParamBuilder';
import { routes } from '@/lib/routing/RouteConfig'; import { routes } from '@/lib/routing/RouteConfig';

View File

@@ -1,450 +1,15 @@
'use client'; import { notFound } from 'next/navigation';
import { SponsorDashboardPageQuery } from '@/lib/page-queries/SponsorDashboardPageQuery';
import { SponsorDashboardTemplate } from '@/templates/SponsorDashboardTemplate';
export const dynamic = 'force-dynamic'; export default async function SponsorDashboardPage() {
const pageQuery = new SponsorDashboardPageQuery();
const result = await pageQuery.execute('demo-sponsor-1');
import { motion, useReducedMotion, AnimatePresence } from 'framer-motion'; if (result.isErr()) {
import Card from '@/components/ui/Card'; notFound();
import Button from '@/components/ui/Button';
import StatusBadge from '@/components/ui/StatusBadge';
import InfoBanner from '@/components/ui/InfoBanner';
import MetricCard from '@/components/sponsors/MetricCard';
import SponsorshipCategoryCard from '@/components/sponsors/SponsorshipCategoryCard';
import ActivityItem from '@/components/sponsors/ActivityItem';
import RenewalAlert from '@/components/sponsors/RenewalAlert';
import {
BarChart3,
Eye,
Users,
Trophy,
TrendingUp,
Calendar,
DollarSign,
Target,
ArrowUpRight,
ArrowDownRight,
ExternalLink,
Loader2,
Car,
Flag,
Megaphone,
ChevronRight,
Plus,
Bell,
Settings,
CreditCard,
FileText,
RefreshCw
} from 'lucide-react';
import Link from 'next/link';
import { useSponsorDashboard } from '@/lib/hooks/sponsor/useSponsorDashboard';
export default function SponsorDashboardPage() {
const shouldReduceMotion = useReducedMotion();
// Use the hook instead of manual query construction
const { data: dashboardData, isLoading, error, retry } = useSponsorDashboard('demo-sponsor-1');
if (isLoading) {
return (
<div className="max-w-7xl mx-auto py-8 px-4 flex items-center justify-center min-h-[600px]">
<div className="text-center">
<Loader2 className="w-8 h-8 animate-spin text-primary-blue mx-auto mb-4" />
<p className="text-gray-400">Loading dashboard...</p>
</div>
</div>
);
} }
if (error || !dashboardData) { const viewData = result.unwrap();
return ( return <SponsorDashboardTemplate viewData={viewData} />;
<div className="max-w-7xl mx-auto py-8 px-4 flex items-center justify-center min-h-[600px]">
<div className="text-center">
<p className="text-gray-400">{error?.getUserMessage() || 'Failed to load dashboard data'}</p>
{error && (
<Button variant="secondary" onClick={retry} className="mt-4">
Retry
</Button>
)}
</div>
</div>
);
}
const categoryData = dashboardData.categoryData;
return (
<div className="max-w-7xl mx-auto py-8 px-4">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-8">
<div>
<h2 className="text-2xl font-bold text-white">Sponsor Dashboard</h2>
<p className="text-gray-400">Welcome back, {dashboardData.sponsorName}</p>
</div>
<div className="flex items-center gap-3">
{/* Time Range Selector */}
<div className="flex items-center bg-iron-gray/50 rounded-lg p-1">
{(['7d', '30d', '90d', 'all'] as const).map((range) => (
<button
key={range}
onClick={() => {}}
className={`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
false
? 'bg-primary-blue text-white'
: 'text-gray-400 hover:text-white'
}`}
>
{range === 'all' ? 'All' : range}
</button>
))}
</div>
{/* Quick Actions */}
<Button variant="secondary" className="hidden sm:flex">
<RefreshCw className="w-4 h-4" />
</Button>
<Link href="/sponsor/settings">
<Button variant="secondary" className="hidden sm:flex">
<Settings className="w-4 h-4" />
</Button>
</Link>
</div>
</div>
{/* Key Metrics */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
<MetricCard
title="Total Impressions"
value={dashboardData.totalImpressions}
change={dashboardData.metrics.impressionsChange}
icon={Eye}
delay={0}
/>
<MetricCard
title="Unique Viewers"
value={dashboardData.metrics.uniqueViewers}
change={dashboardData.metrics.viewersChange}
icon={Users}
delay={0.1}
/>
<MetricCard
title="Engagement Rate"
value={dashboardData.metrics.exposure}
change={dashboardData.metrics.exposureChange}
icon={TrendingUp}
suffix="%"
delay={0.2}
/>
<MetricCard
title="Total Investment"
value={dashboardData.totalInvestment}
icon={DollarSign}
prefix="$"
delay={0.3}
/>
</div>
{/* Sponsorship Categories */}
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-white">Your Sponsorships</h3>
<Link href="/sponsor/campaigns">
<Button variant="secondary" className="text-sm">
View All
<ChevronRight className="w-4 h-4 ml-1" />
</Button>
</Link>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
<SponsorshipCategoryCard
icon={Trophy}
title="Leagues"
count={categoryData.leagues.count}
impressions={categoryData.leagues.impressions}
color="text-primary-blue"
href="/sponsor/campaigns?type=leagues"
/>
<SponsorshipCategoryCard
icon={Users}
title="Teams"
count={categoryData.teams.count}
impressions={categoryData.teams.impressions}
color="text-purple-400"
href="/sponsor/campaigns?type=teams"
/>
<SponsorshipCategoryCard
icon={Car}
title="Drivers"
count={categoryData.drivers.count}
impressions={categoryData.drivers.impressions}
color="text-performance-green"
href="/sponsor/campaigns?type=drivers"
/>
<SponsorshipCategoryCard
icon={Flag}
title="Races"
count={categoryData.races.count}
impressions={categoryData.races.impressions}
color="text-warning-amber"
href="/sponsor/campaigns?type=races"
/>
<SponsorshipCategoryCard
icon={Megaphone}
title="Platform Ads"
count={categoryData.platform.count}
impressions={categoryData.platform.impressions}
color="text-racing-red"
href="/sponsor/campaigns?type=platform"
/>
</div>
</div>
{/* Main Content Grid */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Left Column - Sponsored Entities */}
<div className="lg:col-span-2 space-y-6">
{/* Top Performing Sponsorships */}
<Card>
<div className="flex items-center justify-between p-4 border-b border-charcoal-outline">
<h3 className="text-lg font-semibold text-white">Top Performing</h3>
<Link href="/leagues">
<Button variant="secondary" className="text-sm">
<Plus className="w-4 h-4 mr-1" />
Find More
</Button>
</Link>
</div>
<div className="divide-y divide-charcoal-outline/50">
{/* Leagues */}
{dashboardData.sponsorships.leagues.map((league: any) => (
<div key={league.id} className="flex items-center justify-between p-4 hover:bg-iron-gray/30 transition-colors">
<div className="flex items-center gap-4">
<div className={`px-2 py-1 rounded text-xs font-medium ${
league.tier === 'main'
? 'bg-primary-blue/20 text-primary-blue border border-primary-blue/30'
: 'bg-purple-500/20 text-purple-400 border border-purple-500/30'
}`}>
{league.tier === 'main' ? 'Main' : 'Secondary'}
</div>
<div>
<div className="flex items-center gap-2">
<Trophy className="w-4 h-4 text-gray-500" />
<span className="font-medium text-white">{league.entityName}</span>
</div>
<div className="text-sm text-gray-500">{league.details}</div>
</div>
</div>
<div className="flex items-center gap-4">
<div className="text-right">
<div className="font-semibold text-white">{league.formattedImpressions}</div>
<div className="text-xs text-gray-500">impressions</div>
</div>
<Link href={`/sponsor/leagues/${league.entityId}`}>
<Button variant="secondary" className="text-xs">
<ExternalLink className="w-3 h-3" />
</Button>
</Link>
</div>
</div>
))}
{/* Teams */}
{dashboardData.sponsorships.teams.map((team: any) => (
<div key={team.id} className="flex items-center justify-between p-4 hover:bg-iron-gray/30 transition-colors">
<div className="flex items-center gap-4">
<div className="px-2 py-1 rounded text-xs font-medium bg-purple-500/20 text-purple-400 border border-purple-500/30">
Team
</div>
<div>
<div className="flex items-center gap-2">
<Users className="w-4 h-4 text-gray-500" />
<span className="font-medium text-white">{team.entityName}</span>
</div>
<div className="text-sm text-gray-500">{team.details}</div>
</div>
</div>
<div className="flex items-center gap-4">
<div className="text-right">
<div className="font-semibold text-white">{team.formattedImpressions}</div>
<div className="text-xs text-gray-500">impressions</div>
</div>
<Button variant="secondary" className="text-xs">
<ExternalLink className="w-3 h-3" />
</Button>
</div>
</div>
))}
{/* Drivers */}
{dashboardData.sponsorships.drivers.slice(0, 2).map((driver: any) => (
<div key={driver.id} className="flex items-center justify-between p-4 hover:bg-iron-gray/30 transition-colors">
<div className="flex items-center gap-4">
<div className="px-2 py-1 rounded text-xs font-medium bg-performance-green/20 text-performance-green border border-performance-green/30">
Driver
</div>
<div>
<div className="flex items-center gap-2">
<Car className="w-4 h-4 text-gray-500" />
<span className="font-medium text-white">{driver.entityName}</span>
</div>
<div className="text-sm text-gray-500">{driver.details}</div>
</div>
</div>
<div className="flex items-center gap-4">
<div className="text-right">
<div className="font-semibold text-white">{driver.formattedImpressions}</div>
<div className="text-xs text-gray-500">impressions</div>
</div>
<Button variant="secondary" className="text-xs">
<ExternalLink className="w-3 h-3" />
</Button>
</div>
</div>
))}
</div>
</Card>
{/* Upcoming Events */}
<Card>
<div className="p-4 border-b border-charcoal-outline">
<h3 className="text-lg font-semibold text-white flex items-center gap-2">
<Calendar className="w-5 h-5 text-warning-amber" />
Upcoming Sponsored Events
</h3>
</div>
<div className="p-4">
{dashboardData.sponsorships.races.length > 0 ? (
<div className="space-y-3">
{dashboardData.sponsorships.races.map((race: any) => (
<div key={race.id} className="flex items-center justify-between p-3 rounded-lg bg-iron-gray/30">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-lg bg-warning-amber/10 flex items-center justify-center">
<Flag className="w-5 h-5 text-warning-amber" />
</div>
<div>
<p className="font-medium text-white">{race.entityName}</p>
<p className="text-sm text-gray-500">{race.details}</p>
</div>
</div>
<div className="text-right">
<span className="px-2 py-1 rounded text-xs font-medium bg-warning-amber/20 text-warning-amber">
{race.status}
</span>
</div>
</div>
))}
</div>
) : (
<div className="text-center py-8 text-gray-500">
<Calendar className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p>No upcoming sponsored events</p>
</div>
)}
</div>
</Card>
</div>
{/* Right Column - Activity & Quick Actions */}
<div className="space-y-6">
{/* Quick Actions */}
<Card className="p-4">
<h3 className="text-lg font-semibold text-white mb-4">Quick Actions</h3>
<div className="space-y-2">
<Link href="/leagues" className="block">
<Button variant="secondary" className="w-full justify-start">
<Target className="w-4 h-4 mr-2" />
Find Leagues to Sponsor
</Button>
</Link>
<Link href="/teams" className="block">
<Button variant="secondary" className="w-full justify-start">
<Users className="w-4 h-4 mr-2" />
Browse Teams
</Button>
</Link>
<Link href="/drivers" className="block">
<Button variant="secondary" className="w-full justify-start">
<Car className="w-4 h-4 mr-2" />
Discover Drivers
</Button>
</Link>
<Link href="/sponsor/billing" className="block">
<Button variant="secondary" className="w-full justify-start">
<CreditCard className="w-4 h-4 mr-2" />
Manage Billing
</Button>
</Link>
<Link href="/sponsor/campaigns" className="block">
<Button variant="secondary" className="w-full justify-start">
<BarChart3 className="w-4 h-4 mr-2" />
View Analytics
</Button>
</Link>
</div>
</Card>
{/* Renewal Alerts */}
{dashboardData.upcomingRenewals.length > 0 && (
<Card className="p-4">
<h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<Bell className="w-5 h-5 text-warning-amber" />
Upcoming Renewals
</h3>
<div className="space-y-3">
{dashboardData.upcomingRenewals.map((renewal: any) => (
<RenewalAlert key={renewal.id} renewal={renewal} />
))}
</div>
</Card>
)}
{/* Recent Activity */}
<Card className="p-4">
<h3 className="text-lg font-semibold text-white mb-4">Recent Activity</h3>
<div>
{dashboardData.recentActivity.map((activity: any) => (
<ActivityItem key={activity.id} activity={activity} />
))}
</div>
</Card>
{/* Investment Summary */}
<Card className="p-4">
<h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<FileText className="w-5 h-5 text-primary-blue" />
Investment Summary
</h3>
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="text-gray-400">Active Sponsorships</span>
<span className="font-medium text-white">{dashboardData.activeSponsorships}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-400">Total Investment</span>
<span className="font-medium text-white">{dashboardData.formattedTotalInvestment}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-400">Cost per 1K Views</span>
<span className="font-medium text-performance-green">
{dashboardData.costPerThousandViews}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-400">Next Invoice</span>
<span className="font-medium text-white">Jan 1, 2026</span>
</div>
<div className="pt-3 border-t border-charcoal-outline">
<Link href="/sponsor/billing">
<Button variant="secondary" className="w-full text-sm">
<CreditCard className="w-4 h-4 mr-2" />
View Billing Details
</Button>
</Link>
</div>
</div>
</Card>
</div>
</div>
</div>
);
} }

View File

@@ -0,0 +1,32 @@
'use client';
import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { AdminDashboardTemplate } from '@/templates/AdminDashboardTemplate';
import { AdminDashboardViewData } from '@/lib/view-data/AdminDashboardViewData';
interface AdminDashboardWrapperProps {
initialViewData: AdminDashboardViewData;
}
export function AdminDashboardWrapper({ initialViewData }: AdminDashboardWrapperProps) {
const router = useRouter();
// UI state (not business logic)
const [loading, setLoading] = useState(false);
const handleRefresh = useCallback(() => {
setLoading(true);
router.refresh();
// Reset loading after a short delay to show the spinner
setTimeout(() => setLoading(false), 1000);
}, [router]);
return (
<AdminDashboardTemplate
adminDashboardViewData={initialViewData}
onRefresh={handleRefresh}
isLoading={loading}
/>
);
}

View File

@@ -4,7 +4,7 @@ import { useState, useCallback } from 'react';
import { useRouter, useSearchParams } from 'next/navigation'; import { useRouter, useSearchParams } from 'next/navigation';
import { AdminUsersTemplate } from '@/templates/AdminUsersTemplate'; import { AdminUsersTemplate } from '@/templates/AdminUsersTemplate';
import { AdminUsersViewData } from '@/lib/view-data/AdminUsersViewData'; import { AdminUsersViewData } from '@/lib/view-data/AdminUsersViewData';
import { updateUserStatus, deleteUser } from '../actions'; import { updateUserStatus, deleteUser } from '@/app/admin/actions';
import { routes } from '@/lib/routing/RouteConfig'; import { routes } from '@/lib/routing/RouteConfig';
interface AdminUsersWrapperProps { interface AdminUsersWrapperProps {
@@ -14,12 +14,12 @@ interface AdminUsersWrapperProps {
export function AdminUsersWrapper({ initialViewData }: AdminUsersWrapperProps) { export function AdminUsersWrapper({ initialViewData }: AdminUsersWrapperProps) {
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
// UI state (not business logic) // UI state (not business logic)
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [deletingUser, setDeletingUser] = useState<string | null>(null); const [deletingUser, setDeletingUser] = useState<string | null>(null);
// Current filter values from URL // Current filter values from URL
const search = searchParams.get('search') || ''; const search = searchParams.get('search') || '';
const roleFilter = searchParams.get('role') || ''; const roleFilter = searchParams.get('role') || '';
@@ -63,12 +63,12 @@ export function AdminUsersWrapper({ initialViewData }: AdminUsersWrapperProps) {
try { try {
setLoading(true); setLoading(true);
const result = await updateUserStatus(userId, newStatus); const result = await updateUserStatus(userId, newStatus);
if (result.isErr()) { if (result.isErr()) {
setError(result.getError()); setError(result.getError());
return; return;
} }
// Revalidate data // Revalidate data
router.refresh(); router.refresh();
} catch (err) { } catch (err) {
@@ -86,12 +86,12 @@ export function AdminUsersWrapper({ initialViewData }: AdminUsersWrapperProps) {
try { try {
setDeletingUser(userId); setDeletingUser(userId);
const result = await deleteUser(userId); const result = await deleteUser(userId);
if (result.isErr()) { if (result.isErr()) {
setError(result.getError()); setError(result.getError());
return; return;
} }
// Revalidate data // Revalidate data
router.refresh(); router.refresh();
} catch (err) { } catch (err) {

View File

@@ -2,6 +2,9 @@ import React from 'react';
import { Trophy, Crown, Flag, ChevronRight } from 'lucide-react'; import { Trophy, Crown, Flag, ChevronRight } from 'lucide-react';
import Button from '@/components/ui/Button'; import Button from '@/components/ui/Button';
import Image from 'next/image'; import Image from 'next/image';
import { SkillLevelDisplay } from '@/lib/display-objects/SkillLevelDisplay';
import { MedalDisplay } from '@/lib/display-objects/MedalDisplay';
import { RatingDisplay } from '@/lib/display-objects/RatingDisplay';
interface DriverLeaderboardPreviewProps { interface DriverLeaderboardPreviewProps {
drivers: { drivers: {
@@ -19,33 +22,8 @@ interface DriverLeaderboardPreviewProps {
onNavigateToDrivers: () => void; onNavigateToDrivers: () => void;
} }
const SKILL_LEVELS = [
{ id: 'pro', label: 'Pro', color: 'text-yellow-400' },
{ id: 'advanced', label: 'Advanced', color: 'text-purple-400' },
{ id: 'intermediate', label: 'Intermediate', color: 'text-primary-blue' },
{ id: 'beginner', label: 'Beginner', color: 'text-green-400' },
];
export function DriverLeaderboardPreview({ drivers, onDriverClick, onNavigateToDrivers }: DriverLeaderboardPreviewProps) { export function DriverLeaderboardPreview({ drivers, onDriverClick, onNavigateToDrivers }: DriverLeaderboardPreviewProps) {
const top10 = drivers.slice(0, 10); const top10 = drivers; // Already sliced in builder
const getMedalColor = (position: number) => {
switch (position) {
case 1: return 'text-yellow-400';
case 2: return 'text-gray-300';
case 3: return 'text-amber-600';
default: return 'text-gray-500';
}
};
const getMedalBg = (position: number) => {
switch (position) {
case 1: return 'bg-yellow-400/10 border-yellow-400/30';
case 2: return 'bg-gray-300/10 border-gray-300/30';
case 3: return 'bg-amber-600/10 border-amber-600/30';
default: return 'bg-iron-gray/50 border-charcoal-outline';
}
};
return ( return (
<div className="rounded-xl bg-iron-gray/30 border border-charcoal-outline overflow-hidden"> <div className="rounded-xl bg-iron-gray/30 border border-charcoal-outline overflow-hidden">
@@ -71,7 +49,6 @@ export function DriverLeaderboardPreview({ drivers, onDriverClick, onNavigateToD
<div className="divide-y divide-charcoal-outline/50"> <div className="divide-y divide-charcoal-outline/50">
{top10.map((driver, index) => { {top10.map((driver, index) => {
const levelConfig = SKILL_LEVELS.find((l) => l.id === driver.skillLevel);
const position = index + 1; const position = index + 1;
return ( return (
@@ -81,7 +58,7 @@ export function DriverLeaderboardPreview({ drivers, onDriverClick, onNavigateToD
onClick={() => onDriverClick(driver.id)} onClick={() => onDriverClick(driver.id)}
className="flex items-center gap-4 px-5 py-3 w-full text-left hover:bg-iron-gray/30 transition-colors group" className="flex items-center gap-4 px-5 py-3 w-full text-left hover:bg-iron-gray/30 transition-colors group"
> >
<div className={`flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold border ${getMedalBg(position)} ${getMedalColor(position)}`}> <div className={`flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold border ${MedalDisplay.getBg(position)} ${MedalDisplay.getColor(position)}`}>
{position <= 3 ? <Crown className="w-3.5 h-3.5" /> : position} {position <= 3 ? <Crown className="w-3.5 h-3.5" /> : position}
</div> </div>
@@ -96,13 +73,13 @@ export function DriverLeaderboardPreview({ drivers, onDriverClick, onNavigateToD
<div className="flex items-center gap-2 text-xs text-gray-500"> <div className="flex items-center gap-2 text-xs text-gray-500">
<Flag className="w-3 h-3" /> <Flag className="w-3 h-3" />
{driver.nationality} {driver.nationality}
<span className={levelConfig?.color}>{levelConfig?.label}</span> <span className={SkillLevelDisplay.getColor(driver.skillLevel)}>{SkillLevelDisplay.getLabel(driver.skillLevel)}</span>
</div> </div>
</div> </div>
<div className="flex items-center gap-4 text-sm"> <div className="flex items-center gap-4 text-sm">
<div className="text-center"> <div className="text-center">
<p className="text-primary-blue font-mono font-semibold">{driver.rating.toLocaleString()}</p> <p className="text-primary-blue font-mono font-semibold">{RatingDisplay.format(driver.rating)}</p>
<p className="text-[10px] text-gray-500">Rating</p> <p className="text-[10px] text-gray-500">Rating</p>
</div> </div>
<div className="text-center"> <div className="text-center">

View File

@@ -3,6 +3,8 @@ import Image from 'next/image';
import { Users, Crown, Shield, ChevronRight } from 'lucide-react'; import { Users, Crown, Shield, ChevronRight } from 'lucide-react';
import Button from '@/components/ui/Button'; import Button from '@/components/ui/Button';
import { getMediaUrl } from '@/lib/utilities/media'; import { getMediaUrl } from '@/lib/utilities/media';
import { SkillLevelDisplay } from '@/lib/display-objects/SkillLevelDisplay';
import { MedalDisplay } from '@/lib/display-objects/MedalDisplay';
interface TeamLeaderboardPreviewProps { interface TeamLeaderboardPreviewProps {
teams: { teams: {
@@ -19,33 +21,8 @@ interface TeamLeaderboardPreviewProps {
onNavigateToTeams: () => void; onNavigateToTeams: () => void;
} }
const SKILL_LEVELS = [
{ id: 'pro', label: 'Pro', icon: Crown, color: 'text-yellow-400', bgColor: 'bg-yellow-400/10', borderColor: 'border-yellow-400/30' },
{ id: 'advanced', label: 'Advanced', icon: Crown, color: 'text-purple-400', bgColor: 'bg-purple-400/10', borderColor: 'border-purple-400/30' },
{ id: 'intermediate', label: 'Intermediate', icon: Crown, color: 'text-primary-blue', bgColor: 'bg-primary-blue/10', borderColor: 'border-primary-blue/30' },
{ id: 'beginner', label: 'Beginner', icon: Shield, color: 'text-green-400', bgColor: 'bg-green-400/10', borderColor: 'border-green-400/30' },
];
export function TeamLeaderboardPreview({ teams, onTeamClick, onNavigateToTeams }: TeamLeaderboardPreviewProps) { export function TeamLeaderboardPreview({ teams, onTeamClick, onNavigateToTeams }: TeamLeaderboardPreviewProps) {
const top5 = teams.slice(0, 5); const top5 = teams; // Already sliced in builder when implemented
const getMedalColor = (position: number) => {
switch (position) {
case 1: return 'text-yellow-400';
case 2: return 'text-gray-300';
case 3: return 'text-amber-600';
default: return 'text-gray-500';
}
};
const getMedalBg = (position: number) => {
switch (position) {
case 1: return 'bg-yellow-400/10 border-yellow-400/30';
case 2: return 'bg-gray-300/10 border-gray-300/30';
case 3: return 'bg-amber-600/10 border-amber-600/30';
default: return 'bg-iron-gray/50 border-charcoal-outline';
}
};
return ( return (
<div className="rounded-xl bg-iron-gray/30 border border-charcoal-outline overflow-hidden"> <div className="rounded-xl bg-iron-gray/30 border border-charcoal-outline overflow-hidden">
@@ -71,8 +48,6 @@ export function TeamLeaderboardPreview({ teams, onTeamClick, onNavigateToTeams }
<div className="divide-y divide-charcoal-outline/50"> <div className="divide-y divide-charcoal-outline/50">
{top5.map((team, index) => { {top5.map((team, index) => {
const levelConfig = SKILL_LEVELS.find((l) => l.id === team.category);
const LevelIcon = levelConfig?.icon || Shield;
const position = team.position; const position = team.position;
return ( return (
@@ -82,7 +57,7 @@ export function TeamLeaderboardPreview({ teams, onTeamClick, onNavigateToTeams }
onClick={() => onTeamClick(team.id)} onClick={() => onTeamClick(team.id)}
className="flex items-center gap-4 px-5 py-3 w-full text-left hover:bg-iron-gray/30 transition-colors group" className="flex items-center gap-4 px-5 py-3 w-full text-left hover:bg-iron-gray/30 transition-colors group"
> >
<div className={`flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold border ${getMedalBg(position)} ${getMedalColor(position)}`}> <div className={`flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold border ${MedalDisplay.getBg(position)} ${MedalDisplay.getColor(position)}`}>
{position <= 3 ? <Crown className="w-3.5 h-3.5" /> : position} {position <= 3 ? <Crown className="w-3.5 h-3.5" /> : position}
</div> </div>
@@ -111,7 +86,7 @@ export function TeamLeaderboardPreview({ teams, onTeamClick, onNavigateToTeams }
<Users className="w-3 h-3" /> <Users className="w-3 h-3" />
{team.memberCount} members {team.memberCount} members
</span> </span>
<span className={levelConfig?.color}>{levelConfig?.label}</span> <span className={SkillLevelDisplay.getColor(team.category || '')}>{SkillLevelDisplay.getLabel(team.category || '')}</span>
</div> </div>
</div> </div>

View File

@@ -66,7 +66,7 @@ interface LeagueSliderProps {
} }
interface LeaguesTemplateProps { interface LeaguesTemplateProps {
data: LeaguesViewData; viewData: LeaguesViewData;
} }
// ============================================================================ // ============================================================================
@@ -406,15 +406,15 @@ function LeagueSlider({
// MAIN TEMPLATE COMPONENT // MAIN TEMPLATE COMPONENT
// ============================================================================ // ============================================================================
export function LeaguesTemplate({ export function LeaguesClient({
data, viewData,
}: LeaguesTemplateProps) { }: LeaguesTemplateProps) {
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
const [activeCategory, setActiveCategory] = useState<CategoryId>('all'); const [activeCategory, setActiveCategory] = useState<CategoryId>('all');
const [showFilters, setShowFilters] = useState(false); const [showFilters, setShowFilters] = useState(false);
// Filter by search query // Filter by search query
const searchFilteredLeagues = data.leagues.filter((league) => { const searchFilteredLeagues = viewData.leagues.filter((league) => {
if (!searchQuery) return true; if (!searchQuery) return true;
const query = searchQuery.toLowerCase(); const query = searchQuery.toLowerCase();
return ( return (
@@ -485,7 +485,7 @@ export function LeaguesTemplate({
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-performance-green animate-pulse" /> <div className="w-2 h-2 rounded-full bg-performance-green animate-pulse" />
<span className="text-sm text-gray-400"> <span className="text-sm text-gray-400">
<span className="text-white font-semibold">{data.leagues.length}</span> active leagues <span className="text-white font-semibold">{viewData.leagues.length}</span> active leagues
</span> </span>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@@ -505,7 +505,7 @@ export function LeaguesTemplate({
{/* CTA */} {/* CTA */}
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<a href="/leagues/create" className="flex items-center gap-2 px-6 py-3 bg-primary-blue text-white rounded-lg hover:bg-blue-600 transition-colors"> <a href=routes.league.detail('create') className="flex items-center gap-2 px-6 py-3 bg-primary-blue text-white rounded-lg hover:bg-blue-600 transition-colors">
<Plus className="w-5 h-5" /> <Plus className="w-5 h-5" />
<span>Create League</span> <span>Create League</span>
</a> </a>
@@ -575,7 +575,7 @@ export function LeaguesTemplate({
</div> </div>
{/* Content */} {/* Content */}
{data.leagues.length === 0 ? ( {viewData.leagues.length === 0 ? (
/* Empty State */ /* Empty State */
<Card className="text-center py-16"> <Card className="text-center py-16">
<div className="max-w-md mx-auto"> <div className="max-w-md mx-auto">
@@ -588,7 +588,7 @@ export function LeaguesTemplate({
<p className="text-gray-400 mb-8"> <p className="text-gray-400 mb-8">
Be the first to create a racing series. Start your own league and invite drivers to compete for glory. Be the first to create a racing series. Start your own league and invite drivers to compete for glory.
</p> </p>
<a href="/leagues/create" className="inline-flex items-center gap-2 px-6 py-3 bg-primary-blue text-white rounded-lg hover:bg-blue-600 transition-colors"> <a href=routes.league.detail('create') className="inline-flex items-center gap-2 px-6 py-3 bg-primary-blue text-white rounded-lg hover:bg-blue-600 transition-colors">
<Sparkles className="w-4 h-4" /> <Sparkles className="w-4 h-4" />
Create Your First League Create Your First League
</a> </a>

View File

@@ -1,3 +1,5 @@
'use client';
import { useState, FormEvent } from 'react'; import { useState, FormEvent } from 'react';
import Card from '@/components/ui/Card'; import Card from '@/components/ui/Card';
import { StepIndicator } from '@/ui/StepIndicator'; import { StepIndicator } from '@/ui/StepIndicator';

View File

@@ -1,14 +1,12 @@
'use client'; 'use client';
import { useRouter } from 'next/navigation'; import { OnboardingWizard } from './OnboardingWizard';
import { OnboardingWizard } from '@/components/onboarding/OnboardingWizard';
import { routes } from '@/lib/routing/RouteConfig'; import { routes } from '@/lib/routing/RouteConfig';
import { completeOnboardingAction } from './completeOnboardingAction'; import { completeOnboardingAction } from '@/app/onboarding/completeOnboardingAction';
import { generateAvatarsAction } from './generateAvatarsAction'; import { generateAvatarsAction } from '@/app/onboarding/generateAvatarsAction';
import { useAuth } from '@/lib/auth/AuthContext'; import { useAuth } from '@/lib/auth/AuthContext';
export function OnboardingWizardClient() { export function OnboardingWizardClient() {
const router = useRouter();
const { session } = useAuth(); const { session } = useAuth();
const handleCompleteOnboarding = async (input: { const handleCompleteOnboarding = async (input: {
@@ -20,13 +18,12 @@ export function OnboardingWizardClient() {
}) => { }) => {
try { try {
const result = await completeOnboardingAction(input); const result = await completeOnboardingAction(input);
if (result.isErr()) { if (result.isErr()) {
return { success: false, error: result.getError() }; return { success: false, error: result.getError() };
} }
router.push(routes.protected.dashboard); window.location.href = routes.protected.dashboard;
router.refresh();
return { success: true }; return { success: true };
} catch (error) { } catch (error) {
return { success: false, error: 'Failed to complete onboarding' }; return { success: false, error: 'Failed to complete onboarding' };
@@ -62,8 +59,7 @@ export function OnboardingWizardClient() {
return ( return (
<OnboardingWizard <OnboardingWizard
onCompleted={() => { onCompleted={() => {
router.push(routes.protected.dashboard); window.location.href = routes.protected.dashboard;
router.refresh();
}} }}
onCompleteOnboarding={handleCompleteOnboarding} onCompleteOnboarding={handleCompleteOnboarding}
onGenerateAvatars={handleGenerateAvatars} onGenerateAvatars={handleGenerateAvatars}

View File

@@ -225,13 +225,13 @@ export default function UserPill() {
return ( return (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Link <Link
href="/auth/login" href=routes.auth.login
className="inline-flex items-center gap-2 rounded-full bg-iron-gray border border-charcoal-outline px-4 py-1.5 text-xs font-medium text-gray-300 hover:text-white hover:border-gray-500 transition-all" className="inline-flex items-center gap-2 rounded-full bg-iron-gray border border-charcoal-outline px-4 py-1.5 text-xs font-medium text-gray-300 hover:text-white hover:border-gray-500 transition-all"
> >
Sign In Sign In
</Link> </Link>
<Link <Link
href="/auth/signup" href=routes.auth.signup
className="inline-flex items-center gap-2 rounded-full bg-primary-blue px-4 py-1.5 text-xs font-semibold text-white shadow-[0_0_12px_rgba(25,140,255,0.5)] hover:bg-primary-blue/90 hover:shadow-[0_0_18px_rgba(25,140,255,0.8)] transition-all" className="inline-flex items-center gap-2 rounded-full bg-primary-blue px-4 py-1.5 text-xs font-semibold text-white shadow-[0_0_12px_rgba(25,140,255,0.5)] hover:bg-primary-blue/90 hover:shadow-[0_0_18px_rgba(25,140,255,0.8)] transition-all"
> >
Get Started Get Started
@@ -378,7 +378,7 @@ export default function UserPill() {
<span>Dashboard</span> <span>Dashboard</span>
</Link> </Link>
<Link <Link
href="/sponsor/campaigns" href=routes.sponsor.campaigns
className="flex items-center gap-3 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors" className="flex items-center gap-3 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors"
onClick={() => setIsMenuOpen(false)} onClick={() => setIsMenuOpen(false)}
> >
@@ -386,7 +386,7 @@ export default function UserPill() {
<span>My Sponsorships</span> <span>My Sponsorships</span>
</Link> </Link>
<Link <Link
href="/sponsor/billing" href=routes.sponsor.billing
className="flex items-center gap-3 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors" className="flex items-center gap-3 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors"
onClick={() => setIsMenuOpen(false)} onClick={() => setIsMenuOpen(false)}
> >
@@ -394,7 +394,7 @@ export default function UserPill() {
<span>Billing</span> <span>Billing</span>
</Link> </Link>
<Link <Link
href="/sponsor/settings" href=routes.sponsor.settings
className="flex items-center gap-3 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors" className="flex items-center gap-3 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors"
onClick={() => setIsMenuOpen(false)} onClick={() => setIsMenuOpen(false)}
> >
@@ -406,21 +406,21 @@ export default function UserPill() {
{/* Regular user profile links */} {/* Regular user profile links */}
<Link <Link
href="/profile" href=routes.protected.profile
className="block px-4 py-2.5 hover:bg-iron-gray/50 transition-colors" className="block px-4 py-2.5 hover:bg-iron-gray/50 transition-colors"
onClick={() => setIsMenuOpen(false)} onClick={() => setIsMenuOpen(false)}
> >
Profile Profile
</Link> </Link>
<Link <Link
href="/profile/leagues" href=routes.protected.profileLeagues
className="block px-4 py-2.5 hover:bg-iron-gray/50 transition-colors" className="block px-4 py-2.5 hover:bg-iron-gray/50 transition-colors"
onClick={() => setIsMenuOpen(false)} onClick={() => setIsMenuOpen(false)}
> >
Manage leagues Manage leagues
</Link> </Link>
<Link <Link
href="/profile/liveries" href=routes.protected.profileLiveries
className="flex items-center gap-2 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors" className="flex items-center gap-2 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors"
onClick={() => setIsMenuOpen(false)} onClick={() => setIsMenuOpen(false)}
> >
@@ -428,7 +428,7 @@ export default function UserPill() {
<span>Liveries</span> <span>Liveries</span>
</Link> </Link>
<Link <Link
href="/profile/sponsorship-requests" href=routes.protected.profileSponsorshipRequests
className="flex items-center gap-2 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors" className="flex items-center gap-2 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors"
onClick={() => setIsMenuOpen(false)} onClick={() => setIsMenuOpen(false)}
> >
@@ -436,7 +436,7 @@ export default function UserPill() {
<span>Sponsorship Requests</span> <span>Sponsorship Requests</span>
</Link> </Link>
<Link <Link
href="/profile/settings" href=routes.protected.profileSettings
className="flex items-center gap-2 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors" className="flex items-center gap-2 px-4 py-2.5 hover:bg-iron-gray/50 transition-colors"
onClick={() => setIsMenuOpen(false)} onClick={() => setIsMenuOpen(false)}
> >

View File

@@ -1,66 +1,5 @@
import { BaseApiClient } from '../base/BaseApiClient'; import { BaseApiClient } from '../base/BaseApiClient';
import type { UserDto, UserListResponse, ListUsersQuery, DashboardStats } from '@/lib/types/admin';
export interface UserDto {
id: string;
email: string;
displayName: string;
roles: string[];
status: string;
isSystemAdmin: boolean;
createdAt: Date;
updatedAt: Date;
lastLoginAt?: Date;
primaryDriverId?: string;
}
export interface UserListResponse {
users: UserDto[];
total: number;
page: number;
limit: number;
totalPages: number;
}
export interface ListUsersQuery {
role?: string;
status?: string;
email?: string;
search?: string;
page?: number;
limit?: number;
sortBy?: 'email' | 'displayName' | 'createdAt' | 'lastLoginAt' | 'status';
sortDirection?: 'asc' | 'desc';
}
export interface DashboardStats {
totalUsers: number;
activeUsers: number;
suspendedUsers: number;
deletedUsers: number;
systemAdmins: number;
recentLogins: number;
newUsersToday: number;
userGrowth: {
label: string;
value: number;
color: string;
}[];
roleDistribution: {
label: string;
value: number;
color: string;
}[];
statusDistribution: {
active: number;
suspended: number;
deleted: number;
};
activityTimeline: {
date: string;
newUsers: number;
logins: number;
}[];
}
/** /**
* Admin API Client * Admin API Client

View File

@@ -12,6 +12,8 @@ import type { RaceDetailEntryDTO } from '../../types/generated/RaceDetailEntryDT
import type { RaceDetailRegistrationDTO } from '../../types/generated/RaceDetailRegistrationDTO'; import type { RaceDetailRegistrationDTO } from '../../types/generated/RaceDetailRegistrationDTO';
import type { RaceDetailUserResultDTO } from '../../types/generated/RaceDetailUserResultDTO'; import type { RaceDetailUserResultDTO } from '../../types/generated/RaceDetailUserResultDTO';
import type { FileProtestCommandDTO } from '../../types/generated/FileProtestCommandDTO'; import type { FileProtestCommandDTO } from '../../types/generated/FileProtestCommandDTO';
import type { AllRacesPageDTO } from '../../types/generated/AllRacesPageDTO';
import type { FilteredRacesPageDataDTO } from '../../types/tbd/FilteredRacesPageDataDTO';
// Define missing types // Define missing types
type RacesPageDataDTO = { races: RacesPageDataRaceDTO[] }; type RacesPageDataDTO = { races: RacesPageDataRaceDTO[] };

View File

@@ -1,4 +1,4 @@
import type { DashboardStats } from '@/lib/api/admin/AdminApiClient'; import type { DashboardStats } from '@/lib/types/admin';
import type { AdminDashboardViewData } from '@/lib/view-data/AdminDashboardViewData'; import type { AdminDashboardViewData } from '@/lib/view-data/AdminDashboardViewData';
/** /**

View File

@@ -1,4 +1,4 @@
import type { UserListResponse } from '@/lib/api/admin/AdminApiClient'; import type { UserListResponse } from '@/lib/types/admin';
import { AdminUsersViewData } from '@/lib/view-data/AdminUsersViewData'; import { AdminUsersViewData } from '@/lib/view-data/AdminUsersViewData';
/** /**

View File

@@ -11,7 +11,7 @@ import { AvatarViewData } from '@/lib/view-data/AvatarViewData';
export class AvatarViewDataBuilder { export class AvatarViewDataBuilder {
static build(apiDto: MediaBinaryDTO): AvatarViewData { static build(apiDto: MediaBinaryDTO): AvatarViewData {
return { return {
buffer: apiDto.buffer, buffer: Buffer.from(apiDto.buffer).toString('base64'),
contentType: apiDto.contentType, contentType: apiDto.contentType,
}; };
} }

View File

@@ -11,7 +11,7 @@ import { CategoryIconViewData } from '@/lib/view-data/CategoryIconViewData';
export class CategoryIconViewDataBuilder { export class CategoryIconViewDataBuilder {
static build(apiDto: MediaBinaryDTO): CategoryIconViewData { static build(apiDto: MediaBinaryDTO): CategoryIconViewData {
return { return {
buffer: apiDto.buffer, buffer: Buffer.from(apiDto.buffer).toString('base64'),
contentType: apiDto.contentType, contentType: apiDto.contentType,
}; };
} }

View File

@@ -1,5 +1,7 @@
import type { DriverLeaderboardItemDTO } from '@/lib/types/generated/DriverLeaderboardItemDTO'; import type { DriverLeaderboardItemDTO } from '@/lib/types/generated/DriverLeaderboardItemDTO';
import type { DriverRankingsViewData } from '@/lib/view-data/DriverRankingsViewData'; import type { DriverRankingsViewData } from '@/lib/view-data/DriverRankingsViewData';
import { WinRateDisplay } from '@/lib/display-objects/WinRateDisplay';
import { MedalDisplay } from '@/lib/display-objects/MedalDisplay';
export class DriverRankingsViewDataBuilder { export class DriverRankingsViewDataBuilder {
static build(apiDto: DriverLeaderboardItemDTO[]): DriverRankingsViewData { static build(apiDto: DriverLeaderboardItemDTO[]): DriverRankingsViewData {
@@ -26,15 +28,9 @@ export class DriverRankingsViewDataBuilder {
podiums: driver.podiums, podiums: driver.podiums,
rank: driver.rank, rank: driver.rank,
avatarUrl: driver.avatarUrl || '', avatarUrl: driver.avatarUrl || '',
winRate: driver.racesCompleted > 0 ? ((driver.wins / driver.racesCompleted) * 100).toFixed(1) : '0.0', winRate: WinRateDisplay.calculate(driver.racesCompleted, driver.wins),
medalBg: driver.rank === 1 ? 'bg-gradient-to-br from-yellow-400/20 to-yellow-600/10 border-yellow-400/40' : medalBg: MedalDisplay.getBg(driver.rank),
driver.rank === 2 ? 'bg-gradient-to-br from-gray-300/20 to-gray-400/10 border-gray-300/40' : medalColor: MedalDisplay.getColor(driver.rank),
driver.rank === 3 ? 'bg-gradient-to-br from-amber-600/20 to-amber-700/10 border-amber-600/40' :
'bg-iron-gray/50 border-charcoal-outline',
medalColor: driver.rank === 1 ? 'text-yellow-400' :
driver.rank === 2 ? 'text-gray-300' :
driver.rank === 3 ? 'text-amber-600' :
'text-gray-500',
})), })),
podium: apiDto.slice(0, 3).map((driver, index) => { podium: apiDto.slice(0, 3).map((driver, index) => {
const positions = [2, 1, 3]; // Display order: 2nd, 1st, 3rd const positions = [2, 1, 3]; // Display order: 2nd, 1st, 3rd

View File

@@ -1,22 +1,26 @@
import type { DriversLeaderboardDTO } from '@/lib/types/generated/DriversLeaderboardDTO'; import type { DriversLeaderboardDTO } from '@/lib/types/generated/DriversLeaderboardDTO';
import type { DriversViewData } from './DriversViewData'; import type { DriversViewData } from '@/lib/types/view-data/DriversViewData';
/**
* DriversViewDataBuilder
*
* Transforms DriversLeaderboardDTO into ViewData for the drivers listing page.
* Deterministic, side-effect free, no HTTP calls.
*
* This builder does NOT perform filtering or sorting - that belongs in the API.
* If the API doesn't support filtering, it should be marked as NotImplemented.
*/
export class DriversViewDataBuilder { export class DriversViewDataBuilder {
static build(apiDto: DriversLeaderboardDTO): DriversViewData { static build(dto: DriversLeaderboardDTO): DriversViewData {
return { return {
drivers: apiDto.drivers, drivers: dto.drivers.map(driver => ({
totalRaces: apiDto.totalRaces, id: driver.id,
totalWins: apiDto.totalWins, name: driver.name,
activeCount: apiDto.activeCount, rating: driver.rating,
skillLevel: driver.skillLevel,
category: driver.category,
nationality: driver.nationality,
racesCompleted: driver.racesCompleted,
wins: driver.wins,
podiums: driver.podiums,
isActive: driver.isActive,
rank: driver.rank,
avatarUrl: driver.avatarUrl,
})),
totalRaces: dto.totalRaces,
totalWins: dto.totalWins,
activeCount: dto.activeCount,
}; };
} }
} }

View File

@@ -1,13 +1,12 @@
import type { DriverLeaderboardItemDTO } from '@/lib/types/generated/DriverLeaderboardItemDTO'; import type { DriverLeaderboardItemDTO } from '@/lib/types/generated/DriverLeaderboardItemDTO';
import type { TeamListItemDTO } from '@/lib/types/generated/TeamListItemDTO';
import type { LeaderboardsViewData } from '@/lib/view-data/LeaderboardsViewData'; import type { LeaderboardsViewData } from '@/lib/view-data/LeaderboardsViewData';
export class LeaderboardsViewDataBuilder { export class LeaderboardsViewDataBuilder {
static build( static build(
apiDto: { drivers: { drivers: DriverLeaderboardItemDTO[] }; teams: { teams: TeamListItemDTO[] } } apiDto: { drivers: { drivers: DriverLeaderboardItemDTO[] }; teams: { teams: [] } }
): LeaderboardsViewData { ): LeaderboardsViewData {
return { return {
drivers: apiDto.drivers.drivers.map(driver => ({ drivers: apiDto.drivers.drivers.slice(0, 10).map(driver => ({
id: driver.id, id: driver.id,
name: driver.name, name: driver.name,
rating: driver.rating, rating: driver.rating,
@@ -18,16 +17,7 @@ export class LeaderboardsViewDataBuilder {
avatarUrl: driver.avatarUrl || '', avatarUrl: driver.avatarUrl || '',
position: driver.rank, position: driver.rank,
})), })),
teams: apiDto.teams.teams.map(team => ({ teams: [], // Teams leaderboard not implemented
id: team.id,
name: team.name,
tag: team.tag,
memberCount: team.memberCount,
category: team.category,
totalWins: team.totalWins || 0,
logoUrl: team.logoUrl || '',
position: 0, // API doesn't provide team ranking
})),
}; };
} }
} }

View File

@@ -11,7 +11,7 @@ import { LeagueCoverViewData } from '@/lib/view-data/LeagueCoverViewData';
export class LeagueCoverViewDataBuilder { export class LeagueCoverViewDataBuilder {
static build(apiDto: MediaBinaryDTO): LeagueCoverViewData { static build(apiDto: MediaBinaryDTO): LeagueCoverViewData {
return { return {
buffer: apiDto.buffer, buffer: Buffer.from(apiDto.buffer).toString('base64'),
contentType: apiDto.contentType, contentType: apiDto.contentType,
}; };
} }

View File

@@ -11,7 +11,7 @@ import { LeagueLogoViewData } from '@/lib/view-data/LeagueLogoViewData';
export class LeagueLogoViewDataBuilder { export class LeagueLogoViewDataBuilder {
static build(apiDto: MediaBinaryDTO): LeagueLogoViewData { static build(apiDto: MediaBinaryDTO): LeagueLogoViewData {
return { return {
buffer: apiDto.buffer, buffer: Buffer.from(apiDto.buffer).toString('base64'),
contentType: apiDto.contentType, contentType: apiDto.contentType,
}; };
} }

View File

@@ -0,0 +1,36 @@
import type { SponsorDashboardDTO } from '@/lib/types/generated/SponsorDashboardDTO';
import type { SponsorDashboardViewData } from '@/lib/view-data/SponsorDashboardViewData';
/**
* Sponsor Dashboard ViewData Builder
*
* Transforms SponsorDashboardDTO into ViewData for templates.
* Deterministic and side-effect free.
*/
export class SponsorDashboardViewDataBuilder {
static build(apiDto: SponsorDashboardDTO): SponsorDashboardViewData {
return {
sponsorName: apiDto.sponsorName,
totalImpressions: apiDto.metrics.impressions.toString(),
totalInvestment: `$${apiDto.investment.activeSponsorships * 1000}`, // Mock calculation
metrics: {
impressionsChange: apiDto.metrics.impressions > 1000 ? 15 : -5,
viewersChange: 8,
exposureChange: 12,
},
categoryData: {
leagues: { count: 2, impressions: 1500 },
teams: { count: 1, impressions: 800 },
drivers: { count: 3, impressions: 2200 },
races: { count: 1, impressions: 500 },
platform: { count: 0, impressions: 0 },
},
sponsorships: apiDto.sponsorships,
activeSponsorships: apiDto.investment.activeSponsorships,
formattedTotalInvestment: `$${apiDto.investment.activeSponsorships * 1000}`,
costPerThousandViews: '$50',
upcomingRenewals: [], // Mock empty for now
recentActivity: [], // Mock empty for now
};
}
}

View File

@@ -11,7 +11,7 @@ import { SponsorLogoViewData } from '@/lib/view-data/SponsorLogoViewData';
export class SponsorLogoViewDataBuilder { export class SponsorLogoViewDataBuilder {
static build(apiDto: MediaBinaryDTO): SponsorLogoViewData { static build(apiDto: MediaBinaryDTO): SponsorLogoViewData {
return { return {
buffer: apiDto.buffer, buffer: Buffer.from(apiDto.buffer).toString('base64'),
contentType: apiDto.contentType, contentType: apiDto.contentType,
}; };
} }

View File

@@ -11,7 +11,7 @@ import { TeamLogoViewData } from '@/lib/view-data/TeamLogoViewData';
export class TeamLogoViewDataBuilder { export class TeamLogoViewDataBuilder {
static build(apiDto: MediaBinaryDTO): TeamLogoViewData { static build(apiDto: MediaBinaryDTO): TeamLogoViewData {
return { return {
buffer: apiDto.buffer, buffer: Buffer.from(apiDto.buffer).toString('base64'),
contentType: apiDto.contentType, contentType: apiDto.contentType,
}; };
} }

View File

@@ -11,7 +11,7 @@ import { TrackImageViewData } from '@/lib/view-data/TrackImageViewData';
export class TrackImageViewDataBuilder { export class TrackImageViewDataBuilder {
static build(apiDto: MediaBinaryDTO): TrackImageViewData { static build(apiDto: MediaBinaryDTO): TrackImageViewData {
return { return {
buffer: apiDto.buffer, buffer: Buffer.from(apiDto.buffer).toString('base64'),
contentType: apiDto.contentType, contentType: apiDto.contentType,
}; };
} }

View File

@@ -5,31 +5,12 @@ import { LeagueStewardingService } from '../../services/leagues/LeagueStewarding
import { LeagueWalletService } from '../../services/leagues/LeagueWalletService'; import { LeagueWalletService } from '../../services/leagues/LeagueWalletService';
import { LeagueMembershipService } from '../../services/leagues/LeagueMembershipService'; import { LeagueMembershipService } from '../../services/leagues/LeagueMembershipService';
import { LeaguesApiClient } from '@/lib/api/leagues/LeaguesApiClient';
import { DriversApiClient } from '@/lib/api/drivers/DriversApiClient';
import { SponsorsApiClient } from '@/lib/api/sponsors/SponsorsApiClient';
import { RacesApiClient } from '@/lib/api/races/RacesApiClient';
import { WalletsApiClient } from '@/lib/api/wallets/WalletsApiClient';
import { RaceService } from '@/lib/services/races/RaceService';
import { ProtestService } from '@/lib/services/protests/ProtestService';
import { PenaltyService } from '@/lib/services/penalties/PenaltyService';
import { DriverService } from '@/lib/services/drivers/DriverService';
import { import {
LEAGUE_SERVICE_TOKEN, LEAGUE_SERVICE_TOKEN,
LEAGUE_SETTINGS_SERVICE_TOKEN, LEAGUE_SETTINGS_SERVICE_TOKEN,
LEAGUE_STEWARDING_SERVICE_TOKEN, LEAGUE_STEWARDING_SERVICE_TOKEN,
LEAGUE_WALLET_SERVICE_TOKEN, LEAGUE_WALLET_SERVICE_TOKEN,
LEAGUE_MEMBERSHIP_SERVICE_TOKEN, LEAGUE_MEMBERSHIP_SERVICE_TOKEN
LEAGUE_API_CLIENT_TOKEN,
DRIVER_API_CLIENT_TOKEN,
SPONSOR_API_CLIENT_TOKEN,
RACE_API_CLIENT_TOKEN,
WALLET_API_CLIENT_TOKEN,
RACE_SERVICE_TOKEN,
PROTEST_SERVICE_TOKEN,
PENALTY_SERVICE_TOKEN,
DRIVER_SERVICE_TOKEN
} from '../tokens'; } from '../tokens';
export const LeagueModule = new ContainerModule((options) => { export const LeagueModule = new ContainerModule((options) => {
@@ -37,63 +18,36 @@ export const LeagueModule = new ContainerModule((options) => {
// League Service // League Service
bind<LeagueService>(LEAGUE_SERVICE_TOKEN) bind<LeagueService>(LEAGUE_SERVICE_TOKEN)
.toDynamicValue((ctx) => { .toDynamicValue(() => {
const leagueApiClient = ctx.get<LeaguesApiClient>(LEAGUE_API_CLIENT_TOKEN); return new LeagueService();
const driverApiClient = ctx.get<DriversApiClient>(DRIVER_API_CLIENT_TOKEN);
const sponsorApiClient = ctx.get<SponsorsApiClient>(SPONSOR_API_CLIENT_TOKEN);
const raceApiClient = ctx.get<RacesApiClient>(RACE_API_CLIENT_TOKEN);
return new LeagueService(
leagueApiClient,
driverApiClient,
sponsorApiClient,
raceApiClient
);
}) })
.inSingletonScope(); .inSingletonScope();
// League Settings Service // League Settings Service
bind<LeagueSettingsService>(LEAGUE_SETTINGS_SERVICE_TOKEN) bind<LeagueSettingsService>(LEAGUE_SETTINGS_SERVICE_TOKEN)
.toDynamicValue((ctx) => { .toDynamicValue(() => {
const leagueApiClient = ctx.get<LeaguesApiClient>(LEAGUE_API_CLIENT_TOKEN); return new LeagueSettingsService();
const driverApiClient = ctx.get<DriversApiClient>(DRIVER_API_CLIENT_TOKEN);
return new LeagueSettingsService(leagueApiClient, driverApiClient);
}) })
.inSingletonScope(); .inSingletonScope();
// League Stewarding Service // League Stewarding Service
bind<LeagueStewardingService>(LEAGUE_STEWARDING_SERVICE_TOKEN) bind<LeagueStewardingService>(LEAGUE_STEWARDING_SERVICE_TOKEN)
.toDynamicValue((ctx) => { .toDynamicValue(() => {
const raceService = ctx.get<RaceService>(RACE_SERVICE_TOKEN); return new LeagueStewardingService();
const protestService = ctx.get<ProtestService>(PROTEST_SERVICE_TOKEN);
const penaltyService = ctx.get<PenaltyService>(PENALTY_SERVICE_TOKEN);
const driverService = ctx.get<DriverService>(DRIVER_SERVICE_TOKEN);
const membershipService = ctx.get<LeagueMembershipService>(LEAGUE_MEMBERSHIP_SERVICE_TOKEN);
return new LeagueStewardingService(
raceService,
protestService,
penaltyService,
driverService,
membershipService
);
}) })
.inSingletonScope(); .inSingletonScope();
// League Wallet Service // League Wallet Service
bind<LeagueWalletService>(LEAGUE_WALLET_SERVICE_TOKEN) bind<LeagueWalletService>(LEAGUE_WALLET_SERVICE_TOKEN)
.toDynamicValue((ctx) => { .toDynamicValue(() => {
const walletApiClient = ctx.get<WalletsApiClient>(WALLET_API_CLIENT_TOKEN); return new LeagueWalletService();
return new LeagueWalletService(walletApiClient);
}) })
.inSingletonScope(); .inSingletonScope();
// League Membership Service // League Membership Service
bind<LeagueMembershipService>(LEAGUE_MEMBERSHIP_SERVICE_TOKEN) bind<LeagueMembershipService>(LEAGUE_MEMBERSHIP_SERVICE_TOKEN)
.toDynamicValue((ctx) => { .toDynamicValue(() => {
const leagueApiClient = ctx.get<LeaguesApiClient>(LEAGUE_API_CLIENT_TOKEN); return new LeagueMembershipService();
return new LeagueMembershipService(leagueApiClient);
}) })
.inSingletonScope(); .inSingletonScope();
}); });

View File

@@ -1,16 +1,12 @@
import { ContainerModule } from 'inversify'; import { ContainerModule } from 'inversify';
import { SPONSOR_SERVICE_TOKEN, SPONSOR_API_CLIENT_TOKEN } from '../tokens'; import { SPONSOR_SERVICE_TOKEN } from '../tokens';
import { SponsorService } from '@/lib/services/sponsors/SponsorService'; import { SponsorService } from '@/lib/services/sponsors/SponsorService';
import { SponsorsApiClient } from '@/lib/api/sponsors/SponsorsApiClient';
export const SponsorModule = new ContainerModule((options) => { export const SponsorModule = new ContainerModule((options) => {
const bind = options.bind; const bind = options.bind;
// Sponsor Service // Sponsor Service - creates its own dependencies for server safety
bind<SponsorService>(SPONSOR_SERVICE_TOKEN) bind<SponsorService>(SPONSOR_SERVICE_TOKEN)
.toDynamicValue((ctx) => { .to(SponsorService)
const apiClient = ctx.get<SponsorsApiClient>(SPONSOR_API_CLIENT_TOKEN); .inTransientScope(); // Not singleton for server concurrency
return new SponsorService(apiClient);
})
.inSingletonScope();
}); });

View File

@@ -0,0 +1,23 @@
export class MedalDisplay {
static getColor(position: number): string {
switch (position) {
case 1: return 'text-yellow-400';
case 2: return 'text-gray-300';
case 3: return 'text-amber-600';
default: return 'text-gray-500';
}
}
static getBg(position: number): string {
switch (position) {
case 1: return 'bg-yellow-400/10 border-yellow-400/30';
case 2: return 'bg-gray-300/10 border-gray-300/30';
case 3: return 'bg-amber-600/10 border-amber-600/30';
default: return 'bg-iron-gray/50 border-charcoal-outline';
}
}
static getMedalIcon(position: number): string | null {
return position <= 3 ? '🏆' : null;
}
}

View File

@@ -1,11 +1,5 @@
/**
* RatingDisplay
*
* Deterministic rating formatting for display.
*/
export class RatingDisplay { export class RatingDisplay {
static format(rating: number): string { static format(rating: number): string {
return rating.toFixed(1); return rating.toString();
} }
} }

View File

@@ -0,0 +1,41 @@
export class SkillLevelDisplay {
static getLabel(skillLevel: string): string {
const levels: Record<string, string> = {
pro: 'Pro',
advanced: 'Advanced',
intermediate: 'Intermediate',
beginner: 'Beginner',
};
return levels[skillLevel] || skillLevel;
}
static getColor(skillLevel: string): string {
const colors: Record<string, string> = {
pro: 'text-yellow-400',
advanced: 'text-purple-400',
intermediate: 'text-primary-blue',
beginner: 'text-green-400',
};
return colors[skillLevel] || 'text-gray-400';
}
static getBgColor(skillLevel: string): string {
const colors: Record<string, string> = {
pro: 'bg-yellow-400/10',
advanced: 'bg-purple-400/10',
intermediate: 'bg-primary-blue/10',
beginner: 'bg-green-400/10',
};
return colors[skillLevel] || 'bg-gray-400/10';
}
static getBorderColor(skillLevel: string): string {
const colors: Record<string, string> = {
pro: 'border-yellow-400/30',
advanced: 'border-purple-400/30',
intermediate: 'border-primary-blue/30',
beginner: 'border-green-400/30',
};
return colors[skillLevel] || 'border-gray-400/30';
}
}

View File

@@ -0,0 +1,7 @@
export class WinRateDisplay {
static calculate(racesCompleted: number, wins: number): string {
if (racesCompleted === 0) return '0.0';
const rate = (wins / racesCompleted) * 100;
return rate.toFixed(1);
}
}

View File

@@ -20,7 +20,7 @@ export class DeleteUserMutation implements Mutation<{ userId: string }, void, Mu
// Manual construction: Service creates its own dependencies // Manual construction: Service creates its own dependencies
const service = new AdminService(); const service = new AdminService();
const result = await service.deleteUser(input.userId); const result = await service.deleteUser();
if (result.isErr()) { if (result.isErr()) {
return Result.err(mapToMutationError(result.getError())); return Result.err(mapToMutationError(result.getError()));

View File

@@ -16,19 +16,19 @@ import { Mutation } from '@/lib/contracts/mutations/Mutation';
*/ */
export class UpdateUserStatusMutation implements Mutation<{ userId: string; status: string }, void, MutationError> { export class UpdateUserStatusMutation implements Mutation<{ userId: string; status: string }, void, MutationError> {
async execute(input: { userId: string; status: string }): Promise<Result<void, MutationError>> { async execute(input: { userId: string; status: string }): Promise<Result<void, MutationError>> {
try { try {
// Manual construction: Service creates its own dependencies // Manual construction: Service creates its own dependencies
const service = new AdminService(); const service = new AdminService();
const result = await service.updateUserStatus(input.userId, input.status); const result = await service.updateUserStatus(input.userId, input.status);
if (result.isErr()) { if (result.isErr()) {
return Result.err(mapToMutationError(result.getError())); return Result.err(mapToMutationError(result.getError()));
} }
return Result.ok(undefined); return Result.ok(undefined);
} catch (err) { } catch (err) {
return Result.err('updateFailed'); return Result.err('updateFailed');
} }
} }
} }

View File

@@ -21,7 +21,7 @@ export class CreateLeagueMutation {
const logger = new ConsoleLogger(); const logger = new ConsoleLogger();
const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger); const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
this.service = new LeagueService(apiClient); this.service = new LeagueService();
} }
async execute(input: CreateLeagueInputDTO): Promise<Result<string, string>> { async execute(input: CreateLeagueInputDTO): Promise<Result<string, string>> {

View File

@@ -21,7 +21,7 @@ export class RosterAdminMutation {
const logger = new ConsoleLogger(); const logger = new ConsoleLogger();
const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger); const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
this.service = new LeagueService(apiClient); this.service = new LeagueService();
} }
async approveJoinRequest(leagueId: string, joinRequestId: string): Promise<Result<void, string>> { async approveJoinRequest(leagueId: string, joinRequestId: string): Promise<Result<void, string>> {

View File

@@ -22,7 +22,7 @@ export class ScheduleAdminMutation {
const logger = new ConsoleLogger(); const logger = new ConsoleLogger();
const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger); const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
this.service = new LeagueService(apiClient); this.service = new LeagueService();
} }
async publishSchedule(leagueId: string, seasonId: string): Promise<Result<void, string>> { async publishSchedule(leagueId: string, seasonId: string): Promise<Result<void, string>> {

View File

@@ -20,7 +20,7 @@ export class StewardingMutation {
const logger = new ConsoleLogger(); const logger = new ConsoleLogger();
const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger); const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
this.service = new LeagueService(apiClient); this.service = new LeagueService();
} }
async applyPenalty(input: { async applyPenalty(input: {

View File

@@ -20,7 +20,7 @@ export class WalletMutation {
const logger = new ConsoleLogger(); const logger = new ConsoleLogger();
const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger); const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
this.service = new LeagueService(apiClient); this.service = new LeagueService();
} }
async withdraw(leagueId: string, amount: number): Promise<Result<void, string>> { async withdraw(leagueId: string, amount: number): Promise<Result<void, string>> {

View File

@@ -11,20 +11,14 @@ import { PresentationError, mapToPresentationError } from '@/lib/contracts/page-
* Server-side composition for admin users page. * Server-side composition for admin users page.
* Fetches user list from API and transforms to ViewData. * Fetches user list from API and transforms to ViewData.
*/ */
export class AdminUsersPageQuery implements PageQuery<AdminUsersViewData, { search?: string; role?: string; status?: string; page?: number; limit?: number }> { export class AdminUsersPageQuery implements PageQuery<AdminUsersViewData, void> {
async execute(query: { search?: string; role?: string; status?: string; page?: number; limit?: number }): Promise<Result<AdminUsersViewData, PresentationError>> { async execute(): Promise<Result<AdminUsersViewData, PresentationError>> {
try { try {
// Manual construction: Service creates its own dependencies // Manual construction: Service creates its own dependencies
const adminService = new AdminService(); const adminService = new AdminService();
// Fetch user list via service // Fetch user list via service
const apiDtoResult = await adminService.listUsers({ const apiDtoResult = await adminService.listUsers();
search: query.search,
role: query.role,
status: query.status,
page: query.page || 1,
limit: query.limit || 50,
});
if (apiDtoResult.isErr()) { if (apiDtoResult.isErr()) {
return Result.err(mapToPresentationError(apiDtoResult.getError())); return Result.err(mapToPresentationError(apiDtoResult.getError()));
@@ -46,8 +40,8 @@ export class AdminUsersPageQuery implements PageQuery<AdminUsersViewData, { sear
} }
// Static method to avoid object construction in server code // Static method to avoid object construction in server code
static async execute(query: { search?: string; role?: string; status?: string; page?: number; limit?: number }): Promise<Result<AdminUsersViewData, PresentationError>> { static async execute(): Promise<Result<AdminUsersViewData, PresentationError>> {
const queryInstance = new AdminUsersPageQuery(); const queryInstance = new AdminUsersPageQuery();
return queryInstance.execute(query); return queryInstance.execute();
} }
} }

View File

@@ -0,0 +1,38 @@
import { Result } from '@/lib/contracts/Result';
import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { SponsorService } from '@/lib/services/sponsors/SponsorService';
import { SponsorDashboardViewDataBuilder } from '@/lib/builders/view-data/SponsorDashboardViewDataBuilder';
import type { SponsorDashboardViewData } from '@/lib/view-data/SponsorDashboardViewData';
/**
* Sponsor Dashboard Page Query
*
* Composes data for the sponsor dashboard page.
* Maps domain errors to presentation errors.
*/
export class SponsorDashboardPageQuery implements PageQuery<SponsorDashboardViewData, string> {
async execute(sponsorId: string): Promise<Result<SponsorDashboardViewData, string>> {
const service = new SponsorService();
const dashboardResult = await service.getSponsorDashboard(sponsorId);
if (dashboardResult.isErr()) {
return Result.err(this.mapToPresentationError(dashboardResult.getError()));
}
const dto = dashboardResult.unwrap();
const viewData = SponsorDashboardViewDataBuilder.build(dto);
return Result.ok(viewData);
}
private mapToPresentationError(domainError: { type: string }): string {
switch (domainError.type) {
case 'notFound':
return 'Dashboard not found';
case 'notImplemented':
return 'Dashboard feature not yet implemented';
default:
return 'Failed to load dashboard';
}
}
}

View File

@@ -1,26 +1,25 @@
import type { PageQueryResult } from '@/lib/contracts/page-queries/PageQueryResult'; import { Result } from '@/lib/contracts/Result';
import { DriverProfilePageService } from '@/lib/services/drivers/DriverProfilePageService'; import { DriverProfilePageService } from '@/lib/services/drivers/DriverProfilePageService';
import { DriverProfileViewModelBuilder } from '@/lib/builders/view-models/DriverProfileViewModelBuilder'; import { DriverProfileViewDataBuilder } from '@/lib/builders/view-data/DriverProfileViewDataBuilder';
import type { DriverProfileViewModel } from '@/lib/view-models/DriverProfileViewModel'; import type { DriverProfileViewData } from '@/lib/types/view-data/DriverProfileViewData';
/** /**
* DriverProfilePageQuery * DriverProfilePageQuery
* *
* Server-side data fetcher for the driver profile page. * Server-side data fetcher for the driver profile page.
* Returns a discriminated union with all possible page states. * Returns Result<ViewData, PresentationError>
* Uses Service for data access and ViewModelBuilder for transformation. * Uses Service for data access and ViewDataBuilder for transformation.
*/ */
export class DriverProfilePageQuery { export class DriverProfilePageQuery {
/** /**
* Execute the driver profile page query * Execute the driver profile page query
* *
* @param driverId - The driver ID to fetch profile for * @param driverId - The driver ID to fetch profile for
* @returns PageQueryResult with discriminated union of states * @returns Result with ViewData or error
*/ */
static async execute(driverId: string | null): Promise<PageQueryResult<DriverProfileViewModel>> { static async execute(driverId: string | null): Promise<Result<DriverProfileViewData, string>> {
// Handle missing driver ID
if (!driverId) { if (!driverId) {
return { status: 'notFound' }; return Result.err('NotFound');
} }
try { try {
@@ -31,26 +30,26 @@ export class DriverProfilePageQuery {
if (result.isErr()) { if (result.isErr()) {
const error = result.getError(); const error = result.getError();
if (error === 'notFound') { if (error === 'notFound') {
return { status: 'notFound' }; return Result.err('NotFound');
} }
if (error === 'unauthorized') { if (error === 'unauthorized') {
return { status: 'error', errorId: 'UNAUTHORIZED' }; return Result.err('Unauthorized');
} }
return { status: 'error', errorId: 'DRIVER_PROFILE_FETCH_FAILED' }; return Result.err('Error');
} }
// Build ViewModel from DTO // Build ViewData from DTO
const dto = result.unwrap(); const dto = result.unwrap();
const viewModel = DriverProfileViewModelBuilder.build(dto); const viewData = DriverProfileViewDataBuilder.build(dto);
return { status: 'ok', dto: viewModel }; return Result.ok(viewData);
} catch (error) { } catch (error) {
console.error('DriverProfilePageQuery failed:', error); console.error('DriverProfilePageQuery failed:', error);
return { status: 'error', errorId: 'DRIVER_PROFILE_FETCH_FAILED' }; return Result.err('Error');
} }
} }
} }

View File

@@ -1,22 +1,22 @@
import type { PageQueryResult } from '@/lib/contracts/page-queries/PageQueryResult'; import { Result } from '@/lib/contracts/Result';
import { DriversPageService } from '@/lib/services/drivers/DriversPageService'; import { DriversPageService } from '@/lib/services/drivers/DriversPageService';
import { DriversViewModelBuilder } from '@/lib/builders/view-models/DriversViewModelBuilder'; import { DriversViewDataBuilder } from '@/lib/builders/view-data/DriversViewDataBuilder';
import type { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel'; import type { DriversViewData } from '@/lib/types/view-data/DriversViewData';
/** /**
* DriversPageQuery * DriversPageQuery
* *
* Server-side data fetcher for the drivers listing page. * Server-side data fetcher for the drivers listing page.
* Returns a discriminated union with all possible page states. * Returns Result<ViewData, PresentationError>
* Uses Service for data access and ViewModelBuilder for transformation. * Uses Service for data access and ViewDataBuilder for transformation.
*/ */
export class DriversPageQuery { export class DriversPageQuery {
/** /**
* Execute the drivers page query * Execute the drivers page query
* *
* @returns PageQueryResult with discriminated union of states * @returns Result with ViewData or error
*/ */
static async execute(): Promise<PageQueryResult<DriverLeaderboardViewModel>> { static async execute(): Promise<Result<DriversViewData, string>> {
try { try {
// Manual wiring: construct dependencies explicitly // Manual wiring: construct dependencies explicitly
const service = new DriversPageService(); const service = new DriversPageService();
@@ -25,22 +25,22 @@ export class DriversPageQuery {
if (result.isErr()) { if (result.isErr()) {
const error = result.getError(); const error = result.getError();
if (error === 'notFound') { if (error === 'notFound') {
return { status: 'notFound' }; return Result.err('NotFound');
} }
return { status: 'error', errorId: 'DRIVERS_FETCH_FAILED' }; return Result.err('Error');
} }
// Build ViewModel from DTO // Build ViewData from DTO
const dto = result.unwrap(); const dto = result.unwrap();
const viewModel = DriversViewModelBuilder.build(dto); const viewData = DriversViewDataBuilder.build(dto);
return { status: 'ok', dto: viewModel }; return Result.ok(viewData);
} catch (error) { } catch (error) {
console.error('DriversPageQuery failed:', error); console.error('DriversPageQuery failed:', error);
return { status: 'error', errorId: 'DRIVERS_FETCH_FAILED' }; return Result.err('Error');
} }
} }
} }

View File

@@ -2,10 +2,7 @@ import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { Result } from '@/lib/contracts/Result'; import { Result } from '@/lib/contracts/Result';
import { LeaguesViewDataBuilder } from '@/lib/builders/view-data/LeaguesViewDataBuilder'; import { LeaguesViewDataBuilder } from '@/lib/builders/view-data/LeaguesViewDataBuilder';
import type { LeaguesViewData } from '@/lib/view-data/LeaguesViewData'; import type { LeaguesViewData } from '@/lib/view-data/LeaguesViewData';
import { LeaguesApiClient } from '@/lib/api/leagues/LeaguesApiClient'; import { LeagueService } from '@/lib/services/leagues/LeagueService';
import { DomainError } from '@/lib/contracts/services/Service';
import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
/** /**
* Leagues page query * Leagues page query
@@ -14,40 +11,30 @@ import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
*/ */
export class LeaguesPageQuery implements PageQuery<LeaguesViewData, void> { export class LeaguesPageQuery implements PageQuery<LeaguesViewData, void> {
async execute(): Promise<Result<LeaguesViewData, 'notFound' | 'redirect' | 'LEAGUES_FETCH_FAILED' | 'UNKNOWN_ERROR'>> { async execute(): Promise<Result<LeaguesViewData, 'notFound' | 'redirect' | 'LEAGUES_FETCH_FAILED' | 'UNKNOWN_ERROR'>> {
// Manual wiring: create API client // Manual construction: Service creates its own dependencies
const baseUrl = process.env.NEXT_PUBLIC_API_URL || ''; const service = new LeagueService();
const errorReporter = new ConsoleErrorReporter();
const logger = new ConsoleLogger(); // Fetch data using service
const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger); const result = await service.getAllLeagues();
// Fetch data using API client if (result.isErr()) {
try { const error = result.getError();
const apiDto = await apiClient.getAllWithCapacityAndScoring(); switch (error.type) {
case 'notFound':
if (!apiDto || !apiDto.leagues) {
return Result.err('notFound');
}
// Transform to ViewData using builder
const viewData = LeaguesViewDataBuilder.build(apiDto);
return Result.ok(viewData);
} catch (error) {
console.error('LeaguesPageQuery failed:', error);
if (error instanceof Error) {
if (error.message.includes('403') || error.message.includes('401')) {
return Result.err('redirect');
}
if (error.message.includes('404')) {
return Result.err('notFound'); return Result.err('notFound');
} case 'unauthorized':
if (error.message.includes('5') || error.message.includes('server')) { case 'forbidden':
return Result.err('redirect');
case 'serverError':
return Result.err('LEAGUES_FETCH_FAILED'); return Result.err('LEAGUES_FETCH_FAILED');
} default:
return Result.err('UNKNOWN_ERROR');
} }
return Result.err('UNKNOWN_ERROR');
} }
// Transform to ViewData using builder
const viewData = LeaguesViewDataBuilder.build(result.unwrap());
return Result.ok(viewData);
} }
// Static method to avoid object construction in server code // Static method to avoid object construction in server code

View File

@@ -1,5 +1,5 @@
import { AdminApiClient } from '@/lib/api/admin/AdminApiClient'; import { AdminApiClient } from '@/lib/api/admin/AdminApiClient';
import type { UserDto, DashboardStats, UserListResponse, ListUsersQuery } from '@/lib/api/admin/AdminApiClient'; import type { UserDto, DashboardStats, UserListResponse } from '@/lib/types/admin';
import { Result } from '@/lib/contracts/Result'; import { Result } from '@/lib/contracts/Result';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger'; import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter'; import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
@@ -30,82 +30,103 @@ export class AdminService implements Service {
} }
/** /**
* Get dashboard statistics * Get dashboard statistics
*/ */
async getDashboardStats(): Promise<Result<DashboardStats, DomainError>> { async getDashboardStats(): Promise<Result<DashboardStats, DomainError>> {
try { // Mock data until API is implemented
const result = await this.apiClient.getDashboardStats(); const mockStats: DashboardStats = {
return Result.ok(result); totalUsers: 1250,
} catch (error) { activeUsers: 1100,
console.error('AdminService.getDashboardStats failed:', error); suspendedUsers: 50,
deletedUsers: 100,
if (error instanceof Error) { systemAdmins: 5,
if (error.message.includes('403') || error.message.includes('401')) { recentLogins: 450,
return Result.err({ type: 'notFound', message: 'Access denied' }); newUsersToday: 12,
} userGrowth: [
} { label: 'This week', value: 45, color: '#10b981' },
{ label: 'Last week', value: 38, color: '#3b82f6' },
return Result.err({ type: 'serverError', message: 'Failed to fetch dashboard stats' }); ],
} roleDistribution: [
} { label: 'Users', value: 1200, color: '#6b7280' },
{ label: 'Admins', value: 50, color: '#8b5cf6' },
],
statusDistribution: {
active: 1100,
suspended: 50,
deleted: 100,
},
activityTimeline: [
{ date: '2024-01-01', newUsers: 10, logins: 200 },
{ date: '2024-01-02', newUsers: 15, logins: 220 },
],
};
return Result.ok(mockStats);
}
/** /**
* List users with filtering and pagination * List users with filtering and pagination
*/ */
async listUsers(query: ListUsersQuery = {}): Promise<Result<UserListResponse, DomainError>> { async listUsers(): Promise<Result<UserListResponse, DomainError>> {
try { // Mock data until API is implemented
const result = await this.apiClient.listUsers(query); const mockUsers: UserDto[] = [
return Result.ok(result); {
} catch (error) { id: '1',
console.error('AdminService.listUsers failed:', error); email: 'admin@example.com',
displayName: 'Admin User',
if (error instanceof Error) { roles: ['owner', 'admin'],
if (error.message.includes('403') || error.message.includes('401')) { status: 'active',
return Result.err({ type: 'notFound', message: 'Access denied' }); isSystemAdmin: true,
} createdAt: '2024-01-01T00:00:00.000Z',
} updatedAt: '2024-01-01T00:00:00.000Z',
lastLoginAt: '2024-01-15T10:00:00.000Z',
return Result.err({ type: 'serverError', message: 'Failed to fetch users' }); primaryDriverId: 'driver-1',
} },
} {
id: '2',
email: 'user@example.com',
displayName: 'Regular User',
roles: ['user'],
status: 'active',
isSystemAdmin: false,
createdAt: '2024-01-02T00:00:00.000Z',
updatedAt: '2024-01-02T00:00:00.000Z',
lastLoginAt: '2024-01-14T15:00:00.000Z',
},
];
const mockResponse: UserListResponse = {
users: mockUsers,
total: 2,
page: 1,
limit: 50,
totalPages: 1,
};
return Result.ok(mockResponse);
}
/** /**
* Update user status * Update user status
*/ */
async updateUserStatus(userId: string, status: string): Promise<Result<UserDto, DomainError>> { async updateUserStatus(userId: string, status: string): Promise<Result<UserDto, DomainError>> {
try { // Mock success until API is implemented
const result = await this.apiClient.updateUserStatus(userId, status); return Result.ok({
return Result.ok(result); id: userId,
} catch (error) { email: 'mock@example.com',
console.error('AdminService.updateUserStatus failed:', error); displayName: 'Mock User',
roles: ['user'],
if (error instanceof Error) { status,
if (error.message.includes('403') || error.message.includes('401')) { isSystemAdmin: false,
return Result.err({ type: 'forbidden', message: 'Insufficient permissions' }); createdAt: '2024-01-01T00:00:00.000Z',
} updatedAt: '2024-01-01T00:00:00.000Z',
} });
}
return Result.err({ type: 'serverError', message: 'Failed to update user status' });
}
}
/** /**
* Delete a user (soft delete) * Delete a user (soft delete)
*/ */
async deleteUser(userId: string): Promise<Result<void, DomainError>> { async deleteUser(): Promise<Result<void, DomainError>> {
try { // Mock success until API is implemented
await this.apiClient.deleteUser(userId); return Result.ok(undefined);
return Result.ok(undefined); }
} catch (error) {
console.error('AdminService.deleteUser failed:', error);
if (error instanceof Error) {
if (error.message.includes('403') || error.message.includes('401')) {
return Result.err({ type: 'forbidden', message: 'Insufficient permissions' });
}
}
return Result.err({ type: 'serverError', message: 'Failed to delete user' });
}
}
} }

View File

@@ -1,17 +1,38 @@
import { Result } from '@/lib/contracts/Result'; import { Result } from '@/lib/contracts/Result';
import type { Service } from '@/lib/contracts/services/Service'; import type { Service } from '@/lib/contracts/services/Service';
import type { GetLiveriesOutputDTO } from '@/lib/types/tbd/GetLiveriesOutputDTO';
/** /**
* Livery Service * Livery Service
* *
* Currently not implemented - returns NotImplemented errors for all endpoints. * Provides livery management functionality.
*/ */
export class LiveryService implements Service { export class LiveryService implements Service {
async getLiveries(): Promise<Result<void, 'NOT_IMPLEMENTED'>> { async getLiveries(driverId: string): Promise<Result<GetLiveriesOutputDTO, string>> {
return Result.err('NOT_IMPLEMENTED'); // Mock data for now
const mockLiveries: GetLiveriesOutputDTO = {
liveries: [
{
id: 'livery-1',
name: 'Default Livery',
imageUrl: '/mock-livery-1.png',
createdAt: new Date().toISOString(),
isActive: true,
},
{
id: 'livery-2',
name: 'Custom Livery',
imageUrl: '/mock-livery-2.png',
createdAt: new Date(Date.now() - 86400000).toISOString(),
isActive: false,
},
],
};
return Result.ok(mockLiveries);
} }
async uploadLivery(): Promise<Result<void, 'NOT_IMPLEMENTED'>> { async uploadLivery(driverId: string, file: File): Promise<Result<{ liveryId: string }, string>> {
return Result.err('NOT_IMPLEMENTED'); // Mock implementation
return Result.ok({ liveryId: 'new-livery-id' });
} }
} }

View File

@@ -1,18 +1,11 @@
import { DriversApiClient } from '@/lib/api/drivers/DriversApiClient'; import { DriversApiClient } from '@/lib/api/drivers/DriversApiClient';
import { TeamsApiClient } from '@/lib/api/teams/TeamsApiClient';
import { Result } from '@/lib/contracts/Result'; import { Result } from '@/lib/contracts/Result';
import { Service, DomainError } from '@/lib/contracts/services/Service'; import { Service, DomainError } from '@/lib/contracts/services/Service';
import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter'; import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger'; import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import type { DriverLeaderboardItemDTO } from '@/lib/types/generated/DriverLeaderboardItemDTO';
import type { TeamListItemDTO } from '@/lib/types/generated/TeamListItemDTO';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl'; import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { ApiError } from '@/lib/api/base/ApiError'; import { ApiError } from '@/lib/api/base/ApiError';
import type { LeaderboardsData } from '@/lib/types/LeaderboardsData';
export interface LeaderboardsData {
drivers: { drivers: DriverLeaderboardItemDTO[] };
teams: { teams: TeamListItemDTO[] };
}
export class LeaderboardsService implements Service { export class LeaderboardsService implements Service {
async getLeaderboards(): Promise<Result<LeaderboardsData, DomainError>> { async getLeaderboards(): Promise<Result<LeaderboardsData, DomainError>> {
@@ -20,33 +13,20 @@ export class LeaderboardsService implements Service {
const baseUrl = getWebsiteApiBaseUrl(); const baseUrl = getWebsiteApiBaseUrl();
const errorReporter = new ConsoleErrorReporter(); const errorReporter = new ConsoleErrorReporter();
const logger = new ConsoleLogger(); const logger = new ConsoleLogger();
const driversApiClient = new DriversApiClient(baseUrl, errorReporter, logger); const driversApiClient = new DriversApiClient(baseUrl, errorReporter, logger);
const teamsApiClient = new TeamsApiClient(baseUrl, errorReporter, logger);
const driverResult = await driversApiClient.getLeaderboard();
const [driverResult, teamResult] = await Promise.all([
driversApiClient.getLeaderboard(), if (!driverResult) {
teamsApiClient.getAll(),
]);
if (!driverResult && !teamResult) {
return Result.err({ type: 'notFound', message: 'No leaderboard data available' }); return Result.err({ type: 'notFound', message: 'No leaderboard data available' });
} }
// Check if team ranking is needed but not provided by API
// TeamListItemDTO does not have a rank field, so we cannot provide ranked team data
if (teamResult && teamResult.teams.length > 0) {
const hasRankField = teamResult.teams.some(team => 'rank' in team);
if (!hasRankField) {
return Result.err({ type: 'serverError', message: 'Team ranking not implemented' });
}
}
const data: LeaderboardsData = { const data: LeaderboardsData = {
drivers: driverResult || { drivers: [] }, drivers: driverResult,
teams: teamResult || { teams: [] }, teams: { teams: [] }, // Teams leaderboard not implemented
}; };
return Result.ok(data); return Result.ok(data);
} catch (error) { } catch (error) {
// Convert ApiError to DomainError // Convert ApiError to DomainError
@@ -65,12 +45,12 @@ export class LeaderboardsService implements Service {
return Result.err({ type: 'unknown', message: error.message }); return Result.err({ type: 'unknown', message: error.message });
} }
} }
// Handle non-ApiError cases // Handle non-ApiError cases
if (error instanceof Error) { if (error instanceof Error) {
return Result.err({ type: 'unknown', message: error.message }); return Result.err({ type: 'unknown', message: error.message });
} }
return Result.err({ type: 'unknown', message: 'Leaderboards fetch failed' }); return Result.err({ type: 'unknown', message: 'Leaderboards fetch failed' });
} }
} }

View File

@@ -6,10 +6,7 @@ import { CreateLeagueInputDTO } from "@/lib/types/generated/CreateLeagueInputDTO
import { CreateLeagueOutputDTO } from "@/lib/types/generated/CreateLeagueOutputDTO"; import { CreateLeagueOutputDTO } from "@/lib/types/generated/CreateLeagueOutputDTO";
import type { MembershipRole } from "@/lib/types/MembershipRole"; import type { MembershipRole } from "@/lib/types/MembershipRole";
import type { LeagueRosterJoinRequestDTO } from "@/lib/types/generated/LeagueRosterJoinRequestDTO"; import type { LeagueRosterJoinRequestDTO } from "@/lib/types/generated/LeagueRosterJoinRequestDTO";
import type { RaceDTO } from "@/lib/types/generated/RaceDTO";
import type { TotalLeaguesDTO } from '@/lib/types/generated/TotalLeaguesDTO'; import type { TotalLeaguesDTO } from '@/lib/types/generated/TotalLeaguesDTO';
import type { LeagueScoringConfigDTO } from "@/lib/types/generated/LeagueScoringConfigDTO";
import type { LeagueMembership } from "@/lib/types/LeagueMembership";
import type { LeagueSeasonSummaryDTO } from '@/lib/types/generated/LeagueSeasonSummaryDTO'; import type { LeagueSeasonSummaryDTO } from '@/lib/types/generated/LeagueSeasonSummaryDTO';
import type { LeagueScheduleDTO } from '@/lib/types/generated/LeagueScheduleDTO'; import type { LeagueScheduleDTO } from '@/lib/types/generated/LeagueScheduleDTO';
import type { CreateLeagueScheduleRaceInputDTO } from '@/lib/types/generated/CreateLeagueScheduleRaceInputDTO'; import type { CreateLeagueScheduleRaceInputDTO } from '@/lib/types/generated/CreateLeagueScheduleRaceInputDTO';
@@ -19,27 +16,52 @@ import type { LeagueScheduleRaceMutationSuccessDTO } from '@/lib/types/generated
import type { LeagueSeasonSchedulePublishOutputDTO } from '@/lib/types/generated/LeagueSeasonSchedulePublishOutputDTO'; import type { LeagueSeasonSchedulePublishOutputDTO } from '@/lib/types/generated/LeagueSeasonSchedulePublishOutputDTO';
import type { LeagueRosterMemberDTO } from '@/lib/types/generated/LeagueRosterMemberDTO'; import type { LeagueRosterMemberDTO } from '@/lib/types/generated/LeagueRosterMemberDTO';
import type { LeagueMembershipsDTO } from '@/lib/types/generated/LeagueMembershipsDTO'; import type { LeagueMembershipsDTO } from '@/lib/types/generated/LeagueMembershipsDTO';
import { Result } from '@/lib/contracts/Result';
import { DomainError, Service } from '@/lib/contracts/services/Service';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { getWebsiteServerEnv } from '@/lib/config/env';
import { AllLeaguesWithCapacityAndScoringDTO } from '@/lib/types/AllLeaguesWithCapacityAndScoringDTO';
/** /**
* League Service - DTO Only * League Service - DTO Only
* *
* Returns raw API DTOs. No ViewModels or UX logic. * Returns Result<ApiDto, DomainError>. No ViewModels or UX logic.
* All client-side presentation logic must be handled by hooks/components. * All client-side presentation logic must be handled by hooks/components.
* @server-safe
*/ */
export class LeagueService { export class LeagueService implements Service {
constructor( private apiClient: LeaguesApiClient;
private readonly apiClient: LeaguesApiClient, private driversApiClient?: DriversApiClient;
private readonly driversApiClient?: DriversApiClient, private sponsorsApiClient?: SponsorsApiClient;
private readonly sponsorsApiClient?: SponsorsApiClient, private racesApiClient?: RacesApiClient;
private readonly racesApiClient?: RacesApiClient
) {}
async getAllLeagues(): Promise<any> { constructor() {
return this.apiClient.getAllWithCapacityAndScoring(); const baseUrl = getWebsiteApiBaseUrl();
const logger = new ConsoleLogger();
const { NODE_ENV } = getWebsiteServerEnv();
const errorReporter = new EnhancedErrorReporter(logger, {
showUserNotifications: false,
logToConsole: true,
reportToExternal: NODE_ENV === 'production',
});
this.apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
// Optional clients can be initialized if needed
} }
async getLeagueStandings(leagueId: string): Promise<any> { async getAllLeagues(): Promise<Result<AllLeaguesWithCapacityAndScoringDTO, DomainError>> {
return this.apiClient.getStandings(leagueId); try {
const dto = await this.apiClient.getAllWithCapacityAndScoring();
return Result.ok(dto);
} catch (error) {
console.error('LeagueService.getAllLeagues failed:', error);
return Result.err({ type: 'serverError', message: 'Failed to fetch leagues' });
}
}
async getLeagueStandings(): Promise<Result<never, DomainError>> {
return Result.err({ type: 'notImplemented', message: 'League standings endpoint not implemented' });
} }
async getLeagueStats(): Promise<TotalLeaguesDTO> { async getLeagueStats(): Promise<TotalLeaguesDTO> {
@@ -166,16 +188,15 @@ export class LeagueService {
return { success: dto.success }; return { success: dto.success };
} }
async getLeagueDetail(leagueId: string): Promise<any> { async getLeagueDetail(): Promise<Result<never, DomainError>> {
return this.apiClient.getAllWithCapacityAndScoring(); return Result.err({ type: 'notImplemented', message: 'League detail endpoint not implemented' });
} }
async getLeagueDetailPageData(leagueId: string): Promise<any> { async getLeagueDetailPageData(): Promise<Result<never, DomainError>> {
return this.apiClient.getAllWithCapacityAndScoring(); return Result.err({ type: 'notImplemented', message: 'League detail page data endpoint not implemented' });
} }
async getScoringPresets(): Promise<any[]> { async getScoringPresets(): Promise<Result<never, DomainError>> {
const result = await this.apiClient.getScoringPresets(); return Result.err({ type: 'notImplemented', message: 'Scoring presets endpoint not implemented' });
return result.presets;
} }
} }

View File

@@ -1,5 +1,18 @@
import { Result } from '@/lib/contracts/Result'; import { Result } from '@/lib/contracts/Result';
import { DomainError } from '@/lib/contracts/services/Service'; import { DomainError, Service } from '@/lib/contracts/services/Service';
import { SponsorsApiClient } from '@/lib/api/sponsors/SponsorsApiClient';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
import { getWebsiteServerEnv } from '@/lib/config/env';
import type { SponsorDashboardDTO } from '@/lib/types/generated/SponsorDashboardDTO';
import type { SponsorSponsorshipsDTO } from '@/lib/types/generated/SponsorSponsorshipsDTO';
import type { GetSponsorOutputDTO } from '@/lib/types/generated/GetSponsorOutputDTO';
import type { GetPendingSponsorshipRequestsOutputDTO } from '@/lib/types/generated/GetPendingSponsorshipRequestsOutputDTO';
import type { SponsorBillingDTO } from '@/lib/types/tbd/SponsorBillingDTO';
import type { AvailableLeaguesDTO } from '@/lib/types/tbd/AvailableLeaguesDTO';
import type { LeagueDetailForSponsorDTO } from '@/lib/types/tbd/LeagueDetailForSponsorDTO';
import type { SponsorSettingsDTO } from '@/lib/types/tbd/SponsorSettingsDTO';
/** /**
* Sponsor Service - DTO Only * Sponsor Service - DTO Only
@@ -7,100 +20,96 @@ import { DomainError } from '@/lib/contracts/services/Service';
* Returns raw API DTOs. No ViewModels or UX logic. * Returns raw API DTOs. No ViewModels or UX logic.
* All client-side presentation logic must be handled by hooks/components. * All client-side presentation logic must be handled by hooks/components.
*/ */
export class SponsorService { export class SponsorService implements Service {
constructor(private readonly apiClient: any) {} private apiClient: SponsorsApiClient;
async getSponsorById(sponsorId: string): Promise<Result<any, DomainError>> { constructor() {
const baseUrl = getWebsiteApiBaseUrl();
const logger = new ConsoleLogger();
const { NODE_ENV } = getWebsiteServerEnv();
const errorReporter = new EnhancedErrorReporter(logger, {
showUserNotifications: true,
logToConsole: true,
reportToExternal: NODE_ENV === 'production',
});
this.apiClient = new SponsorsApiClient(baseUrl, errorReporter, logger);
}
async getSponsorById(sponsorId: string): Promise<Result<GetSponsorOutputDTO, DomainError>> {
try { try {
const result = await this.apiClient.getSponsor(sponsorId); const result = await this.apiClient.getSponsor(sponsorId);
if (!result) {
return Result.err({ type: 'notFound', message: 'Sponsor not found' });
}
return Result.ok(result); return Result.ok(result);
} catch (error) { } catch (error) {
return Result.err({ type: 'notImplemented', message: 'getSponsorById' }); return Result.err({ type: 'unknown', message: 'Failed to get sponsor' });
} }
} }
async getSponsorDashboard(sponsorId: string): Promise<Result<any, DomainError>> { async getSponsorDashboard(sponsorId: string): Promise<Result<SponsorDashboardDTO, DomainError>> {
try { try {
const result = await this.apiClient.getDashboard(sponsorId); const result = await this.apiClient.getDashboard(sponsorId);
if (!result) {
return Result.err({ type: 'notFound', message: 'Dashboard not found' });
}
return Result.ok(result); return Result.ok(result);
} catch (error) { } catch (error) {
return Result.err({ type: 'notImplemented', message: 'getSponsorDashboard' }); return Result.err({ type: 'notImplemented', message: 'getSponsorDashboard' });
} }
} }
async getSponsorSponsorships(sponsorId: string): Promise<Result<any, DomainError>> { async getSponsorSponsorships(sponsorId: string): Promise<Result<SponsorSponsorshipsDTO, DomainError>> {
try { try {
const result = await this.apiClient.getSponsorships(sponsorId); const result = await this.apiClient.getSponsorships(sponsorId);
if (!result) {
return Result.err({ type: 'notFound', message: 'Sponsorships not found' });
}
return Result.ok(result); return Result.ok(result);
} catch (error) { } catch (error) {
return Result.err({ type: 'notImplemented', message: 'getSponsorSponsorships' }); return Result.err({ type: 'notImplemented', message: 'getSponsorSponsorships' });
} }
} }
async getBilling(sponsorId: string): Promise<Result<any, DomainError>> { async getBilling(): Promise<Result<SponsorBillingDTO, DomainError>> {
try { return Result.err({ type: 'notImplemented', message: 'getBilling' });
const result = await this.apiClient.getBilling(sponsorId);
return Result.ok(result);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'getBilling' });
}
} }
async getAvailableLeagues(): Promise<Result<any, DomainError>> { async getAvailableLeagues(): Promise<Result<AvailableLeaguesDTO, DomainError>> {
try { return Result.err({ type: 'notImplemented', message: 'getAvailableLeagues' });
const result = await this.apiClient.getAvailableLeagues();
return Result.ok(result);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'getAvailableLeagues' });
}
} }
async getLeagueDetail(leagueId: string): Promise<Result<any, DomainError>> { async getLeagueDetail(): Promise<Result<LeagueDetailForSponsorDTO, DomainError>> {
try { return Result.err({ type: 'notImplemented', message: 'getLeagueDetail' });
const result = await this.apiClient.getLeagueDetail(leagueId);
return Result.ok(result);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'getLeagueDetail' });
}
} }
async getSettings(sponsorId: string): Promise<Result<any, DomainError>> { async getSettings(): Promise<Result<SponsorSettingsDTO, DomainError>> {
try { return Result.err({ type: 'notImplemented', message: 'getSettings' });
const result = await this.apiClient.getSettings(sponsorId);
return Result.ok(result);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'getSettings' });
}
} }
async updateSettings(sponsorId: string, input: any): Promise<Result<void, DomainError>> { async updateSettings(): Promise<Result<void, DomainError>> {
try { return Result.err({ type: 'notImplemented', message: 'updateSettings' });
await this.apiClient.updateSettings(sponsorId, input);
return Result.ok(undefined);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'updateSettings' });
}
} }
async acceptSponsorshipRequest(requestId: string, sponsorId: string): Promise<Result<void, DomainError>> { async acceptSponsorshipRequest(requestId: string, sponsorId: string): Promise<Result<void, DomainError>> {
try { try {
await this.apiClient.acceptSponsorshipRequest(requestId, sponsorId); await this.apiClient.acceptSponsorshipRequest(requestId, { respondedBy: sponsorId });
return Result.ok(undefined); return Result.ok(undefined);
} catch (error) { } catch (error) {
return Result.err({ type: 'notImplemented', message: 'acceptSponsorshipRequest' }); return Result.err({ type: 'unknown', message: 'Failed to accept sponsorship request' });
} }
} }
async rejectSponsorshipRequest(requestId: string, sponsorId: string, reason?: string): Promise<Result<void, DomainError>> { async rejectSponsorshipRequest(requestId: string, sponsorId: string, reason?: string): Promise<Result<void, DomainError>> {
try { try {
await this.apiClient.rejectSponsorshipRequest(requestId, sponsorId, reason); await this.apiClient.rejectSponsorshipRequest(requestId, { respondedBy: sponsorId, reason });
return Result.ok(undefined); return Result.ok(undefined);
} catch (error) { } catch (error) {
return Result.err({ type: 'notImplemented', message: 'rejectSponsorshipRequest' }); return Result.err({ type: 'unknown', message: 'Failed to reject sponsorship request' });
} }
} }
async getPendingSponsorshipRequests(input: any): Promise<Result<any, DomainError>> { async getPendingSponsorshipRequests(input: { entityType: string; entityId: string }): Promise<Result<GetPendingSponsorshipRequestsOutputDTO, DomainError>> {
try { try {
const result = await this.apiClient.getPendingSponsorshipRequests(input); const result = await this.apiClient.getPendingSponsorshipRequests(input);
return Result.ok(result); return Result.ok(result);

View File

@@ -27,10 +27,10 @@ export class TeamService implements Service {
this.apiClient = new TeamsApiClient(baseUrl, errorReporter, logger); this.apiClient = new TeamsApiClient(baseUrl, errorReporter, logger);
} }
async getAllTeams(): Promise<Result<TeamSummaryViewModel[], DomainError>> { async getAllTeams(): Promise<Result<TeamListItemDTO[], DomainError>> {
try { try {
const result = await this.apiClient.getAll(); const result = await this.apiClient.getAll();
return Result.ok(result.teams.map(team => new TeamSummaryViewModel(team))); return Result.ok(result.teams);
} catch (error) { } catch (error) {
return Result.err({ type: 'unknown', message: 'Failed to fetch teams' }); return Result.err({ type: 'unknown', message: 'Failed to fetch teams' });
} }

View File

@@ -0,0 +1,6 @@
import type { DriverLeaderboardItemDTO } from '@/lib/types/generated/DriverLeaderboardItemDTO';
export interface LeaderboardsData {
drivers: { drivers: DriverLeaderboardItemDTO[] };
teams: { teams: [] };
}

View File

@@ -0,0 +1,7 @@
// Re-export TBD DTOs for admin functionality
export type {
AdminUserDto as UserDto,
AdminUserListResponseDto as UserListResponse,
AdminListUsersQueryDto as ListUsersQuery,
AdminDashboardStatsDto as DashboardStats,
} from './tbd/AdminUserDto';

View File

@@ -0,0 +1,76 @@
/**
* AdminUserDto - TBD DTO for admin user data
*
* This DTO represents the shape of user data returned by admin endpoints.
* TODO: Generate this from API OpenAPI spec when admin endpoints are implemented.
*/
export interface AdminUserDto {
id: string;
email: string;
displayName: string;
roles: string[];
status: string;
isSystemAdmin: boolean;
createdAt: string; // ISO date string
updatedAt: string; // ISO date string
lastLoginAt?: string; // ISO date string
primaryDriverId?: string;
}
/**
* AdminUserListResponseDto - TBD DTO for user list response
*/
export interface AdminUserListResponseDto {
users: AdminUserDto[];
total: number;
page: number;
limit: number;
totalPages: number;
}
/**
* AdminDashboardStatsDto - TBD DTO for dashboard statistics
*/
export interface AdminDashboardStatsDto {
totalUsers: number;
activeUsers: number;
suspendedUsers: number;
deletedUsers: number;
systemAdmins: number;
recentLogins: number;
newUsersToday: number;
userGrowth: {
label: string;
value: number;
color: string;
}[];
roleDistribution: {
label: string;
value: number;
color: string;
}[];
statusDistribution: {
active: number;
suspended: number;
deleted: number;
};
activityTimeline: {
date: string;
newUsers: number;
logins: number;
}[];
}
/**
* AdminListUsersQueryDto - TBD DTO for user list query parameters
*/
export interface AdminListUsersQueryDto {
role?: string;
status?: string;
email?: string;
search?: string;
page?: number;
limit?: number;
sortBy?: 'email' | 'displayName' | 'createdAt' | 'lastLoginAt' | 'status';
sortDirection?: 'asc' | 'desc';
}

View File

@@ -0,0 +1,23 @@
export interface AvailableLeaguesDTO {
leagues: AvailableLeagueDTO[];
}
export interface AvailableLeagueDTO {
id: string;
name: string;
description: string;
drivers: number;
mainSponsorSlot: {
available: boolean;
price: number;
};
secondarySlots: {
available: number;
price: number;
};
cpm: number;
season: {
startDate: string;
endDate: string;
};
}

View File

@@ -0,0 +1,34 @@
/**
* Filtered Races Page Data DTO
*
* API response for filtered races page data with status, time, and league filters.
* Used when the API supports filtering parameters.
*/
export interface FilteredRacesPageDataDTO {
races: FilteredRacesPageDataRaceDTO[];
totalCount: number;
scheduledRaces: FilteredRacesPageDataRaceDTO[];
runningRaces: FilteredRacesPageDataRaceDTO[];
completedRaces: FilteredRacesPageDataRaceDTO[];
filters: {
statuses: { value: string; label: string }[];
leagues: { id: string; name: string }[];
timeFilters: { value: string; label: string }[];
};
}
export interface FilteredRacesPageDataRaceDTO {
id: string;
track: string;
car: string;
scheduledAt: string;
status: 'scheduled' | 'running' | 'completed' | 'cancelled';
sessionType: string;
leagueId?: string;
leagueName?: string;
strengthOfField?: number;
isUpcoming: boolean;
isLive: boolean;
isPast: boolean;
}

View File

@@ -0,0 +1,9 @@
export interface GetLiveriesOutputDTO {
liveries: Array<{
id: string;
name: string;
imageUrl: string;
createdAt: string;
isActive: boolean;
}>;
}

View File

@@ -0,0 +1,41 @@
export interface LeagueDetailForSponsorDTO {
league: LeagueDetailDTO;
drivers: SponsorDriverDTO[];
races: SponsorRaceDTO[];
}
export interface LeagueDetailDTO {
id: string;
name: string;
description: string;
drivers: number;
mainSponsorSlot: {
available: boolean;
price: number;
};
secondarySlots: {
available: number;
price: number;
};
cpm: number;
season: {
startDate: string;
endDate: string;
};
}
export interface SponsorDriverDTO {
id: string;
name: string;
rating: number;
car: string;
sponsorshipPrice: number;
}
export interface SponsorRaceDTO {
id: string;
name: string;
date: string;
track: string;
sponsorshipPrice: number;
}

View File

@@ -0,0 +1,40 @@
export interface SponsorBillingDTO {
sponsorId: string;
paymentMethods: PaymentMethodDTO[];
invoices: InvoiceDTO[];
stats: BillingStatsDTO;
}
export interface PaymentMethodDTO {
id: string;
type: 'card' | 'bank' | 'sepa';
last4: string;
brand?: string;
isDefault: boolean;
expiryMonth?: number;
expiryYear?: number;
bankName?: string;
}
export interface InvoiceDTO {
id: string;
invoiceNumber: string;
date: string;
dueDate: string;
amount: number;
vatAmount: number;
totalAmount: number;
status: 'paid' | 'pending' | 'overdue' | 'failed';
description: string;
sponsorshipType: 'league' | 'team' | 'driver' | 'race' | 'platform';
pdfUrl: string;
}
export interface BillingStatsDTO {
totalSpent: number;
pendingAmount: number;
nextPaymentDate: string;
nextPaymentAmount: number;
activeSponsorships: number;
averageMonthlySpend: number;
}

View File

@@ -0,0 +1,36 @@
export interface SponsorSettingsDTO {
profile: SponsorProfileDTO;
notifications: NotificationSettingsDTO;
}
export interface SponsorProfileDTO {
companyName: string;
contactName: string;
contactEmail: string;
contactPhone: string;
website: string;
description: string;
logoUrl: string | null;
industry: string;
address: {
street: string;
city: string;
country: string;
postalCode: string;
};
taxId: string;
socialLinks: {
twitter: string;
linkedin: string;
instagram: string;
};
}
export interface NotificationSettingsDTO {
emailNewSponsorships: boolean;
emailWeeklyReport: boolean;
emailRaceAlerts: boolean;
emailPaymentAlerts: boolean;
emailNewOpportunities: boolean;
emailContractExpiry: boolean;
}

View File

@@ -0,0 +1,14 @@
export interface TeamsLeaderboardItemDTO {
id: string;
name: string;
tag: string;
memberCount: number;
category?: string;
totalWins: number;
logoUrl?: string;
rank: number;
}
export interface TeamsLeaderboardDto {
teams: TeamsLeaderboardItemDTO[];
}

View File

@@ -0,0 +1,19 @@
export interface DriversViewData {
drivers: {
id: string;
name: string;
rating: number;
skillLevel: string;
category?: string;
nationality: string;
racesCompleted: number;
wins: number;
podiums: number;
isActive: boolean;
rank: number;
avatarUrl?: string;
}[];
totalRaces: number;
totalWins: number;
activeCount: number;
}

View File

@@ -0,0 +1,146 @@
/**
* Auth Validation Utilities
*
* Pure functions for client-side validation of auth forms.
* No side effects, synchronous.
*/
export interface SignupFormData {
firstName: string;
lastName: string;
email: string;
password: string;
confirmPassword: string;
}
export interface ForgotPasswordFormData {
email: string;
}
export interface ResetPasswordFormData {
newPassword: string;
confirmPassword: string;
}
export interface SignupValidationError {
field: keyof SignupFormData;
message: string;
}
export interface ForgotPasswordValidationError {
field: keyof ForgotPasswordFormData;
message: string;
}
export interface ResetPasswordValidationError {
field: keyof ResetPasswordFormData;
message: string;
}
export class SignupFormValidation {
static validateForm(data: SignupFormData): SignupValidationError[] {
const errors: SignupValidationError[] = [];
// First name
if (!data.firstName.trim()) {
errors.push({ field: 'firstName', message: 'First name is required' });
} else if (data.firstName.trim().length < 2) {
errors.push({ field: 'firstName', message: 'First name must be at least 2 characters' });
}
// Last name
if (!data.lastName.trim()) {
errors.push({ field: 'lastName', message: 'Last name is required' });
} else if (data.lastName.trim().length < 2) {
errors.push({ field: 'lastName', message: 'Last name must be at least 2 characters' });
}
// Email
if (!data.email.trim()) {
errors.push({ field: 'email', message: 'Email is required' });
} else if (!this.isValidEmail(data.email)) {
errors.push({ field: 'email', message: 'Please enter a valid email address' });
}
// Password
if (!data.password) {
errors.push({ field: 'password', message: 'Password is required' });
} else if (data.password.length < 8) {
errors.push({ field: 'password', message: 'Password must be at least 8 characters' });
} else if (!this.hasValidPasswordComplexity(data.password)) {
errors.push({ field: 'password', message: 'Password must contain at least one uppercase letter, one lowercase letter, and one number' });
}
// Confirm password
if (!data.confirmPassword) {
errors.push({ field: 'confirmPassword', message: 'Please confirm your password' });
} else if (data.password !== data.confirmPassword) {
errors.push({ field: 'confirmPassword', message: 'Passwords do not match' });
}
return errors;
}
static generateDisplayName(firstName: string, lastName: string): string {
const trimmedFirst = firstName.trim();
const trimmedLast = lastName.trim();
return `${trimmedFirst} ${trimmedLast}`.trim() || trimmedFirst || trimmedLast;
}
private static isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
private static hasValidPasswordComplexity(password: string): boolean {
return /[a-z]/.test(password) && /[A-Z]/.test(password) && /\d/.test(password);
}
}
export class ForgotPasswordFormValidation {
static validateForm(data: ForgotPasswordFormData): ForgotPasswordValidationError[] {
const errors: ForgotPasswordValidationError[] = [];
// Email
if (!data.email.trim()) {
errors.push({ field: 'email', message: 'Email is required' });
} else if (!this.isValidEmail(data.email)) {
errors.push({ field: 'email', message: 'Please enter a valid email address' });
}
return errors;
}
private static isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
}
export class ResetPasswordFormValidation {
static validateForm(data: ResetPasswordFormData): ResetPasswordValidationError[] {
const errors: ResetPasswordValidationError[] = [];
// New password
if (!data.newPassword) {
errors.push({ field: 'newPassword', message: 'New password is required' });
} else if (data.newPassword.length < 8) {
errors.push({ field: 'newPassword', message: 'Password must be at least 8 characters' });
} else if (!this.hasValidPasswordComplexity(data.newPassword)) {
errors.push({ field: 'newPassword', message: 'Password must contain at least one uppercase letter, one lowercase letter, and one number' });
}
// Confirm password
if (!data.confirmPassword) {
errors.push({ field: 'confirmPassword', message: 'Please confirm your new password' });
} else if (data.newPassword !== data.confirmPassword) {
errors.push({ field: 'confirmPassword', message: 'Passwords do not match' });
}
return errors;
}
private static hasValidPasswordComplexity(password: string): boolean {
return /[a-z]/.test(password) && /[A-Z]/.test(password) && /\d/.test(password);
}
}

View File

@@ -4,6 +4,6 @@
* ViewData for avatar media rendering. * ViewData for avatar media rendering.
*/ */
export interface AvatarViewData { export interface AvatarViewData {
buffer: ArrayBuffer; buffer: string; // base64 encoded
contentType: string; contentType: string;
} }

View File

@@ -4,6 +4,6 @@
* ViewData for category icon media rendering. * ViewData for category icon media rendering.
*/ */
export interface CategoryIconViewData { export interface CategoryIconViewData {
buffer: ArrayBuffer; buffer: string; // base64 encoded
contentType: string; contentType: string;
} }

View File

@@ -4,6 +4,6 @@
* ViewData for league cover media rendering. * ViewData for league cover media rendering.
*/ */
export interface LeagueCoverViewData { export interface LeagueCoverViewData {
buffer: ArrayBuffer; buffer: string; // base64 encoded
contentType: string; contentType: string;
} }

View File

@@ -4,6 +4,6 @@
* ViewData for league logo media rendering. * ViewData for league logo media rendering.
*/ */
export interface LeagueLogoViewData { export interface LeagueLogoViewData {
buffer: ArrayBuffer; buffer: string; // base64 encoded
contentType: string; contentType: string;
} }

View File

@@ -0,0 +1,23 @@
export interface SponsorDashboardViewData {
sponsorName: string;
totalImpressions: string;
totalInvestment: string;
metrics: {
impressionsChange: number;
viewersChange: number;
exposureChange: number;
};
categoryData: {
leagues: { count: number; impressions: number };
teams: { count: number; impressions: number };
drivers: { count: number; impressions: number };
races: { count: number; impressions: number };
platform: { count: number; impressions: number };
};
sponsorships: Record<string, unknown>; // From DTO
activeSponsorships: number;
formattedTotalInvestment: string;
costPerThousandViews: string;
upcomingRenewals: any[];
recentActivity: any[];
}

View File

@@ -4,6 +4,6 @@
* ViewData for sponsor logo media rendering. * ViewData for sponsor logo media rendering.
*/ */
export interface SponsorLogoViewData { export interface SponsorLogoViewData {
buffer: ArrayBuffer; buffer: string; // base64 encoded
contentType: string; contentType: string;
} }

View File

@@ -4,6 +4,6 @@
* ViewData for team logo media rendering. * ViewData for team logo media rendering.
*/ */
export interface TeamLogoViewData { export interface TeamLogoViewData {
buffer: ArrayBuffer; buffer: string; // base64 encoded
contentType: string; contentType: string;
} }

View File

@@ -4,6 +4,6 @@
* ViewData for track image media rendering. * ViewData for track image media rendering.
*/ */
export interface TrackImageViewData { export interface TrackImageViewData {
buffer: ArrayBuffer; buffer: string; // base64 encoded
contentType: string; contentType: string;
} }

View File

@@ -1,4 +1,4 @@
import type { UserDto } from '@/lib/api/admin/AdminApiClient'; import type { UserDto } from '@/lib/types/admin';
/** /**
* AdminUserViewModel * AdminUserViewModel

View File

@@ -1,47 +0,0 @@
'use client';
import type { UserDto, DashboardStats, UserListResponse } from '@/lib/api/admin/AdminApiClient';
import { AdminUserViewModel, DashboardStatsViewModel, UserListViewModel } from './AdminUserViewModel';
/**
* AdminViewModelPresenter
*
* Presenter layer for transforming API DTOs to ViewModels.
* Runs in client code only ('use client').
* Deterministic, side-effect free transformations.
*/
export class AdminViewModelPresenter {
/**
* Map a single user DTO to a View Model
*/
static mapUser(apiDto: UserDto): AdminUserViewModel {
return new AdminUserViewModel(apiDto);
}
/**
* Map an array of user DTOs to View Models
*/
static mapUsers(apiDtos: UserDto[]): AdminUserViewModel[] {
return apiDtos.map(apiDto => this.mapUser(apiDto));
}
/**
* Map dashboard stats DTO to View Model
*/
static mapDashboardStats(apiDto: DashboardStats): DashboardStatsViewModel {
return new DashboardStatsViewModel(apiDto);
}
/**
* Map user list response to View Model
*/
static mapUserList(viewData: UserListResponse): UserListViewModel {
return new UserListViewModel({
users: viewData.users,
total: viewData.total,
page: viewData.page,
limit: viewData.limit,
totalPages: viewData.totalPages,
});
}
}

View File

@@ -1,105 +0,0 @@
import type { LeagueMembershipsViewModel } from './LeagueMembershipsViewModel';
import type { RaceResultsDetailViewModel } from './RaceResultsDetailViewModel';
import type { RaceWithSOFViewModel } from './RaceWithSOFViewModel';
// TODO fucking violating our architecture, it should be a ViewModel
export interface TransformedRaceResultsData {
raceTrack?: string;
raceScheduledAt?: string;
totalDrivers?: number;
leagueName?: string;
raceSOF: number | null;
results: Array<{
position: number;
driverId: string;
driverName: string;
driverAvatar: string;
country: string;
car: string;
laps: number;
time: string;
fastestLap: string;
points: number;
incidents: number;
isCurrentUser: boolean;
}>;
penalties: Array<{
driverId: string;
driverName: string;
type: 'time_penalty' | 'grid_penalty' | 'points_deduction' | 'disqualification' | 'warning' | 'license_points';
value: number;
reason: string;
notes?: string;
}>;
pointsSystem: Record<string, number>;
fastestLapTime: number;
memberships?: Array<{
driverId: string;
role: string;
}>;
}
export class RaceResultsDataTransformer {
static transform(
resultsData: RaceResultsDetailViewModel | null,
sofData: RaceWithSOFViewModel | null,
currentDriverId: string,
membershipsData?: LeagueMembershipsViewModel
): TransformedRaceResultsData {
if (!resultsData) {
return {
raceSOF: null,
results: [],
penalties: [],
pointsSystem: {},
fastestLapTime: 0,
};
}
// Transform results
const results = resultsData.results.map((result) => ({
position: result.position,
driverId: result.driverId,
driverName: result.driverName,
driverAvatar: result.avatarUrl,
country: 'US', // Default since view model doesn't have car
car: 'Unknown', // Default since view model doesn't have car
laps: 0, // Default since view model doesn't have laps
time: '0:00.00', // Default since view model doesn't have time
fastestLap: result.fastestLap.toString(), // Convert number to string
points: 0, // Default since view model doesn't have points
incidents: result.incidents,
isCurrentUser: result.driverId === currentDriverId,
}));
// Transform penalties
const penalties = resultsData.penalties.map((penalty) => ({
driverId: penalty.driverId,
driverName: resultsData.results.find((r) => r.driverId === penalty.driverId)?.driverName || 'Unknown',
type: penalty.type as 'time_penalty' | 'grid_penalty' | 'points_deduction' | 'disqualification' | 'warning' | 'license_points',
value: penalty.value || 0,
reason: 'Penalty applied', // Default since view model doesn't have reason
notes: undefined, // Default since view model doesn't have notes
}));
// Transform memberships
const memberships = membershipsData?.memberships.map((membership) => ({
driverId: membership.driverId,
role: membership.role || 'member',
}));
return {
raceTrack: resultsData.race?.track,
raceScheduledAt: resultsData.race?.scheduledAt,
totalDrivers: resultsData.stats?.totalDrivers,
leagueName: resultsData.league?.name,
raceSOF: sofData?.strengthOfField || null,
results,
penalties,
pointsSystem: resultsData.pointsSystem || {},
fastestLapTime: resultsData.fastestLapTime || 0,
memberships,
};
}
}

View File

@@ -87,5 +87,3 @@ export * from './UploadMediaViewModel';
export * from './UserProfileViewModel'; export * from './UserProfileViewModel';
export * from './WalletTransactionViewModel'; export * from './WalletTransactionViewModel';
export * from './WalletViewModel'; export * from './WalletViewModel';
export * from './AdminViewModelPresenter';

View File

@@ -40,8 +40,8 @@ export function AdminDashboardTemplate(props: {
System overview and statistics System overview and statistics
</Text> </Text>
</div> </div>
<Button <Button
onClick={onRefresh} onClick={onRefresh}
disabled={isLoading} disabled={isLoading}
variant="secondary" variant="secondary"
className="flex items-center gap-2" className="flex items-center gap-2"

View File

@@ -1,9 +1,14 @@
import Card from '@/components/ui/Card'; import { Card } from '@/ui/Card';
import StatusBadge from '@/components/ui/StatusBadge'; import StatusBadge from '@/components/ui/StatusBadge';
import { import { Input } from '@/ui/Input';
Search, import { Select } from '@/ui/Select';
Filter, import { Table, TableHead, TableBody, TableRow, TableHeader, TableCell } from '@/ui/Table';
RefreshCw, import { Button } from '@/ui/Button';
import { Text } from '@/ui/Text';
import {
Search,
Filter,
RefreshCw,
Users, Users,
Shield, Shield,
Trash2, Trash2,
@@ -94,17 +99,18 @@ export function AdminUsersTemplate(props: {
{/* Header */} {/* Header */}
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<h1 className="text-2xl font-bold text-white">User Management</h1> <Text size="2xl" weight="bold" color="text-white">User Management</Text>
<p className="text-gray-400 mt-1">Manage and monitor all system users</p> <Text size="sm" color="text-gray-400" className="mt-1">Manage and monitor all system users</Text>
</div> </div>
<button <Button
onClick={onRefresh} onClick={onRefresh}
disabled={loading} disabled={loading}
className="px-4 py-2 bg-iron-gray border border-charcoal-outline rounded-lg text-white hover:bg-iron-gray/80 transition-colors flex items-center gap-2 disabled:opacity-50" variant="secondary"
className="flex items-center gap-2"
> >
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} /> <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
Refresh Refresh
</button> </Button>
</div> </div>
{/* Error Banner */} {/* Error Banner */}
@@ -112,15 +118,16 @@ export function AdminUsersTemplate(props: {
<div className="bg-racing-red/10 border border-racing-red text-racing-red px-4 py-3 rounded-lg flex items-start gap-3"> <div className="bg-racing-red/10 border border-racing-red text-racing-red px-4 py-3 rounded-lg flex items-start gap-3">
<AlertTriangle className="w-5 h-5 mt-0.5 flex-shrink-0" /> <AlertTriangle className="w-5 h-5 mt-0.5 flex-shrink-0" />
<div className="flex-1"> <div className="flex-1">
<div className="font-medium">Error</div> <Text weight="medium">Error</Text>
<div className="text-sm opacity-90">{error}</div> <Text size="sm" className="opacity-90">{error}</Text>
</div> </div>
<button <Button
onClick={() => {}} onClick={() => {}}
className="text-racing-red hover:opacity-70" variant="secondary"
className="text-racing-red hover:opacity-70 p-0"
> >
× ×
</button> </Button>
</div> </div>
)} )}
@@ -130,52 +137,53 @@ export function AdminUsersTemplate(props: {
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Filter className="w-4 h-4 text-gray-400" /> <Filter className="w-4 h-4 text-gray-400" />
<span className="font-medium text-white">Filters</span> <Text weight="medium" color="text-white">Filters</Text>
</div> </div>
{(search || roleFilter || statusFilter) && ( {(search || roleFilter || statusFilter) && (
<button <Button
onClick={onClearFilters} onClick={onClearFilters}
className="text-xs text-primary-blue hover:text-blue-400" variant="secondary"
className="text-xs p-0"
> >
Clear all Clear all
</button> </Button>
)} )}
</div> </div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4"> <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="relative"> <div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<input <Input
type="text" type="text"
placeholder="Search by email or name..." placeholder="Search by email or name..."
value={search} value={search}
onChange={(e) => onSearch(e.target.value)} onChange={(e) => onSearch(e.target.value)}
className="w-full pl-9 pr-3 py-2 bg-deep-graphite border border-charcoal-outline rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-primary-blue transition-colors" className="pl-9"
/> />
</div> </div>
<select <Select
value={roleFilter} value={roleFilter}
onChange={(e) => onFilterRole(e.target.value)} onChange={(e) => onFilterRole(e.target.value)}
className="w-full px-3 py-2 bg-deep-graphite border border-charcoal-outline rounded-lg text-white focus:outline-none focus:border-primary-blue transition-colors" options={[
> { value: '', label: 'All Roles' },
<option value="">All Roles</option> { value: 'owner', label: 'Owner' },
<option value="owner">Owner</option> { value: 'admin', label: 'Admin' },
<option value="admin">Admin</option> { value: 'user', label: 'User' },
<option value="user">User</option> ]}
</select> />
<select <Select
value={statusFilter} value={statusFilter}
onChange={(e) => onFilterStatus(e.target.value)} onChange={(e) => onFilterStatus(e.target.value)}
className="w-full px-3 py-2 bg-deep-graphite border border-charcoal-outline rounded-lg text-white focus:outline-none focus:border-primary-blue transition-colors" options={[
> { value: '', label: 'All Status' },
<option value="">All Status</option> { value: 'active', label: 'Active' },
<option value="active">Active</option> { value: 'suspended', label: 'Suspended' },
<option value="suspended">Suspended</option> { value: 'deleted', label: 'Deleted' },
<option value="deleted">Deleted</option> ]}
</select> />
</div> </div>
</div> </div>
</Card> </Card>
@@ -184,113 +192,115 @@ export function AdminUsersTemplate(props: {
{loading ? ( {loading ? (
<div className="flex flex-col items-center justify-center py-12 space-y-3"> <div className="flex flex-col items-center justify-center py-12 space-y-3">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-blue"></div> <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-blue"></div>
<div className="text-gray-400">Loading users...</div> <Text color="text-gray-400">Loading users...</Text>
</div> </div>
) : !viewData.users || viewData.users.length === 0 ? ( ) : !viewData.users || viewData.users.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 space-y-3"> <div className="flex flex-col items-center justify-center py-12 space-y-3">
<Users className="w-12 h-12 text-gray-600" /> <Users className="w-12 h-12 text-gray-600" />
<div className="text-gray-400">No users found</div> <Text color="text-gray-400">No users found</Text>
<button <Button
onClick={onClearFilters} onClick={onClearFilters}
className="text-primary-blue hover:text-blue-400 text-sm" variant="secondary"
className="text-sm p-0"
> >
Clear filters Clear filters
</button> </Button>
</div> </div>
) : ( ) : (
<div className="overflow-x-auto"> <Table>
<table className="w-full"> <TableHead>
<thead> <TableRow>
<tr className="border-b border-charcoal-outline"> <TableHeader>User</TableHeader>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">User</th> <TableHeader>Email</TableHeader>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">Email</th> <TableHeader>Roles</TableHeader>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">Roles</th> <TableHeader>Status</TableHeader>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">Status</th> <TableHeader>Last Login</TableHeader>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">Last Login</th> <TableHeader>Actions</TableHeader>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">Actions</th> </TableRow>
</tr> </TableHead>
</thead> <TableBody>
<tbody> {viewData.users.map((user, index: number) => (
{viewData.users.map((user, index: number) => ( <TableRow
<tr key={user.id}
key={user.id} className={index % 2 === 0 ? 'bg-transparent' : 'bg-iron-gray/10'}
className={`border-b border-charcoal-outline/50 hover:bg-iron-gray/30 transition-colors ${index % 2 === 0 ? 'bg-transparent' : 'bg-iron-gray/10'}`} >
> <TableCell>
<td className="py-3 px-4"> <div className="flex items-center gap-3">
<div className="flex items-center gap-3"> <div className="w-8 h-8 rounded-full bg-primary-blue/20 flex items-center justify-center">
<div className="w-8 h-8 rounded-full bg-primary-blue/20 flex items-center justify-center"> <Shield className="w-4 h-4 text-primary-blue" />
<Shield className="w-4 h-4 text-primary-blue" />
</div>
<div>
<div className="font-medium text-white">{user.displayName}</div>
<div className="text-xs text-gray-500">ID: {user.id}</div>
{user.primaryDriverId && (
<div className="text-xs text-gray-500">Driver: {user.primaryDriverId}</div>
)}
</div>
</div> </div>
</td> <div>
<td className="py-3 px-4"> <div className="font-medium text-white">{user.displayName}</div>
<div className="text-sm text-gray-300">{user.email}</div> <div className="text-xs text-gray-500">ID: {user.id}</div>
</td> {user.primaryDriverId && (
<td className="py-3 px-4"> <div className="text-xs text-gray-500">Driver: {user.primaryDriverId}</div>
<div className="flex flex-wrap gap-1">
{user.roles.map((role: string, idx: number) => (
<span
key={idx}
className={`px-2 py-1 text-xs rounded-full font-medium ${getRoleBadgeClass(role)}`}
>
{getRoleBadgeLabel(role)}
</span>
))}
</div>
</td>
<td className="py-3 px-4">
{(() => {
const badge = toStatusBadgeProps(user.status);
return <StatusBadge status={badge.status} label={badge.label} />;
})()}
</td>
<td className="py-3 px-4">
<div className="text-sm text-gray-400">
{user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleDateString() : 'Never'}
</div>
</td>
<td className="py-3 px-4">
<div className="flex items-center gap-2">
{user.status === 'active' && (
<button
onClick={() => onUpdateStatus(user.id, 'suspended')}
className="px-3 py-1 text-xs rounded bg-yellow-500/20 text-yellow-300 hover:bg-yellow-500/30 transition-colors"
>
Suspend
</button>
)}
{user.status === 'suspended' && (
<button
onClick={() => onUpdateStatus(user.id, 'active')}
className="px-3 py-1 text-xs rounded bg-performance-green/20 text-performance-green hover:bg-performance-green/30 transition-colors"
>
Activate
</button>
)}
{user.status !== 'deleted' && (
<button
onClick={() => onDeleteUser(user.id)}
disabled={deletingUser === user.id}
className="px-3 py-1 text-xs rounded bg-racing-red/20 text-racing-red hover:bg-racing-red/30 transition-colors flex items-center gap-1"
>
<Trash2 className="w-3 h-3" />
{deletingUser === user.id ? 'Deleting...' : 'Delete'}
</button>
)} )}
</div> </div>
</td> </div>
</tr> </TableCell>
))} <TableCell>
</tbody> <div className="text-sm text-gray-300">{user.email}</div>
</table> </TableCell>
</div> <TableCell>
<div className="flex flex-wrap gap-1">
{user.roles.map((role: string, idx: number) => (
<span
key={idx}
className={`px-2 py-1 text-xs rounded-full font-medium ${getRoleBadgeClass(role)}`}
>
{getRoleBadgeLabel(role)}
</span>
))}
</div>
</TableCell>
<TableCell>
{(() => {
const badge = toStatusBadgeProps(user.status);
return <StatusBadge status={badge.status} label={badge.label} />;
})()}
</TableCell>
<TableCell>
<div className="text-sm text-gray-400">
{user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleDateString() : 'Never'}
</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-2">
{user.status === 'active' && (
<Button
onClick={() => onUpdateStatus(user.id, 'suspended')}
variant="secondary"
className="px-3 py-1 text-xs bg-yellow-500/20 text-yellow-300 hover:bg-yellow-500/30"
>
Suspend
</Button>
)}
{user.status === 'suspended' && (
<Button
onClick={() => onUpdateStatus(user.id, 'active')}
variant="secondary"
className="px-3 py-1 text-xs bg-performance-green/20 text-performance-green hover:bg-performance-green/30"
>
Activate
</Button>
)}
{user.status !== 'deleted' && (
<Button
onClick={() => onDeleteUser(user.id)}
disabled={deletingUser === user.id}
variant="secondary"
className="px-3 py-1 text-xs bg-racing-red/20 text-racing-red hover:bg-racing-red/30 flex items-center gap-1"
>
<Trash2 className="w-3 h-3" />
{deletingUser === user.id ? 'Deleting...' : 'Delete'}
</Button>
)}
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)} )}
</Card> </Card>
@@ -300,8 +310,8 @@ export function AdminUsersTemplate(props: {
<Card className="bg-gradient-to-br from-blue-900/20 to-blue-700/10"> <Card className="bg-gradient-to-br from-blue-900/20 to-blue-700/10">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<div className="text-sm text-gray-400 mb-1">Total Users</div> <Text size="sm" color="text-gray-400" className="mb-1">Total Users</Text>
<div className="text-2xl font-bold text-white">{viewData.total}</div> <Text size="2xl" weight="bold" color="text-white">{viewData.total}</Text>
</div> </div>
<Users className="w-6 h-6 text-blue-400" /> <Users className="w-6 h-6 text-blue-400" />
</div> </div>
@@ -309,10 +319,10 @@ export function AdminUsersTemplate(props: {
<Card className="bg-gradient-to-br from-green-900/20 to-green-700/10"> <Card className="bg-gradient-to-br from-green-900/20 to-green-700/10">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<div className="text-sm text-gray-400 mb-1">Active</div> <Text size="sm" color="text-gray-400" className="mb-1">Active</Text>
<div className="text-2xl font-bold text-white"> <Text size="2xl" weight="bold" color="text-white">
{viewData.activeUserCount} {viewData.activeUserCount}
</div> </Text>
</div> </div>
<div className="w-6 h-6 text-green-400"></div> <div className="w-6 h-6 text-green-400"></div>
</div> </div>
@@ -320,10 +330,10 @@ export function AdminUsersTemplate(props: {
<Card className="bg-gradient-to-br from-purple-900/20 to-purple-700/10"> <Card className="bg-gradient-to-br from-purple-900/20 to-purple-700/10">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<div className="text-sm text-gray-400 mb-1">Admins</div> <Text size="sm" color="text-gray-400" className="mb-1">Admins</Text>
<div className="text-2xl font-bold text-white"> <Text size="2xl" weight="bold" color="text-white">
{viewData.adminCount} {viewData.adminCount}
</div> </Text>
</div> </div>
<Shield className="w-6 h-6 text-purple-400" /> <Shield className="w-6 h-6 text-purple-400" />
</div> </div>

View File

@@ -1,4 +1,18 @@
import type { DashboardViewData } from '@/lib/view-data/DashboardViewData'; import type { DashboardViewData } from '@/lib/view-data/DashboardViewData';
import {
Trophy,
Medal,
Target,
Users,
ChevronRight,
Calendar,
Clock,
Activity,
Award,
UserPlus,
Flag,
User,
} from 'lucide-react';
interface DashboardTemplateProps { interface DashboardTemplateProps {
viewData: DashboardViewData; viewData: DashboardViewData;
@@ -72,7 +86,7 @@ export function DashboardTemplate({ viewData }: DashboardTemplateProps) {
<span>Flag</span> <span>Flag</span>
Browse Leagues Browse Leagues
</a> </a>
<a href="/profile" className="px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-lg text-white text-sm font-medium transition-colors flex items-center gap-2"> <a href=routes.protected.profile className="px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-lg text-white text-sm font-medium transition-colors flex items-center gap-2">
<span>Activity</span> <span>Activity</span>
View Profile View Profile
</a> </a>
@@ -189,7 +203,7 @@ export function DashboardTemplate({ viewData }: DashboardTemplateProps) {
<span>Award</span> <span>Award</span>
Your Championship Standings Your Championship Standings
</h2> </h2>
<a href="/profile/leagues" className="text-sm text-primary-blue hover:underline flex items-center gap-1"> <a href=routes.protected.profileLeagues className="text-sm text-primary-blue hover:underline flex items-center gap-1">
View all <span>ChevronRight</span> View all <span>ChevronRight</span>
</a> </a>
</div> </div>
@@ -307,7 +321,7 @@ export function DashboardTemplate({ viewData }: DashboardTemplateProps) {
))} ))}
{friends.length > 6 && ( {friends.length > 6 && (
<a <a
href="/profile" href=routes.protected.profile
className="block text-center py-2 text-sm text-primary-blue hover:underline" className="block text-center py-2 text-sm text-primary-blue hover:underline"
> >
+{friends.length - 6} more +{friends.length - 6} more

View File

@@ -95,7 +95,7 @@ export function DriverRankingsTemplate({
</p> </p>
<p className={`font-mono font-bold ${position === 1 ? 'text-xl text-yellow-400' : 'text-lg text-primary-blue'}`}> <p className={`font-mono font-bold ${position === 1 ? 'text-xl text-yellow-400' : 'text-lg text-primary-blue'}`}>
{driver.rating.toLocaleString()} {driver.rating.toString()}
</p> </p>
<div className="flex items-center gap-2 text-xs text-gray-500 mt-1"> <div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
@@ -139,14 +139,6 @@ export function DriverRankingsTemplate({
<div className="divide-y divide-charcoal-outline/50"> <div className="divide-y divide-charcoal-outline/50">
{viewData.drivers.map((driver) => { {viewData.drivers.map((driver) => {
const position = driver.rank; const position = driver.rank;
const medalBg = position === 1 ? 'bg-gradient-to-br from-yellow-400/20 to-yellow-600/10 border-yellow-400/40' :
position === 2 ? 'bg-gradient-to-br from-gray-300/20 to-gray-400/10 border-gray-300/40' :
position === 3 ? 'bg-gradient-to-br from-amber-600/20 to-amber-700/10 border-amber-600/40' :
'bg-iron-gray/50 border-charcoal-outline';
const medalColor = position === 1 ? 'text-yellow-400' :
position === 2 ? 'text-gray-300' :
position === 3 ? 'text-amber-600' :
'text-gray-500';
return ( return (
<button <button
@@ -157,7 +149,7 @@ export function DriverRankingsTemplate({
> >
{/* Position */} {/* Position */}
<div className="col-span-1 flex items-center justify-center"> <div className="col-span-1 flex items-center justify-center">
<div className={`flex h-9 w-9 items-center justify-center rounded-full text-sm font-bold border ${medalBg} ${medalColor}`}> <div className={`flex h-9 w-9 items-center justify-center rounded-full text-sm font-bold border ${driver.medalBg} ${driver.medalColor}`}>
{position <= 3 ? <Medal className="w-4 h-4" /> : position} {position <= 3 ? <Medal className="w-4 h-4" /> : position}
</div> </div>
</div> </div>
@@ -190,7 +182,7 @@ export function DriverRankingsTemplate({
{/* Rating */} {/* Rating */}
<div className="col-span-2 lg:col-span-1 flex items-center justify-center"> <div className="col-span-2 lg:col-span-1 flex items-center justify-center">
<span className="font-mono font-semibold text-white"> <span className="font-mono font-semibold text-white">
{driver.rating.toLocaleString()} {driver.rating.toString()}
</span> </span>
</div> </div>

View File

@@ -1,56 +1,46 @@
'use client'; 'use client';
import React from 'react'; import React from 'react';
import { useRouter } from 'next/navigation';
import { Trophy, Users, Award } from 'lucide-react'; import { Trophy, Users, Award } from 'lucide-react';
import Button from '@/components/ui/Button'; import Button from '@/components/ui/Button';
import Heading from '@/components/ui/Heading'; import Heading from '@/components/ui/Heading';
import { DriverLeaderboardPreview } from '@/components/leaderboards/DriverLeaderboardPreview'; import { DriverLeaderboardPreview } from '@/components/leaderboards/DriverLeaderboardPreview';
import { TeamLeaderboardPreview } from '@/components/leaderboards/TeamLeaderboardPreview'; import { TeamLeaderboardPreview } from '@/components/leaderboards/TeamLeaderboardPreview';
import type { LeaderboardsViewData } from '@/lib/view-data/LeaderboardsViewData';
import { routes } from '@/lib/routing/RouteConfig';
// ============================================================================ // ============================================================================
// TYPES // TYPES
// ============================================================================ // ============================================================================
interface LeaderboardsTemplateProps { interface LeaderboardsTemplateProps {
drivers: { viewData: LeaderboardsViewData;
id: string;
name: string;
rating: number;
skillLevel: string;
nationality: string;
wins: number;
rank: number;
avatarUrl: string;
position: number;
}[];
teams: {
id: string;
name: string;
tag: string;
memberCount: number;
category?: string;
totalWins: number;
logoUrl: string;
position: number;
}[];
onDriverClick: (driverId: string) => void;
onTeamClick: (teamId: string) => void;
onNavigateToDrivers: () => void;
onNavigateToTeams: () => void;
} }
// ============================================================================ // ============================================================================
// MAIN TEMPLATE COMPONENT // MAIN TEMPLATE COMPONENT
// ============================================================================ // ============================================================================
export function LeaderboardsTemplate({ export function LeaderboardsTemplate({ viewData }: LeaderboardsTemplateProps) {
drivers, const router = useRouter();
teams,
onDriverClick, const handleDriverClick = (driverId: string) => {
onTeamClick, router.push(routes.driver.detail(driverId));
onNavigateToDrivers, };
onNavigateToTeams,
}: LeaderboardsTemplateProps) { const handleTeamClick = (teamId: string) => {
router.push(routes.team.detail(teamId));
};
const handleNavigateToDrivers = () => {
router.push(routes.leaderboards.drivers);
};
const handleNavigateToTeams = () => {
router.push(routes.team.leaderboard);
};
return ( return (
<div className="max-w-7xl mx-auto px-4 pb-12"> <div className="max-w-7xl mx-auto px-4 pb-12">
<div className="relative mb-10 py-10 px-8 rounded-2xl bg-gradient-to-br from-yellow-600/20 via-iron-gray/80 to-deep-graphite border border-yellow-500/20 overflow-hidden"> <div className="relative mb-10 py-10 px-8 rounded-2xl bg-gradient-to-br from-yellow-600/20 via-iron-gray/80 to-deep-graphite border border-yellow-500/20 overflow-hidden">
@@ -78,7 +68,7 @@ export function LeaderboardsTemplate({
<div className="flex flex-wrap gap-3"> <div className="flex flex-wrap gap-3">
<Button <Button
variant="secondary" variant="secondary"
onClick={onNavigateToDrivers} onClick={handleNavigateToDrivers}
className="flex items-center gap-2" className="flex items-center gap-2"
> >
<Trophy className="w-4 h-4 text-primary-blue" /> <Trophy className="w-4 h-4 text-primary-blue" />
@@ -86,7 +76,7 @@ export function LeaderboardsTemplate({
</Button> </Button>
<Button <Button
variant="secondary" variant="secondary"
onClick={onNavigateToTeams} onClick={handleNavigateToTeams}
className="flex items-center gap-2" className="flex items-center gap-2"
> >
<Users className="w-4 h-4 text-purple-400" /> <Users className="w-4 h-4 text-purple-400" />
@@ -97,8 +87,8 @@ export function LeaderboardsTemplate({
</div> </div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<DriverLeaderboardPreview drivers={drivers} onDriverClick={onDriverClick} onNavigateToDrivers={onNavigateToDrivers} /> <DriverLeaderboardPreview drivers={viewData.drivers} onDriverClick={handleDriverClick} onNavigateToDrivers={handleNavigateToDrivers} />
<TeamLeaderboardPreview teams={teams} onTeamClick={onTeamClick} onNavigateToTeams={onNavigateToTeams} /> <TeamLeaderboardPreview teams={viewData.teams} onTeamClick={handleTeamClick} onNavigateToTeams={handleNavigateToTeams} />
</div> </div>
</div> </div>
); );

View File

@@ -521,7 +521,7 @@ export function RacesTemplate({
{filteredRaces.length > 0 && ( {filteredRaces.length > 0 && (
<div className="text-center"> <div className="text-center">
<Link <Link
href="/races/all" href="/races"
className="inline-flex items-center gap-2 px-6 py-3 bg-iron-gray border border-charcoal-outline rounded-lg text-white hover:border-primary-blue transition-colors" className="inline-flex items-center gap-2 px-6 py-3 bg-iron-gray border border-charcoal-outline rounded-lg text-white hover:border-primary-blue transition-colors"
> >
View All Races View All Races

View File

@@ -0,0 +1,336 @@
import { motion, useReducedMotion, AnimatePresence } from 'framer-motion';
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 MetricCard from '@/components/sponsors/MetricCard';
import SponsorshipCategoryCard from '@/components/sponsors/SponsorshipCategoryCard';
import ActivityItem from '@/components/sponsors/ActivityItem';
import RenewalAlert from '@/components/sponsors/RenewalAlert';
import {
BarChart3,
Eye,
Users,
Trophy,
TrendingUp,
Calendar,
DollarSign,
Target,
ArrowUpRight,
ArrowDownRight,
ExternalLink,
Loader2,
Car,
Flag,
Megaphone,
ChevronRight,
Plus,
Bell,
Settings,
CreditCard,
FileText,
RefreshCw
} from 'lucide-react';
import Link from 'next/link';
import type { SponsorDashboardViewData } from '@/lib/view-data/SponsorDashboardViewData';
interface SponsorDashboardTemplateProps {
viewData: SponsorDashboardViewData;
}
export function SponsorDashboardTemplate({ viewData }: SponsorDashboardTemplateProps) {
const shouldReduceMotion = useReducedMotion();
const categoryData = viewData.categoryData;
return (
<div className="max-w-7xl mx-auto py-8 px-4">
{/* Header */}
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-8">
<div>
<h2 className="text-2xl font-bold text-white">Sponsor Dashboard</h2>
<p className="text-gray-400">Welcome back, {viewData.sponsorName}</p>
</div>
<div className="flex items-center gap-3">
{/* Time Range Selector */}
<div className="flex items-center bg-iron-gray/50 rounded-lg p-1">
{(['7d', '30d', '90d', 'all'] as const).map((range) => (
<button
key={range}
onClick={() => {}}
className={`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
false
? 'bg-primary-blue text-white'
: 'text-gray-400 hover:text-white'
}`}
>
{range === 'all' ? 'All' : range}
</button>
))}
</div>
{/* Quick Actions */}
<Button variant="secondary" className="hidden sm:flex">
<RefreshCw className="w-4 h-4" />
</Button>
<Link href=routes.sponsor.settings>
<Button variant="secondary" className="hidden sm:flex">
<Settings className="w-4 h-4" />
</Button>
</Link>
</div>
</div>
{/* Key Metrics */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
<MetricCard
title="Total Impressions"
value={viewData.totalImpressions}
change={viewData.metrics.impressionsChange}
icon={Eye}
delay={0}
/>
<MetricCard
title="Unique Viewers"
value="12.5k" // Mock
change={viewData.metrics.viewersChange}
icon={Users}
delay={0.1}
/>
<MetricCard
title="Engagement Rate"
value="4.2%" // Mock
change={viewData.metrics.exposureChange}
icon={TrendingUp}
suffix="%"
delay={0.2}
/>
<MetricCard
title="Total Investment"
value={viewData.totalInvestment}
icon={DollarSign}
prefix="$"
delay={0.3}
/>
</div>
{/* Sponsorship Categories */}
<div className="mb-8">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-white">Your Sponsorships</h3>
<Link href=routes.sponsor.campaigns>
<Button variant="secondary" className="text-sm">
View All
<ChevronRight className="w-4 h-4 ml-1" />
</Button>
</Link>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
<SponsorshipCategoryCard
icon={Trophy}
title="Leagues"
count={categoryData.leagues.count}
impressions={categoryData.leagues.impressions}
color="text-primary-blue"
href="/sponsor/campaigns?type=leagues"
/>
<SponsorshipCategoryCard
icon={Users}
title="Teams"
count={categoryData.teams.count}
impressions={categoryData.teams.impressions}
color="text-purple-400"
href="/sponsor/campaigns?type=teams"
/>
<SponsorshipCategoryCard
icon={Car}
title="Drivers"
count={categoryData.drivers.count}
impressions={categoryData.drivers.impressions}
color="text-performance-green"
href="/sponsor/campaigns?type=drivers"
/>
<SponsorshipCategoryCard
icon={Flag}
title="Races"
count={categoryData.races.count}
impressions={categoryData.races.impressions}
color="text-warning-amber"
href="/sponsor/campaigns?type=races"
/>
<SponsorshipCategoryCard
icon={Megaphone}
title="Platform Ads"
count={categoryData.platform.count}
impressions={categoryData.platform.impressions}
color="text-racing-red"
href="/sponsor/campaigns?type=platform"
/>
</div>
</div>
{/* Main Content Grid */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Left Column - Sponsored Entities */}
<div className="lg:col-span-2 space-y-6">
{/* Top Performing Sponsorships */}
<Card>
<div className="flex items-center justify-between p-4 border-b border-charcoal-outline">
<h3 className="text-lg font-semibold text-white">Top Performing</h3>
<Link href="/leagues">
<Button variant="secondary" className="text-sm">
<Plus className="w-4 h-4 mr-1" />
Find More
</Button>
</Link>
</div>
<div className="divide-y divide-charcoal-outline/50">
{/* Mock data for now */}
<div className="flex items-center justify-between p-4 hover:bg-iron-gray/30 transition-colors">
<div className="flex items-center gap-4">
<div className="px-2 py-1 rounded text-xs font-medium bg-primary-blue/20 text-primary-blue border border-primary-blue/30">
Main
</div>
<div>
<div className="flex items-center gap-2">
<Trophy className="w-4 h-4 text-gray-500" />
<span className="font-medium text-white">Sample League</span>
</div>
<div className="text-sm text-gray-500">Sample details</div>
</div>
</div>
<div className="flex items-center gap-4">
<div className="text-right">
<div className="font-semibold text-white">1.2k</div>
<div className="text-xs text-gray-500">impressions</div>
</div>
<Button variant="secondary" className="text-xs">
<ExternalLink className="w-3 h-3" />
</Button>
</div>
</div>
</div>
</Card>
{/* Upcoming Events */}
<Card>
<div className="p-4 border-b border-charcoal-outline">
<h3 className="text-lg font-semibold text-white flex items-center gap-2">
<Calendar className="w-5 h-5 text-warning-amber" />
Upcoming Sponsored Events
</h3>
</div>
<div className="p-4">
<div className="text-center py-8 text-gray-500">
<Calendar className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p>No upcoming sponsored events</p>
</div>
</div>
</Card>
</div>
{/* Right Column - Activity & Quick Actions */}
<div className="space-y-6">
{/* Quick Actions */}
<Card className="p-4">
<h3 className="text-lg font-semibold text-white mb-4">Quick Actions</h3>
<div className="space-y-2">
<Link href="/leagues" className="block">
<Button variant="secondary" className="w-full justify-start">
<Target className="w-4 h-4 mr-2" />
Find Leagues to Sponsor
</Button>
</Link>
<Link href="/teams" className="block">
<Button variant="secondary" className="w-full justify-start">
<Users className="w-4 h-4 mr-2" />
Browse Teams
</Button>
</Link>
<Link href="/drivers" className="block">
<Button variant="secondary" className="w-full justify-start">
<Car className="w-4 h-4 mr-2" />
Discover Drivers
</Button>
</Link>
<Link href=routes.sponsor.billing className="block">
<Button variant="secondary" className="w-full justify-start">
<CreditCard className="w-4 h-4 mr-2" />
Manage Billing
</Button>
</Link>
<Link href=routes.sponsor.campaigns className="block">
<Button variant="secondary" className="w-full justify-start">
<BarChart3 className="w-4 h-4 mr-2" />
View Analytics
</Button>
</Link>
</div>
</Card>
{/* Renewal Alerts */}
{viewData.upcomingRenewals.length > 0 && (
<Card className="p-4">
<h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<Bell className="w-5 h-5 text-warning-amber" />
Upcoming Renewals
</h3>
<div className="space-y-3">
{viewData.upcomingRenewals.map((renewal: any) => (
<RenewalAlert key={renewal.id} renewal={renewal} />
))}
</div>
</Card>
)}
{/* Recent Activity */}
<Card className="p-4">
<h3 className="text-lg font-semibold text-white mb-4">Recent Activity</h3>
<div>
{viewData.recentActivity.map((activity: any) => (
<ActivityItem key={activity.id} activity={activity} />
))}
</div>
</Card>
{/* Investment Summary */}
<Card className="p-4">
<h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
<FileText className="w-5 h-5 text-primary-blue" />
Investment Summary
</h3>
<div className="space-y-3">
<div className="flex items-center justify-between">
<span className="text-gray-400">Active Sponsorships</span>
<span className="font-medium text-white">{viewData.activeSponsorships}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-400">Total Investment</span>
<span className="font-medium text-white">{viewData.formattedTotalInvestment}</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-400">Cost per 1K Views</span>
<span className="font-medium text-performance-green">
{viewData.costPerThousandViews}
</span>
</div>
<div className="flex items-center justify-between">
<span className="text-gray-400">Next Invoice</span>
<span className="font-medium text-white">Jan 1, 2026</span>
</div>
<div className="pt-3 border-t border-charcoal-outline">
<Link href=routes.sponsor.billing>
<Button variant="secondary" className="w-full text-sm">
<CreditCard className="w-4 h-4 mr-2" />
View Billing Details
</Button>
</Link>
</div>
</div>
</Card>
</div>
</div>
</div>
);
}

View File

@@ -111,9 +111,9 @@ export function SponsorLeagueDetailTemplate({ data }: SponsorLeagueDetailTemplat
<div className="max-w-7xl mx-auto py-8 px-4"> <div className="max-w-7xl mx-auto py-8 px-4">
{/* Breadcrumb */} {/* Breadcrumb */}
<div className="flex items-center gap-2 text-sm text-gray-400 mb-6"> <div className="flex items-center gap-2 text-sm text-gray-400 mb-6">
<Link href="/sponsor/dashboard" className="hover:text-white transition-colors">Dashboard</Link> <Link href=routes.sponsor.dashboard className="hover:text-white transition-colors">Dashboard</Link>
<ChevronRight className="w-4 h-4" /> <ChevronRight className="w-4 h-4" />
<Link href="/sponsor/leagues" className="hover:text-white transition-colors">Leagues</Link> <Link href=routes.sponsor.leagues className="hover:text-white transition-colors">Leagues</Link>
<ChevronRight className="w-4 h-4" /> <ChevronRight className="w-4 h-4" />
<span className="text-white">{league.name}</span> <span className="text-white">{league.name}</span>
</div> </div>

Some files were not shown because too many files have changed in this diff Show More