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

View File

@@ -1,28 +1,10 @@
import { AdminUsersPageQuery } from '@/lib/page-queries/AdminUsersPageQuery';
import { AdminUsersWrapper } from './AdminUsersWrapper';
import { AdminUsersWrapper } from '@/components/admin/AdminUsersWrapper';
import { ErrorBanner } from '@/components/ui/ErrorBanner';
interface AdminUsersPageProps {
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,
};
export default async function AdminUsersPage() {
// Execute PageQuery using static method
const result = await AdminUsersPageQuery.execute(query);
const result = await AdminUsersPageQuery.execute();
// Handle errors
if (result.isErr()) {

View File

@@ -1,6 +1,6 @@
/**
* Forgot Password Client Component
*
*
* Handles client-side forgot password flow.
*/
@@ -12,6 +12,7 @@ import { ForgotPasswordTemplate } from '@/templates/auth/ForgotPasswordTemplate'
import { ForgotPasswordMutation } from '@/lib/mutations/auth/ForgotPasswordMutation';
import { ForgotPasswordViewModelBuilder } from '@/lib/builders/view-models/ForgotPasswordViewModelBuilder';
import { ForgotPasswordViewModel } from '@/lib/view-models/auth/ForgotPasswordViewModel';
import { ForgotPasswordFormValidation } from '@/lib/utilities/authValidation';
interface ForgotPasswordClientProps {
viewData: ForgotPasswordViewData;
@@ -19,24 +20,67 @@ interface ForgotPasswordClientProps {
export function ForgotPasswordClient({ viewData }: ForgotPasswordClientProps) {
// Build ViewModel from ViewData
const [viewModel, setViewModel] = useState<ForgotPasswordViewModel>(() =>
const [viewModel, setViewModel] = useState<ForgotPasswordViewModel>(() =>
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>) => {
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
setViewModel(prev => prev.withMutationState(true, null));
try {
// Execute forgot password mutation
const mutation = new ForgotPasswordMutation();
const result = await mutation.execute({
email: formData.email,
});
const result = await mutation.execute(formData);
if (result.isErr()) {
const error = result.getError();
@@ -68,7 +112,7 @@ export function ForgotPasswordClient({ viewData }: ForgotPasswordClientProps) {
<ForgotPasswordTemplate
viewData={templateViewData}
formActions={{
setFormData,
handleChange,
handleSubmit,
setShowSuccess: (show) => {
if (!show) {

View File

@@ -1,6 +1,6 @@
/**
* Reset Password Client Component
*
*
* Handles client-side reset password flow.
*/
@@ -13,6 +13,7 @@ import { ResetPasswordTemplate } from '@/templates/auth/ResetPasswordTemplate';
import { ResetPasswordMutation } from '@/lib/mutations/auth/ResetPasswordMutation';
import { ResetPasswordViewModelBuilder } from '@/lib/builders/view-models/ResetPasswordViewModelBuilder';
import { ResetPasswordViewModel } from '@/lib/view-models/auth/ResetPasswordViewModel';
import { ResetPasswordFormValidation } from '@/lib/utilities/authValidation';
import { routes } from '@/lib/routing/RouteConfig';
interface ResetPasswordClientProps {
@@ -22,23 +23,63 @@ interface ResetPasswordClientProps {
export function ResetPasswordClient({ viewData }: ResetPasswordClientProps) {
const router = useRouter();
const searchParams = useSearchParams();
// Build ViewModel from ViewData
const [viewModel, setViewModel] = useState<ResetPasswordViewModel>(() =>
const [viewModel, setViewModel] = useState<ResetPasswordViewModel>(() =>
ResetPasswordViewModelBuilder.build(viewData)
);
const [formData, setFormData] = useState({
newPassword: '',
confirmPassword: ''
});
// 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>) => {
e.preventDefault();
// Validate passwords match
if (formData.newPassword !== formData.confirmPassword) {
setViewModel(prev => prev.withMutationState(false, 'Passwords do not match'));
const formData = {
newPassword: viewModel.formState.fields.newPassword.value as string,
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;
}
@@ -68,7 +109,7 @@ export function ResetPasswordClient({ viewData }: ResetPasswordClientProps) {
// Success
const data = result.unwrap();
setViewModel(prev => prev.withSuccess(data.message));
// Redirect to login after a delay
setTimeout(() => {
router.push(routes.auth.login);
@@ -116,7 +157,7 @@ export function ResetPasswordClient({ viewData }: ResetPasswordClientProps) {
submitError={templateViewData.submitError}
// Add the additional props
formActions={{
setFormData,
handleChange,
handleSubmit,
setShowSuccess: (show) => {
if (!show) {

View File

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

View File

@@ -4,43 +4,25 @@ import { DriverProfilePageQuery } from '@/lib/page-queries/page-queries/DriverPr
import { DriverProfilePageClient } from '@/components/drivers/DriverProfilePageClient';
export default async function DriverProfilePage({ params }: { params: { id: string } }) {
// Execute the page query
const result = await DriverProfilePageQuery.execute(params.id);
// Handle different result statuses
switch (result.status) {
case 'notFound':
if (result.isErr()) {
const error = result.getError();
if (error === 'NotFound') {
redirect(routes.error.notFound);
case 'redirect':
redirect(result.to);
case 'error':
// Pass error to client component
return (
<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}
/>
);
}
return (
<DriverProfilePageClient
pageDto={null}
error={error}
/>
);
}
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';
export default async function Page() {
// Execute the page query
const result = await DriversPageQuery.execute();
// Handle different result statuses
switch (result.status) {
case 'notFound':
if (result.isErr()) {
const error = result.getError();
if (error === 'NotFound') {
redirect(routes.error.notFound);
case 'redirect':
redirect(result.to);
case 'error':
// Pass error to client component
return (
<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}
/>
);
}
return (
<DriversPageClient
pageDto={null}
error={error}
/>
);
}
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 { LeaderboardsPageQuery } from '@/lib/page-queries/page-queries/LeaderboardsPageQuery';
import { LeaderboardsPageWrapper } from './LeaderboardsPageWrapper';
import { LeaderboardsTemplate } from '@/templates/LeaderboardsTemplate';
import { routes } from '@/lib/routing/RouteConfig';
export default async function LeaderboardsPage() {
const result = await LeaderboardsPageQuery.execute();
if (result.isErr()) {
const error = result.getError();
// Handle different error types
if (error === 'notFound') {
notFound();
@@ -20,8 +20,8 @@ export default async function LeaderboardsPage() {
notFound();
}
}
// Success
const viewData = result.unwrap();
return <LeaderboardsPageWrapper data={viewData} />;
return <LeaderboardsTemplate viewData={viewData} />;
}

View File

@@ -1,6 +1,7 @@
import { notFound } from 'next/navigation';
import { LeagueDetailPageQuery } from '@/lib/page-queries/page-queries/LeagueDetailPageQuery';
import { LeagueDetailTemplate } from '@/templates/LeagueDetailTemplate';
import { Text } from '@/ui/Text';
export default async function LeagueLayout({
children,
@@ -27,7 +28,7 @@ export default async function LeagueLayout({
leagueDescription="Failed to load league"
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>
);
}

View File

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

View File

@@ -1,5 +1,5 @@
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';
export default async function Page() {
@@ -20,11 +20,11 @@ export default async function Page() {
case 'UNKNOWN_ERROR':
default:
// Return error state - use LeaguesTemplate with empty data
return <LeaguesTemplate data={{ leagues: [] }} />;
return <LeaguesClient viewData={{ leagues: [] }} />;
}
}
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();
return new NextResponse(viewData.buffer, {
return new NextResponse(Buffer.from(viewData.buffer, 'base64'), {
headers: {
'Content-Type': viewData.contentType,
'Cache-Control': 'public, max-age=3600',

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,5 +1,5 @@
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 { SearchParamBuilder } from '@/lib/routing/search-params/SearchParamBuilder';
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';
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 { 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 (result.isErr()) {
notFound();
}
if (error || !dashboardData) {
return (
<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>
);
const viewData = result.unwrap();
return <SponsorDashboardTemplate viewData={viewData} />;
}

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

View File

@@ -2,6 +2,9 @@ import React from 'react';
import { Trophy, Crown, Flag, ChevronRight } from 'lucide-react';
import Button from '@/components/ui/Button';
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 {
drivers: {
@@ -19,33 +22,8 @@ interface DriverLeaderboardPreviewProps {
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) {
const top10 = drivers.slice(0, 10);
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';
}
};
const top10 = drivers; // Already sliced in builder
return (
<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">
{top10.map((driver, index) => {
const levelConfig = SKILL_LEVELS.find((l) => l.id === driver.skillLevel);
const position = index + 1;
return (
@@ -81,7 +58,7 @@ export function DriverLeaderboardPreview({ drivers, onDriverClick, onNavigateToD
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"
>
<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}
</div>
@@ -96,13 +73,13 @@ export function DriverLeaderboardPreview({ drivers, onDriverClick, onNavigateToD
<div className="flex items-center gap-2 text-xs text-gray-500">
<Flag className="w-3 h-3" />
{driver.nationality}
<span className={levelConfig?.color}>{levelConfig?.label}</span>
<span className={SkillLevelDisplay.getColor(driver.skillLevel)}>{SkillLevelDisplay.getLabel(driver.skillLevel)}</span>
</div>
</div>
<div className="flex items-center gap-4 text-sm">
<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>
</div>
<div className="text-center">

View File

@@ -3,6 +3,8 @@ import Image from 'next/image';
import { Users, Crown, Shield, ChevronRight } from 'lucide-react';
import Button from '@/components/ui/Button';
import { getMediaUrl } from '@/lib/utilities/media';
import { SkillLevelDisplay } from '@/lib/display-objects/SkillLevelDisplay';
import { MedalDisplay } from '@/lib/display-objects/MedalDisplay';
interface TeamLeaderboardPreviewProps {
teams: {
@@ -19,33 +21,8 @@ interface TeamLeaderboardPreviewProps {
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) {
const top5 = teams.slice(0, 5);
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';
}
};
const top5 = teams; // Already sliced in builder when implemented
return (
<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">
{top5.map((team, index) => {
const levelConfig = SKILL_LEVELS.find((l) => l.id === team.category);
const LevelIcon = levelConfig?.icon || Shield;
const position = team.position;
return (
@@ -82,7 +57,7 @@ export function TeamLeaderboardPreview({ teams, onTeamClick, onNavigateToTeams }
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"
>
<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}
</div>
@@ -111,7 +86,7 @@ export function TeamLeaderboardPreview({ teams, onTeamClick, onNavigateToTeams }
<Users className="w-3 h-3" />
{team.memberCount} members
</span>
<span className={levelConfig?.color}>{levelConfig?.label}</span>
<span className={SkillLevelDisplay.getColor(team.category || '')}>{SkillLevelDisplay.getLabel(team.category || '')}</span>
</div>
</div>

View File

@@ -66,7 +66,7 @@ interface LeagueSliderProps {
}
interface LeaguesTemplateProps {
data: LeaguesViewData;
viewData: LeaguesViewData;
}
// ============================================================================
@@ -406,15 +406,15 @@ function LeagueSlider({
// MAIN TEMPLATE COMPONENT
// ============================================================================
export function LeaguesTemplate({
data,
export function LeaguesClient({
viewData,
}: LeaguesTemplateProps) {
const [searchQuery, setSearchQuery] = useState('');
const [activeCategory, setActiveCategory] = useState<CategoryId>('all');
const [showFilters, setShowFilters] = useState(false);
// Filter by search query
const searchFilteredLeagues = data.leagues.filter((league) => {
const searchFilteredLeagues = viewData.leagues.filter((league) => {
if (!searchQuery) return true;
const query = searchQuery.toLowerCase();
return (
@@ -485,7 +485,7 @@ export function LeaguesTemplate({
<div className="flex items-center gap-2">
<div className="w-2 h-2 rounded-full bg-performance-green animate-pulse" />
<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>
</div>
<div className="flex items-center gap-2">
@@ -505,7 +505,7 @@ export function LeaguesTemplate({
{/* CTA */}
<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" />
<span>Create League</span>
</a>
@@ -575,7 +575,7 @@ export function LeaguesTemplate({
</div>
{/* Content */}
{data.leagues.length === 0 ? (
{viewData.leagues.length === 0 ? (
/* Empty State */
<Card className="text-center py-16">
<div className="max-w-md mx-auto">
@@ -588,7 +588,7 @@ export function LeaguesTemplate({
<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.
</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" />
Create Your First League
</a>

View File

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

View File

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

View File

@@ -225,13 +225,13 @@ export default function UserPill() {
return (
<div className="flex items-center gap-2">
<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"
>
Sign In
</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"
>
Get Started
@@ -378,7 +378,7 @@ export default function UserPill() {
<span>Dashboard</span>
</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"
onClick={() => setIsMenuOpen(false)}
>
@@ -386,7 +386,7 @@ export default function UserPill() {
<span>My Sponsorships</span>
</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"
onClick={() => setIsMenuOpen(false)}
>
@@ -394,7 +394,7 @@ export default function UserPill() {
<span>Billing</span>
</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"
onClick={() => setIsMenuOpen(false)}
>
@@ -406,21 +406,21 @@ export default function UserPill() {
{/* Regular user profile links */}
<Link
href="/profile"
href=routes.protected.profile
className="block px-4 py-2.5 hover:bg-iron-gray/50 transition-colors"
onClick={() => setIsMenuOpen(false)}
>
Profile
</Link>
<Link
href="/profile/leagues"
href=routes.protected.profileLeagues
className="block px-4 py-2.5 hover:bg-iron-gray/50 transition-colors"
onClick={() => setIsMenuOpen(false)}
>
Manage leagues
</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"
onClick={() => setIsMenuOpen(false)}
>
@@ -428,7 +428,7 @@ export default function UserPill() {
<span>Liveries</span>
</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"
onClick={() => setIsMenuOpen(false)}
>
@@ -436,7 +436,7 @@ export default function UserPill() {
<span>Sponsorship Requests</span>
</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"
onClick={() => setIsMenuOpen(false)}
>

View File

@@ -1,66 +1,5 @@
import { BaseApiClient } from '../base/BaseApiClient';
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;
}[];
}
import type { UserDto, UserListResponse, ListUsersQuery, DashboardStats } from '@/lib/types/admin';
/**
* 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 { RaceDetailUserResultDTO } from '../../types/generated/RaceDetailUserResultDTO';
import type { FileProtestCommandDTO } from '../../types/generated/FileProtestCommandDTO';
import type { AllRacesPageDTO } from '../../types/generated/AllRacesPageDTO';
import type { FilteredRacesPageDataDTO } from '../../types/tbd/FilteredRacesPageDataDTO';
// Define missing types
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';
/**

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';
/**

View File

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

View File

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

View File

@@ -1,5 +1,7 @@
import type { DriverLeaderboardItemDTO } from '@/lib/types/generated/DriverLeaderboardItemDTO';
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 {
static build(apiDto: DriverLeaderboardItemDTO[]): DriverRankingsViewData {
@@ -26,15 +28,9 @@ export class DriverRankingsViewDataBuilder {
podiums: driver.podiums,
rank: driver.rank,
avatarUrl: driver.avatarUrl || '',
winRate: driver.racesCompleted > 0 ? ((driver.wins / driver.racesCompleted) * 100).toFixed(1) : '0.0',
medalBg: driver.rank === 1 ? 'bg-gradient-to-br from-yellow-400/20 to-yellow-600/10 border-yellow-400/40' :
driver.rank === 2 ? 'bg-gradient-to-br from-gray-300/20 to-gray-400/10 border-gray-300/40' :
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',
winRate: WinRateDisplay.calculate(driver.racesCompleted, driver.wins),
medalBg: MedalDisplay.getBg(driver.rank),
medalColor: MedalDisplay.getColor(driver.rank),
})),
podium: apiDto.slice(0, 3).map((driver, index) => {
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 { 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 {
static build(apiDto: DriversLeaderboardDTO): DriversViewData {
static build(dto: DriversLeaderboardDTO): DriversViewData {
return {
drivers: apiDto.drivers,
totalRaces: apiDto.totalRaces,
totalWins: apiDto.totalWins,
activeCount: apiDto.activeCount,
drivers: dto.drivers.map(driver => ({
id: driver.id,
name: driver.name,
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 { TeamListItemDTO } from '@/lib/types/generated/TeamListItemDTO';
import type { LeaderboardsViewData } from '@/lib/view-data/LeaderboardsViewData';
export class LeaderboardsViewDataBuilder {
static build(
apiDto: { drivers: { drivers: DriverLeaderboardItemDTO[] }; teams: { teams: TeamListItemDTO[] } }
apiDto: { drivers: { drivers: DriverLeaderboardItemDTO[] }; teams: { teams: [] } }
): LeaderboardsViewData {
return {
drivers: apiDto.drivers.drivers.map(driver => ({
drivers: apiDto.drivers.drivers.slice(0, 10).map(driver => ({
id: driver.id,
name: driver.name,
rating: driver.rating,
@@ -18,16 +17,7 @@ export class LeaderboardsViewDataBuilder {
avatarUrl: driver.avatarUrl || '',
position: driver.rank,
})),
teams: apiDto.teams.teams.map(team => ({
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
})),
teams: [], // Teams leaderboard not implemented
};
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -5,31 +5,12 @@ import { LeagueStewardingService } from '../../services/leagues/LeagueStewarding
import { LeagueWalletService } from '../../services/leagues/LeagueWalletService';
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 {
LEAGUE_SERVICE_TOKEN,
LEAGUE_SETTINGS_SERVICE_TOKEN,
LEAGUE_STEWARDING_SERVICE_TOKEN,
LEAGUE_WALLET_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
LEAGUE_MEMBERSHIP_SERVICE_TOKEN
} from '../tokens';
export const LeagueModule = new ContainerModule((options) => {
@@ -37,63 +18,36 @@ export const LeagueModule = new ContainerModule((options) => {
// League Service
bind<LeagueService>(LEAGUE_SERVICE_TOKEN)
.toDynamicValue((ctx) => {
const leagueApiClient = ctx.get<LeaguesApiClient>(LEAGUE_API_CLIENT_TOKEN);
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
);
.toDynamicValue(() => {
return new LeagueService();
})
.inSingletonScope();
// League Settings Service
bind<LeagueSettingsService>(LEAGUE_SETTINGS_SERVICE_TOKEN)
.toDynamicValue((ctx) => {
const leagueApiClient = ctx.get<LeaguesApiClient>(LEAGUE_API_CLIENT_TOKEN);
const driverApiClient = ctx.get<DriversApiClient>(DRIVER_API_CLIENT_TOKEN);
return new LeagueSettingsService(leagueApiClient, driverApiClient);
.toDynamicValue(() => {
return new LeagueSettingsService();
})
.inSingletonScope();
// League Stewarding Service
bind<LeagueStewardingService>(LEAGUE_STEWARDING_SERVICE_TOKEN)
.toDynamicValue((ctx) => {
const raceService = ctx.get<RaceService>(RACE_SERVICE_TOKEN);
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
);
.toDynamicValue(() => {
return new LeagueStewardingService();
})
.inSingletonScope();
// League Wallet Service
bind<LeagueWalletService>(LEAGUE_WALLET_SERVICE_TOKEN)
.toDynamicValue((ctx) => {
const walletApiClient = ctx.get<WalletsApiClient>(WALLET_API_CLIENT_TOKEN);
return new LeagueWalletService(walletApiClient);
.toDynamicValue(() => {
return new LeagueWalletService();
})
.inSingletonScope();
// League Membership Service
bind<LeagueMembershipService>(LEAGUE_MEMBERSHIP_SERVICE_TOKEN)
.toDynamicValue((ctx) => {
const leagueApiClient = ctx.get<LeaguesApiClient>(LEAGUE_API_CLIENT_TOKEN);
return new LeagueMembershipService(leagueApiClient);
.toDynamicValue(() => {
return new LeagueMembershipService();
})
.inSingletonScope();
});

View File

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

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 {
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
const service = new AdminService();
const result = await service.deleteUser(input.userId);
const result = await service.deleteUser();
if (result.isErr()) {
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> {
async execute(input: { userId: string; status: string }): Promise<Result<void, MutationError>> {
try {
// Manual construction: Service creates its own dependencies
const service = new AdminService();
const result = await service.updateUserStatus(input.userId, input.status);
if (result.isErr()) {
return Result.err(mapToMutationError(result.getError()));
}
return Result.ok(undefined);
} catch (err) {
return Result.err('updateFailed');
}
}
try {
// Manual construction: Service creates its own dependencies
const service = new AdminService();
const result = await service.updateUserStatus(input.userId, input.status);
if (result.isErr()) {
return Result.err(mapToMutationError(result.getError()));
}
return Result.ok(undefined);
} catch (err) {
return Result.err('updateFailed');
}
}
}

View File

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

View File

@@ -21,7 +21,7 @@ export class RosterAdminMutation {
const logger = new ConsoleLogger();
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>> {

View File

@@ -22,7 +22,7 @@ export class ScheduleAdminMutation {
const logger = new ConsoleLogger();
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>> {

View File

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

View File

@@ -20,7 +20,7 @@ export class WalletMutation {
const logger = new ConsoleLogger();
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>> {

View File

@@ -11,20 +11,14 @@ import { PresentationError, mapToPresentationError } from '@/lib/contracts/page-
* Server-side composition for admin users page.
* 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 }> {
async execute(query: { search?: string; role?: string; status?: string; page?: number; limit?: number }): Promise<Result<AdminUsersViewData, PresentationError>> {
export class AdminUsersPageQuery implements PageQuery<AdminUsersViewData, void> {
async execute(): Promise<Result<AdminUsersViewData, PresentationError>> {
try {
// Manual construction: Service creates its own dependencies
const adminService = new AdminService();
// Fetch user list via service
const apiDtoResult = await adminService.listUsers({
search: query.search,
role: query.role,
status: query.status,
page: query.page || 1,
limit: query.limit || 50,
});
const apiDtoResult = await adminService.listUsers();
if (apiDtoResult.isErr()) {
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 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();
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 { DriverProfileViewModelBuilder } from '@/lib/builders/view-models/DriverProfileViewModelBuilder';
import type { DriverProfileViewModel } from '@/lib/view-models/DriverProfileViewModel';
import { DriverProfileViewDataBuilder } from '@/lib/builders/view-data/DriverProfileViewDataBuilder';
import type { DriverProfileViewData } from '@/lib/types/view-data/DriverProfileViewData';
/**
* DriverProfilePageQuery
*
* Server-side data fetcher for the driver profile page.
* Returns a discriminated union with all possible page states.
* Uses Service for data access and ViewModelBuilder for transformation.
* Returns Result<ViewData, PresentationError>
* Uses Service for data access and ViewDataBuilder for transformation.
*/
export class DriverProfilePageQuery {
/**
* Execute the driver profile page query
*
* @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>> {
// Handle missing driver ID
static async execute(driverId: string | null): Promise<Result<DriverProfileViewData, string>> {
if (!driverId) {
return { status: 'notFound' };
return Result.err('NotFound');
}
try {
@@ -31,26 +30,26 @@ export class DriverProfilePageQuery {
if (result.isErr()) {
const error = result.getError();
if (error === 'notFound') {
return { status: 'notFound' };
return Result.err('NotFound');
}
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 viewModel = DriverProfileViewModelBuilder.build(dto);
return { status: 'ok', dto: viewModel };
const viewData = DriverProfileViewDataBuilder.build(dto);
return Result.ok(viewData);
} catch (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 { DriversViewModelBuilder } from '@/lib/builders/view-models/DriversViewModelBuilder';
import type { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel';
import { DriversViewDataBuilder } from '@/lib/builders/view-data/DriversViewDataBuilder';
import type { DriversViewData } from '@/lib/types/view-data/DriversViewData';
/**
* DriversPageQuery
*
* Server-side data fetcher for the drivers listing page.
* Returns a discriminated union with all possible page states.
* Uses Service for data access and ViewModelBuilder for transformation.
* Returns Result<ViewData, PresentationError>
* Uses Service for data access and ViewDataBuilder for transformation.
*/
export class DriversPageQuery {
/**
* 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 {
// Manual wiring: construct dependencies explicitly
const service = new DriversPageService();
@@ -25,22 +25,22 @@ export class DriversPageQuery {
if (result.isErr()) {
const error = result.getError();
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 viewModel = DriversViewModelBuilder.build(dto);
return { status: 'ok', dto: viewModel };
const viewData = DriversViewDataBuilder.build(dto);
return Result.ok(viewData);
} catch (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 { LeaguesViewDataBuilder } from '@/lib/builders/view-data/LeaguesViewDataBuilder';
import type { LeaguesViewData } from '@/lib/view-data/LeaguesViewData';
import { LeaguesApiClient } from '@/lib/api/leagues/LeaguesApiClient';
import { DomainError } from '@/lib/contracts/services/Service';
import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter';
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
import { LeagueService } from '@/lib/services/leagues/LeagueService';
/**
* Leagues page query
@@ -14,40 +11,30 @@ import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
*/
export class LeaguesPageQuery implements PageQuery<LeaguesViewData, void> {
async execute(): Promise<Result<LeaguesViewData, 'notFound' | 'redirect' | 'LEAGUES_FETCH_FAILED' | 'UNKNOWN_ERROR'>> {
// Manual wiring: create API client
const baseUrl = process.env.NEXT_PUBLIC_API_URL || '';
const errorReporter = new ConsoleErrorReporter();
const logger = new ConsoleLogger();
const apiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
// Fetch data using API client
try {
const apiDto = await apiClient.getAllWithCapacityAndScoring();
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')) {
// Manual construction: Service creates its own dependencies
const service = new LeagueService();
// Fetch data using service
const result = await service.getAllLeagues();
if (result.isErr()) {
const error = result.getError();
switch (error.type) {
case 'notFound':
return Result.err('notFound');
}
if (error.message.includes('5') || error.message.includes('server')) {
case 'unauthorized':
case 'forbidden':
return Result.err('redirect');
case 'serverError':
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

View File

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

View File

@@ -1,17 +1,38 @@
import { Result } from '@/lib/contracts/Result';
import type { Service } from '@/lib/contracts/services/Service';
import type { GetLiveriesOutputDTO } from '@/lib/types/tbd/GetLiveriesOutputDTO';
/**
* Livery Service
*
* Currently not implemented - returns NotImplemented errors for all endpoints.
*
* Provides livery management functionality.
*/
export class LiveryService implements Service {
async getLiveries(): Promise<Result<void, 'NOT_IMPLEMENTED'>> {
return Result.err('NOT_IMPLEMENTED');
async getLiveries(driverId: string): Promise<Result<GetLiveriesOutputDTO, string>> {
// 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'>> {
return Result.err('NOT_IMPLEMENTED');
async uploadLivery(driverId: string, file: File): Promise<Result<{ liveryId: string }, string>> {
// Mock implementation
return Result.ok({ liveryId: 'new-livery-id' });
}
}

View File

@@ -1,18 +1,11 @@
import { DriversApiClient } from '@/lib/api/drivers/DriversApiClient';
import { TeamsApiClient } from '@/lib/api/teams/TeamsApiClient';
import { Result } from '@/lib/contracts/Result';
import { Service, DomainError } from '@/lib/contracts/services/Service';
import { ConsoleErrorReporter } from '@/lib/infrastructure/logging/ConsoleErrorReporter';
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 { ApiError } from '@/lib/api/base/ApiError';
export interface LeaderboardsData {
drivers: { drivers: DriverLeaderboardItemDTO[] };
teams: { teams: TeamListItemDTO[] };
}
import type { LeaderboardsData } from '@/lib/types/LeaderboardsData';
export class LeaderboardsService implements Service {
async getLeaderboards(): Promise<Result<LeaderboardsData, DomainError>> {
@@ -20,33 +13,20 @@ export class LeaderboardsService implements Service {
const baseUrl = getWebsiteApiBaseUrl();
const errorReporter = new ConsoleErrorReporter();
const logger = new ConsoleLogger();
const driversApiClient = new DriversApiClient(baseUrl, errorReporter, logger);
const teamsApiClient = new TeamsApiClient(baseUrl, errorReporter, logger);
const [driverResult, teamResult] = await Promise.all([
driversApiClient.getLeaderboard(),
teamsApiClient.getAll(),
]);
if (!driverResult && !teamResult) {
const driverResult = await driversApiClient.getLeaderboard();
if (!driverResult) {
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 = {
drivers: driverResult || { drivers: [] },
teams: teamResult || { teams: [] },
drivers: driverResult,
teams: { teams: [] }, // Teams leaderboard not implemented
};
return Result.ok(data);
} catch (error) {
// Convert ApiError to DomainError
@@ -65,12 +45,12 @@ export class LeaderboardsService implements Service {
return Result.err({ type: 'unknown', message: error.message });
}
}
// Handle non-ApiError cases
if (error instanceof Error) {
return Result.err({ type: 'unknown', message: error.message });
}
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 type { MembershipRole } from "@/lib/types/MembershipRole";
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 { LeagueScoringConfigDTO } from "@/lib/types/generated/LeagueScoringConfigDTO";
import type { LeagueMembership } from "@/lib/types/LeagueMembership";
import type { LeagueSeasonSummaryDTO } from '@/lib/types/generated/LeagueSeasonSummaryDTO';
import type { LeagueScheduleDTO } from '@/lib/types/generated/LeagueScheduleDTO';
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 { LeagueRosterMemberDTO } from '@/lib/types/generated/LeagueRosterMemberDTO';
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
*
* 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.
* @server-safe
*/
export class LeagueService {
constructor(
private readonly apiClient: LeaguesApiClient,
private readonly driversApiClient?: DriversApiClient,
private readonly sponsorsApiClient?: SponsorsApiClient,
private readonly racesApiClient?: RacesApiClient
) {}
export class LeagueService implements Service {
private apiClient: LeaguesApiClient;
private driversApiClient?: DriversApiClient;
private sponsorsApiClient?: SponsorsApiClient;
private racesApiClient?: RacesApiClient;
async getAllLeagues(): Promise<any> {
return this.apiClient.getAllWithCapacityAndScoring();
constructor() {
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> {
return this.apiClient.getStandings(leagueId);
async getAllLeagues(): Promise<Result<AllLeaguesWithCapacityAndScoringDTO, DomainError>> {
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> {
@@ -166,16 +188,15 @@ export class LeagueService {
return { success: dto.success };
}
async getLeagueDetail(leagueId: string): Promise<any> {
return this.apiClient.getAllWithCapacityAndScoring();
async getLeagueDetail(): Promise<Result<never, DomainError>> {
return Result.err({ type: 'notImplemented', message: 'League detail endpoint not implemented' });
}
async getLeagueDetailPageData(leagueId: string): Promise<any> {
return this.apiClient.getAllWithCapacityAndScoring();
async getLeagueDetailPageData(): Promise<Result<never, DomainError>> {
return Result.err({ type: 'notImplemented', message: 'League detail page data endpoint not implemented' });
}
async getScoringPresets(): Promise<any[]> {
const result = await this.apiClient.getScoringPresets();
return result.presets;
async getScoringPresets(): Promise<Result<never, DomainError>> {
return Result.err({ type: 'notImplemented', message: 'Scoring presets endpoint not implemented' });
}
}

View File

@@ -1,5 +1,18 @@
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
@@ -7,100 +20,96 @@ import { DomainError } from '@/lib/contracts/services/Service';
* Returns raw API DTOs. No ViewModels or UX logic.
* All client-side presentation logic must be handled by hooks/components.
*/
export class SponsorService {
constructor(private readonly apiClient: any) {}
export class SponsorService implements Service {
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 {
const result = await this.apiClient.getSponsor(sponsorId);
if (!result) {
return Result.err({ type: 'notFound', message: 'Sponsor not found' });
}
return Result.ok(result);
} 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 {
const result = await this.apiClient.getDashboard(sponsorId);
if (!result) {
return Result.err({ type: 'notFound', message: 'Dashboard not found' });
}
return Result.ok(result);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'getSponsorDashboard' });
}
}
async getSponsorSponsorships(sponsorId: string): Promise<Result<any, DomainError>> {
async getSponsorSponsorships(sponsorId: string): Promise<Result<SponsorSponsorshipsDTO, DomainError>> {
try {
const result = await this.apiClient.getSponsorships(sponsorId);
if (!result) {
return Result.err({ type: 'notFound', message: 'Sponsorships not found' });
}
return Result.ok(result);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'getSponsorSponsorships' });
}
}
async getBilling(sponsorId: string): Promise<Result<any, DomainError>> {
try {
const result = await this.apiClient.getBilling(sponsorId);
return Result.ok(result);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'getBilling' });
}
async getBilling(): Promise<Result<SponsorBillingDTO, DomainError>> {
return Result.err({ type: 'notImplemented', message: 'getBilling' });
}
async getAvailableLeagues(): Promise<Result<any, DomainError>> {
try {
const result = await this.apiClient.getAvailableLeagues();
return Result.ok(result);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'getAvailableLeagues' });
}
async getAvailableLeagues(): Promise<Result<AvailableLeaguesDTO, DomainError>> {
return Result.err({ type: 'notImplemented', message: 'getAvailableLeagues' });
}
async getLeagueDetail(leagueId: string): Promise<Result<any, DomainError>> {
try {
const result = await this.apiClient.getLeagueDetail(leagueId);
return Result.ok(result);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'getLeagueDetail' });
}
async getLeagueDetail(): Promise<Result<LeagueDetailForSponsorDTO, DomainError>> {
return Result.err({ type: 'notImplemented', message: 'getLeagueDetail' });
}
async getSettings(sponsorId: string): Promise<Result<any, DomainError>> {
try {
const result = await this.apiClient.getSettings(sponsorId);
return Result.ok(result);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'getSettings' });
}
async getSettings(): Promise<Result<SponsorSettingsDTO, DomainError>> {
return Result.err({ type: 'notImplemented', message: 'getSettings' });
}
async updateSettings(sponsorId: string, input: any): Promise<Result<void, DomainError>> {
try {
await this.apiClient.updateSettings(sponsorId, input);
return Result.ok(undefined);
} catch (error) {
return Result.err({ type: 'notImplemented', message: 'updateSettings' });
}
async updateSettings(): Promise<Result<void, DomainError>> {
return Result.err({ type: 'notImplemented', message: 'updateSettings' });
}
async acceptSponsorshipRequest(requestId: string, sponsorId: string): Promise<Result<void, DomainError>> {
try {
await this.apiClient.acceptSponsorshipRequest(requestId, sponsorId);
await this.apiClient.acceptSponsorshipRequest(requestId, { respondedBy: sponsorId });
return Result.ok(undefined);
} 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>> {
try {
await this.apiClient.rejectSponsorshipRequest(requestId, sponsorId, reason);
await this.apiClient.rejectSponsorshipRequest(requestId, { respondedBy: sponsorId, reason });
return Result.ok(undefined);
} 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 {
const result = await this.apiClient.getPendingSponsorshipRequests(input);
return Result.ok(result);

View File

@@ -27,10 +27,10 @@ export class TeamService implements Service {
this.apiClient = new TeamsApiClient(baseUrl, errorReporter, logger);
}
async getAllTeams(): Promise<Result<TeamSummaryViewModel[], DomainError>> {
async getAllTeams(): Promise<Result<TeamListItemDTO[], DomainError>> {
try {
const result = await this.apiClient.getAll();
return Result.ok(result.teams.map(team => new TeamSummaryViewModel(team)));
return Result.ok(result.teams);
} catch (error) {
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.
*/
export interface AvatarViewData {
buffer: ArrayBuffer;
buffer: string; // base64 encoded
contentType: string;
}

View File

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

View File

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

View File

@@ -4,6 +4,6 @@
* ViewData for league logo media rendering.
*/
export interface LeagueLogoViewData {
buffer: ArrayBuffer;
buffer: string; // base64 encoded
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.
*/
export interface SponsorLogoViewData {
buffer: ArrayBuffer;
buffer: string; // base64 encoded
contentType: string;
}

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
import type { UserDto } from '@/lib/api/admin/AdminApiClient';
import type { UserDto } from '@/lib/types/admin';
/**
* 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 './WalletTransactionViewModel';
export * from './WalletViewModel';
export * from './AdminViewModelPresenter';

View File

@@ -40,8 +40,8 @@ export function AdminDashboardTemplate(props: {
System overview and statistics
</Text>
</div>
<Button
onClick={onRefresh}
<Button
onClick={onRefresh}
disabled={isLoading}
variant="secondary"
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 {
Search,
Filter,
RefreshCw,
import { Input } from '@/ui/Input';
import { Select } from '@/ui/Select';
import { Table, TableHead, TableBody, TableRow, TableHeader, TableCell } from '@/ui/Table';
import { Button } from '@/ui/Button';
import { Text } from '@/ui/Text';
import {
Search,
Filter,
RefreshCw,
Users,
Shield,
Trash2,
@@ -94,17 +99,18 @@ export function AdminUsersTemplate(props: {
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-white">User Management</h1>
<p className="text-gray-400 mt-1">Manage and monitor all system users</p>
<Text size="2xl" weight="bold" color="text-white">User Management</Text>
<Text size="sm" color="text-gray-400" className="mt-1">Manage and monitor all system users</Text>
</div>
<button
onClick={onRefresh}
<Button
onClick={onRefresh}
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' : ''}`} />
Refresh
</button>
</Button>
</div>
{/* 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">
<AlertTriangle className="w-5 h-5 mt-0.5 flex-shrink-0" />
<div className="flex-1">
<div className="font-medium">Error</div>
<div className="text-sm opacity-90">{error}</div>
<Text weight="medium">Error</Text>
<Text size="sm" className="opacity-90">{error}</Text>
</div>
<button
<Button
onClick={() => {}}
className="text-racing-red hover:opacity-70"
variant="secondary"
className="text-racing-red hover:opacity-70 p-0"
>
×
</button>
</Button>
</div>
)}
@@ -130,52 +137,53 @@ export function AdminUsersTemplate(props: {
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<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>
{(search || roleFilter || statusFilter) && (
<button
<Button
onClick={onClearFilters}
className="text-xs text-primary-blue hover:text-blue-400"
variant="secondary"
className="text-xs p-0"
>
Clear all
</button>
</Button>
)}
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<input
type="text"
placeholder="Search by email or name..."
value={search}
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"
/>
</div>
<select
value={roleFilter}
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"
>
<option value="">All Roles</option>
<option value="owner">Owner</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<select
value={statusFilter}
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"
>
<option value="">All Status</option>
<option value="active">Active</option>
<option value="suspended">Suspended</option>
<option value="deleted">Deleted</option>
</select>
</div>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<Input
type="text"
placeholder="Search by email or name..."
value={search}
onChange={(e) => onSearch(e.target.value)}
className="pl-9"
/>
</div>
<Select
value={roleFilter}
onChange={(e) => onFilterRole(e.target.value)}
options={[
{ value: '', label: 'All Roles' },
{ value: 'owner', label: 'Owner' },
{ value: 'admin', label: 'Admin' },
{ value: 'user', label: 'User' },
]}
/>
<Select
value={statusFilter}
onChange={(e) => onFilterStatus(e.target.value)}
options={[
{ value: '', label: 'All Status' },
{ value: 'active', label: 'Active' },
{ value: 'suspended', label: 'Suspended' },
{ value: 'deleted', label: 'Deleted' },
]}
/>
</div>
</div>
</Card>
@@ -184,113 +192,115 @@ export function AdminUsersTemplate(props: {
{loading ? (
<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="text-gray-400">Loading users...</div>
<Text color="text-gray-400">Loading users...</Text>
</div>
) : !viewData.users || viewData.users.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 space-y-3">
<Users className="w-12 h-12 text-gray-600" />
<div className="text-gray-400">No users found</div>
<button
<Text color="text-gray-400">No users found</Text>
<Button
onClick={onClearFilters}
className="text-primary-blue hover:text-blue-400 text-sm"
variant="secondary"
className="text-sm p-0"
>
Clear filters
</button>
</Button>
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b border-charcoal-outline">
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">User</th>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">Email</th>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">Roles</th>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">Status</th>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">Last Login</th>
<th className="text-left py-3 px-4 text-xs font-medium text-gray-400 uppercase">Actions</th>
</tr>
</thead>
<tbody>
{viewData.users.map((user, index: number) => (
<tr
key={user.id}
className={`border-b border-charcoal-outline/50 hover:bg-iron-gray/30 transition-colors ${index % 2 === 0 ? 'bg-transparent' : 'bg-iron-gray/10'}`}
>
<td className="py-3 px-4">
<div className="flex items-center gap-3">
<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" />
</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>
<Table>
<TableHead>
<TableRow>
<TableHeader>User</TableHeader>
<TableHeader>Email</TableHeader>
<TableHeader>Roles</TableHeader>
<TableHeader>Status</TableHeader>
<TableHeader>Last Login</TableHeader>
<TableHeader>Actions</TableHeader>
</TableRow>
</TableHead>
<TableBody>
{viewData.users.map((user, index: number) => (
<TableRow
key={user.id}
className={index % 2 === 0 ? 'bg-transparent' : 'bg-iron-gray/10'}
>
<TableCell>
<div className="flex items-center gap-3">
<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" />
</div>
</td>
<td className="py-3 px-4">
<div className="text-sm text-gray-300">{user.email}</div>
</td>
<td className="py-3 px-4">
<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 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>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</TableCell>
<TableCell>
<div className="text-sm text-gray-300">{user.email}</div>
</TableCell>
<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>
@@ -300,8 +310,8 @@ export function AdminUsersTemplate(props: {
<Card className="bg-gradient-to-br from-blue-900/20 to-blue-700/10">
<div className="flex items-center justify-between">
<div>
<div className="text-sm text-gray-400 mb-1">Total Users</div>
<div className="text-2xl font-bold text-white">{viewData.total}</div>
<Text size="sm" color="text-gray-400" className="mb-1">Total Users</Text>
<Text size="2xl" weight="bold" color="text-white">{viewData.total}</Text>
</div>
<Users className="w-6 h-6 text-blue-400" />
</div>
@@ -309,10 +319,10 @@ export function AdminUsersTemplate(props: {
<Card className="bg-gradient-to-br from-green-900/20 to-green-700/10">
<div className="flex items-center justify-between">
<div>
<div className="text-sm text-gray-400 mb-1">Active</div>
<div className="text-2xl font-bold text-white">
<Text size="sm" color="text-gray-400" className="mb-1">Active</Text>
<Text size="2xl" weight="bold" color="text-white">
{viewData.activeUserCount}
</div>
</Text>
</div>
<div className="w-6 h-6 text-green-400"></div>
</div>
@@ -320,10 +330,10 @@ export function AdminUsersTemplate(props: {
<Card className="bg-gradient-to-br from-purple-900/20 to-purple-700/10">
<div className="flex items-center justify-between">
<div>
<div className="text-sm text-gray-400 mb-1">Admins</div>
<div className="text-2xl font-bold text-white">
<Text size="sm" color="text-gray-400" className="mb-1">Admins</Text>
<Text size="2xl" weight="bold" color="text-white">
{viewData.adminCount}
</div>
</Text>
</div>
<Shield className="w-6 h-6 text-purple-400" />
</div>

View File

@@ -1,4 +1,18 @@
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 {
viewData: DashboardViewData;
@@ -72,7 +86,7 @@ export function DashboardTemplate({ viewData }: DashboardTemplateProps) {
<span>Flag</span>
Browse Leagues
</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>
View Profile
</a>
@@ -189,7 +203,7 @@ export function DashboardTemplate({ viewData }: DashboardTemplateProps) {
<span>Award</span>
Your Championship Standings
</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>
</a>
</div>
@@ -307,7 +321,7 @@ export function DashboardTemplate({ viewData }: DashboardTemplateProps) {
))}
{friends.length > 6 && (
<a
href="/profile"
href=routes.protected.profile
className="block text-center py-2 text-sm text-primary-blue hover:underline"
>
+{friends.length - 6} more

View File

@@ -95,7 +95,7 @@ export function DriverRankingsTemplate({
</p>
<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>
<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">
{viewData.drivers.map((driver) => {
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 (
<button
@@ -157,7 +149,7 @@ export function DriverRankingsTemplate({
>
{/* Position */}
<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}
</div>
</div>
@@ -190,7 +182,7 @@ export function DriverRankingsTemplate({
{/* Rating */}
<div className="col-span-2 lg:col-span-1 flex items-center justify-center">
<span className="font-mono font-semibold text-white">
{driver.rating.toLocaleString()}
{driver.rating.toString()}
</span>
</div>

View File

@@ -1,56 +1,46 @@
'use client';
import React from 'react';
import { useRouter } from 'next/navigation';
import { Trophy, Users, Award } from 'lucide-react';
import Button from '@/components/ui/Button';
import Heading from '@/components/ui/Heading';
import { DriverLeaderboardPreview } from '@/components/leaderboards/DriverLeaderboardPreview';
import { TeamLeaderboardPreview } from '@/components/leaderboards/TeamLeaderboardPreview';
import type { LeaderboardsViewData } from '@/lib/view-data/LeaderboardsViewData';
import { routes } from '@/lib/routing/RouteConfig';
// ============================================================================
// TYPES
// ============================================================================
interface LeaderboardsTemplateProps {
drivers: {
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;
viewData: LeaderboardsViewData;
}
// ============================================================================
// MAIN TEMPLATE COMPONENT
// ============================================================================
export function LeaderboardsTemplate({
drivers,
teams,
onDriverClick,
onTeamClick,
onNavigateToDrivers,
onNavigateToTeams,
}: LeaderboardsTemplateProps) {
export function LeaderboardsTemplate({ viewData }: LeaderboardsTemplateProps) {
const router = useRouter();
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);
};
return (
<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">
@@ -78,7 +68,7 @@ export function LeaderboardsTemplate({
<div className="flex flex-wrap gap-3">
<Button
variant="secondary"
onClick={onNavigateToDrivers}
onClick={handleNavigateToDrivers}
className="flex items-center gap-2"
>
<Trophy className="w-4 h-4 text-primary-blue" />
@@ -86,7 +76,7 @@ export function LeaderboardsTemplate({
</Button>
<Button
variant="secondary"
onClick={onNavigateToTeams}
onClick={handleNavigateToTeams}
className="flex items-center gap-2"
>
<Users className="w-4 h-4 text-purple-400" />
@@ -97,8 +87,8 @@ export function LeaderboardsTemplate({
</div>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<DriverLeaderboardPreview drivers={drivers} onDriverClick={onDriverClick} onNavigateToDrivers={onNavigateToDrivers} />
<TeamLeaderboardPreview teams={teams} onTeamClick={onTeamClick} onNavigateToTeams={onNavigateToTeams} />
<DriverLeaderboardPreview drivers={viewData.drivers} onDriverClick={handleDriverClick} onNavigateToDrivers={handleNavigateToDrivers} />
<TeamLeaderboardPreview teams={viewData.teams} onTeamClick={handleTeamClick} onNavigateToTeams={handleNavigateToTeams} />
</div>
</div>
);

View File

@@ -521,7 +521,7 @@ export function RacesTemplate({
{filteredRaces.length > 0 && (
<div className="text-center">
<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"
>
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">
{/* Breadcrumb */}
<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" />
<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" />
<span className="text-white">{league.name}</span>
</div>

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