website refactor
This commit is contained in:
@@ -74,7 +74,9 @@
|
||||
"rules": {
|
||||
"gridpilot-rules/mutation-contract": "error",
|
||||
"gridpilot-rules/mutation-must-use-builders": "error",
|
||||
"gridpilot-rules/filename-service-match": "error"
|
||||
"gridpilot-rules/mutation-must-map-errors": "error",
|
||||
"gridpilot-rules/filename-service-match": "error",
|
||||
"gridpilot-rules/clean-error-handling": "error"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -90,7 +92,8 @@
|
||||
"gridpilot-rules/template-no-mutation-props": "error",
|
||||
"gridpilot-rules/template-no-unsafe-html": "error",
|
||||
"gridpilot-rules/component-no-data-manipulation": "error",
|
||||
"gridpilot-rules/no-hardcoded-routes": "error"
|
||||
"gridpilot-rules/no-hardcoded-routes": "error",
|
||||
"gridpilot-rules/no-raw-html-in-app": "warn"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -98,7 +101,8 @@
|
||||
"components/**/*.tsx"
|
||||
],
|
||||
"rules": {
|
||||
"gridpilot-rules/component-no-data-manipulation": "error"
|
||||
"gridpilot-rules/component-no-data-manipulation": "error",
|
||||
"gridpilot-rules/no-raw-html-in-app": "error"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -278,7 +282,8 @@
|
||||
"rules": {
|
||||
"gridpilot-rules/no-nextjs-imports-in-ui": "error",
|
||||
"gridpilot-rules/component-classification": "warn",
|
||||
"gridpilot-rules/no-hardcoded-routes": "error"
|
||||
"gridpilot-rules/no-hardcoded-routes": "error",
|
||||
"gridpilot-rules/no-raw-html-in-app": "error"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { AdminDashboardTemplate } from '@/templates/AdminDashboardTemplate';
|
||||
import { AdminDashboardViewData } from '@/lib/view-data/AdminDashboardViewData';
|
||||
import { AdminDashboardPageQuery } from '@/lib/page-queries/AdminDashboardPageQuery';
|
||||
|
||||
export function AdminDashboardClient() {
|
||||
const [viewData, setViewData] = useState<AdminDashboardViewData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const loadStats = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
const query = new AdminDashboardPageQuery();
|
||||
const result = await query.execute();
|
||||
|
||||
if (result.status === 'ok') {
|
||||
// Page Query already returns View Data via builder
|
||||
setViewData(result.dto);
|
||||
} else if (result.status === 'notFound') {
|
||||
// Handle not found - could show a message or redirect
|
||||
console.error('Access denied - You must be logged in as an Owner or Admin');
|
||||
} else {
|
||||
// Handle error - could show a toast or error message
|
||||
console.error('Failed to load dashboard stats');
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to load stats';
|
||||
console.error(message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadStats();
|
||||
}, []);
|
||||
|
||||
if (!viewData) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-20 space-y-3">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-blue"></div>
|
||||
<div className="text-gray-400">Loading dashboard...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminDashboardTemplate
|
||||
viewData={viewData}
|
||||
onRefresh={loadStats}
|
||||
isLoading={loading}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { AdminUsersTemplate } from '@/templates/AdminUsersTemplate';
|
||||
import { AdminUsersViewData } from '@/templates/AdminUsersViewData';
|
||||
import { AdminUsersPresenter } from '@/lib/presenters/AdminUsersPresenter';
|
||||
import { AdminUsersPageQuery } from '@/lib/page-queries/AdminUsersPageQuery';
|
||||
import { updateUserStatus, deleteUser } from './actions';
|
||||
|
||||
export function AdminUsersClient() {
|
||||
const [viewData, setViewData] = useState<AdminUsersViewData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [search, setSearch] = useState('');
|
||||
const [roleFilter, setRoleFilter] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState('');
|
||||
const [deletingUser, setDeletingUser] = useState<string | null>(null);
|
||||
|
||||
const loadUsers = useCallback(async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const query = new AdminUsersPageQuery();
|
||||
const result = await query.execute({
|
||||
search: search || undefined,
|
||||
role: roleFilter || undefined,
|
||||
status: statusFilter || undefined,
|
||||
page: 1,
|
||||
limit: 50,
|
||||
});
|
||||
|
||||
if (result.status === 'ok') {
|
||||
const data = AdminUsersPresenter.present(result.dto);
|
||||
setViewData(data);
|
||||
} else if (result.status === 'notFound') {
|
||||
setError('Access denied - You must be logged in as an Owner or Admin');
|
||||
} else {
|
||||
setError('Failed to load users');
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to load users';
|
||||
setError(message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [search, roleFilter, statusFilter]);
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
loadUsers();
|
||||
}, 300);
|
||||
|
||||
return () => clearTimeout(timeout);
|
||||
}, [loadUsers]);
|
||||
|
||||
const handleUpdateStatus = async (userId: string, newStatus: string) => {
|
||||
try {
|
||||
await updateUserStatus(userId, newStatus);
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update status');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteUser = async (userId: string) => {
|
||||
if (!confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setDeletingUser(userId);
|
||||
await deleteUser(userId);
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete user');
|
||||
} finally {
|
||||
setDeletingUser(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearFilters = () => {
|
||||
setSearch('');
|
||||
setRoleFilter('');
|
||||
setStatusFilter('');
|
||||
};
|
||||
|
||||
if (!viewData) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-20 space-y-3">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-blue"></div>
|
||||
<div className="text-gray-400">Loading users...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminUsersTemplate
|
||||
viewData={viewData}
|
||||
onRefresh={loadUsers}
|
||||
onSearch={setSearch}
|
||||
onFilterRole={setRoleFilter}
|
||||
onFilterStatus={setStatusFilter}
|
||||
onClearFilters={handleClearFilters}
|
||||
onUpdateStatus={handleUpdateStatus}
|
||||
onDeleteUser={handleDeleteUser}
|
||||
search={search}
|
||||
roleFilter={roleFilter}
|
||||
statusFilter={statusFilter}
|
||||
loading={loading}
|
||||
error={error}
|
||||
deletingUser={deletingUser}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -15,31 +15,29 @@ import { revalidatePath } from 'next/cache';
|
||||
/**
|
||||
* Update user status
|
||||
*/
|
||||
export async function updateUserStatus(userId: string, status: string): Promise<void> {
|
||||
try {
|
||||
const mutation = new UpdateUserStatusMutation();
|
||||
await mutation.execute({ userId, status });
|
||||
|
||||
// Revalidate the users page
|
||||
revalidatePath('/admin/users');
|
||||
} catch (error) {
|
||||
console.error('updateUserStatus failed:', error);
|
||||
export async function updateUserStatus(userId: string, status: string) {
|
||||
const mutation = new UpdateUserStatusMutation();
|
||||
const result = await mutation.execute({ userId, status });
|
||||
|
||||
if (result.isErr()) {
|
||||
console.error('updateUserStatus failed:', result.getError());
|
||||
throw new Error('Failed to update user status');
|
||||
}
|
||||
|
||||
revalidatePath('/admin/users');
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete user
|
||||
*/
|
||||
export async function deleteUser(userId: string): Promise<void> {
|
||||
try {
|
||||
const mutation = new DeleteUserMutation();
|
||||
await mutation.execute({ userId });
|
||||
|
||||
// Revalidate the users page
|
||||
revalidatePath('/admin/users');
|
||||
} catch (error) {
|
||||
console.error('deleteUser failed:', error);
|
||||
export async function deleteUser(userId: string) {
|
||||
const mutation = new DeleteUserMutation();
|
||||
const result = await mutation.execute({ userId });
|
||||
|
||||
if (result.isErr()) {
|
||||
console.error('deleteUser failed:', result.getError());
|
||||
throw new Error('Failed to delete user');
|
||||
}
|
||||
|
||||
revalidatePath('/admin/users');
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { headers } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { createRouteGuard } from '@/lib/auth/createRouteGuard';
|
||||
|
||||
interface AdminLayoutProps {
|
||||
@@ -16,11 +17,14 @@ export default async function AdminLayout({ children }: AdminLayoutProps) {
|
||||
const pathname = headerStore.get('x-pathname') || '/';
|
||||
|
||||
const guard = createRouteGuard();
|
||||
await guard.enforce({ pathname });
|
||||
const result = await guard.enforce({ pathname });
|
||||
if (result.type === 'redirect') {
|
||||
redirect(result.to);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,32 @@
|
||||
import { AdminDashboardClient } from './AdminDashboardClient';
|
||||
import { AdminDashboardPageQuery } from '@/lib/page-queries/AdminDashboardPageQuery';
|
||||
import { AdminDashboardTemplate } from '@/templates/AdminDashboardTemplate';
|
||||
|
||||
export default function AdminPage() {
|
||||
return <AdminDashboardClient />;
|
||||
export default async function AdminPage() {
|
||||
const result = await AdminDashboardPageQuery.execute();
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
if (error === 'notFound') {
|
||||
return (
|
||||
<div className="container mx-auto p-6">
|
||||
<div className="bg-racing-red/10 border border-racing-red text-racing-red px-4 py-3 rounded-lg">
|
||||
Access denied - You must be logged in as an Owner or Admin
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="container mx-auto p-6">
|
||||
<div className="bg-racing-red/10 border border-racing-red text-racing-red px-4 py-3 rounded-lg">
|
||||
Failed to load dashboard: {error}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const viewData = result.unwrap();
|
||||
|
||||
// For now, use empty callbacks. In a real app, these would be Server Actions
|
||||
// that trigger revalidation or navigation
|
||||
return <AdminDashboardTemplate adminDashboardViewData={viewData} onRefresh={() => {}} isLoading={false} />;
|
||||
}
|
||||
109
apps/website/app/admin/users/AdminUsersWrapper.tsx
Normal file
109
apps/website/app/admin/users/AdminUsersWrapper.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
'use client';
|
||||
|
||||
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';
|
||||
|
||||
interface AdminUsersWrapperProps {
|
||||
initialViewData: AdminUsersViewData;
|
||||
}
|
||||
|
||||
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') || '';
|
||||
const statusFilter = searchParams.get('status') || '';
|
||||
|
||||
// Callbacks that update URL (triggers RSC re-render)
|
||||
const handleSearch = useCallback((newSearch: string) => {
|
||||
const params = new URLSearchParams(searchParams);
|
||||
if (newSearch) params.set('search', newSearch);
|
||||
else params.delete('search');
|
||||
params.delete('page'); // Reset to page 1
|
||||
router.push(`/admin/users?${params.toString()}`);
|
||||
}, [router, searchParams]);
|
||||
|
||||
const handleFilterRole = useCallback((role: string) => {
|
||||
const params = new URLSearchParams(searchParams);
|
||||
if (role) params.set('role', role);
|
||||
else params.delete('role');
|
||||
params.delete('page');
|
||||
router.push(`/admin/users?${params.toString()}`);
|
||||
}, [router, searchParams]);
|
||||
|
||||
const handleFilterStatus = useCallback((status: string) => {
|
||||
const params = new URLSearchParams(searchParams);
|
||||
if (status) params.set('status', status);
|
||||
else params.delete('status');
|
||||
params.delete('page');
|
||||
router.push(`/admin/users?${params.toString()}`);
|
||||
}, [router, searchParams]);
|
||||
|
||||
const handleClearFilters = useCallback(() => {
|
||||
router.push('/admin/users');
|
||||
}, [router]);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
router.refresh();
|
||||
}, [router]);
|
||||
|
||||
// Mutation callbacks (call Server Actions)
|
||||
const handleUpdateStatus = useCallback(async (userId: string, newStatus: string) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
await updateUserStatus(userId, newStatus);
|
||||
// Revalidate data
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update status');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [router]);
|
||||
|
||||
const handleDeleteUser = useCallback(async (userId: string) => {
|
||||
if (!confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setDeletingUser(userId);
|
||||
await deleteUser(userId);
|
||||
// Revalidate data
|
||||
router.refresh();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete user');
|
||||
} finally {
|
||||
setDeletingUser(null);
|
||||
}
|
||||
}, [router]);
|
||||
|
||||
return (
|
||||
<AdminUsersTemplate
|
||||
adminUsersViewData={initialViewData}
|
||||
onRefresh={handleRefresh}
|
||||
onSearch={handleSearch}
|
||||
onFilterRole={handleFilterRole}
|
||||
onFilterStatus={handleFilterStatus}
|
||||
onClearFilters={handleClearFilters}
|
||||
onUpdateStatus={handleUpdateStatus}
|
||||
onDeleteUser={handleDeleteUser}
|
||||
search={search}
|
||||
roleFilter={roleFilter}
|
||||
statusFilter={statusFilter}
|
||||
loading={loading}
|
||||
error={error}
|
||||
deletingUser={deletingUser}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,51 @@
|
||||
import { AdminUsersClient } from '../AdminUsersClient';
|
||||
import { AdminUsersPageQuery } from '@/lib/page-queries/AdminUsersPageQuery';
|
||||
import { AdminUsersWrapper } from './AdminUsersWrapper';
|
||||
|
||||
export default function AdminUsers() {
|
||||
return <AdminUsersClient />;
|
||||
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,
|
||||
};
|
||||
|
||||
// Execute PageQuery using static method
|
||||
const result = await AdminUsersPageQuery.execute(query);
|
||||
|
||||
// Handle errors
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
if (error === 'notFound') {
|
||||
return (
|
||||
<div className="container mx-auto p-6">
|
||||
<div className="bg-racing-red/10 border border-racing-red text-racing-red px-4 py-3 rounded-lg">
|
||||
Access denied - You must be logged in as an Owner or Admin
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="container mx-auto p-6">
|
||||
<div className="bg-racing-red/10 border border-racing-red text-racing-red px-4 py-3 rounded-lg">
|
||||
Failed to load users: {error}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const viewData = result.unwrap();
|
||||
|
||||
// Pass to client wrapper for UI interactions
|
||||
return <AdminUsersWrapper initialViewData={viewData} />;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Forgot Password Client Component
|
||||
*
|
||||
* Handles client-side forgot password flow.
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { ForgotPasswordViewData } from '@/lib/builders/view-data/ForgotPasswordViewDataBuilder';
|
||||
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';
|
||||
|
||||
interface ForgotPasswordClientProps {
|
||||
viewData: ForgotPasswordViewData;
|
||||
}
|
||||
|
||||
export function ForgotPasswordClient({ viewData }: ForgotPasswordClientProps) {
|
||||
// Build ViewModel from ViewData
|
||||
const [viewModel, setViewModel] = useState<ForgotPasswordViewModel>(() =>
|
||||
ForgotPasswordViewModelBuilder.build(viewData)
|
||||
);
|
||||
|
||||
const [formData, setFormData] = useState({ email: '' });
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
// 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,
|
||||
});
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
setViewModel(prev => prev.withMutationState(false, error));
|
||||
return;
|
||||
}
|
||||
|
||||
// Success
|
||||
const data = result.unwrap();
|
||||
setViewModel(prev => prev.withSuccess(data.message, data.magicLink || null));
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to send reset link';
|
||||
setViewModel(prev => prev.withMutationState(false, errorMessage));
|
||||
}
|
||||
};
|
||||
|
||||
// Build viewData for template
|
||||
const templateViewData: ForgotPasswordViewData = {
|
||||
...viewData,
|
||||
showSuccess: viewModel.showSuccess,
|
||||
successMessage: viewModel.successMessage || undefined,
|
||||
magicLink: viewModel.magicLink || undefined,
|
||||
formState: viewModel.formState,
|
||||
isSubmitting: viewModel.isSubmitting,
|
||||
submitError: viewModel.submitError,
|
||||
};
|
||||
|
||||
return (
|
||||
<ForgotPasswordTemplate
|
||||
viewData={templateViewData}
|
||||
formActions={{
|
||||
setFormData,
|
||||
handleSubmit,
|
||||
setShowSuccess: (show) => {
|
||||
if (!show) {
|
||||
// Reset to initial state
|
||||
setViewModel(prev => ForgotPasswordViewModelBuilder.build(viewData));
|
||||
}
|
||||
},
|
||||
}}
|
||||
mutationState={{
|
||||
isPending: viewModel.mutationPending,
|
||||
error: viewModel.mutationError,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,250 +1,34 @@
|
||||
'use client';
|
||||
/**
|
||||
* Forgot Password Page
|
||||
*
|
||||
* RSC composition pattern:
|
||||
* 1. PageQuery executes to get ViewData
|
||||
* 2. Client component renders with ViewData
|
||||
*/
|
||||
|
||||
import { useState, useEffect, FormEvent, type ChangeEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useForgotPassword } from "@/lib/hooks/auth/useForgotPassword";
|
||||
import Link from 'next/link';
|
||||
import { motion } from 'framer-motion';
|
||||
import {
|
||||
Mail,
|
||||
ArrowLeft,
|
||||
AlertCircle,
|
||||
Flag,
|
||||
Shield,
|
||||
CheckCircle2,
|
||||
} from 'lucide-react';
|
||||
import { ForgotPasswordPageQuery } from '@/lib/page-queries/auth/ForgotPasswordPageQuery';
|
||||
import { ForgotPasswordClient } from './ForgotPasswordClient';
|
||||
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
export default async function ForgotPasswordPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<URLSearchParams>;
|
||||
}) {
|
||||
// Execute PageQuery
|
||||
const params = await searchParams;
|
||||
const queryResult = await ForgotPasswordPageQuery.execute(params);
|
||||
|
||||
interface FormErrors {
|
||||
email?: string;
|
||||
submit?: string;
|
||||
}
|
||||
|
||||
interface SuccessState {
|
||||
message: string;
|
||||
magicLink?: string;
|
||||
}
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
const router = useRouter();
|
||||
const { session } = useAuth();
|
||||
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [success, setSuccess] = useState<SuccessState | null>(null);
|
||||
const [formData, setFormData] = useState({
|
||||
email: '',
|
||||
});
|
||||
|
||||
// Check if user is already authenticated
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
router.replace('/dashboard');
|
||||
}
|
||||
}, [session, router]);
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: FormErrors = {};
|
||||
|
||||
if (!formData.email.trim()) {
|
||||
newErrors.email = 'Email is required';
|
||||
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
|
||||
newErrors.email = 'Invalid email format';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
// Use forgot password mutation hook
|
||||
const forgotPasswordMutation = useForgotPassword({
|
||||
onSuccess: (result) => {
|
||||
setSuccess({
|
||||
message: result.message,
|
||||
magicLink: result.magicLink,
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
setErrors({
|
||||
submit: error.message || 'Failed to send reset link. Please try again.',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (forgotPasswordMutation.isPending) return;
|
||||
|
||||
if (!validateForm()) return;
|
||||
|
||||
setErrors({});
|
||||
setSuccess(null);
|
||||
|
||||
try {
|
||||
await forgotPasswordMutation.mutateAsync({ email: formData.email });
|
||||
} catch (error) {
|
||||
// Error handling is done in the mutation's onError callback
|
||||
}
|
||||
};
|
||||
|
||||
// Loading state from mutation
|
||||
const loading = forgotPasswordMutation.isPending;
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex items-center justify-center px-4 py-12">
|
||||
{/* Background Pattern */}
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary-blue/5 via-transparent to-purple-600/5" />
|
||||
<div className="absolute inset-0 opacity-5">
|
||||
<div className="absolute inset-0" style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
|
||||
}} />
|
||||
if (queryResult.isErr()) {
|
||||
// Handle query error
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="text-red-400">Failed to load forgot password page</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
<div className="relative w-full max-w-md">
|
||||
{/* Header */}
|
||||
<div className="text-center mb-8">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
|
||||
<Flag className="w-8 h-8 text-primary-blue" />
|
||||
</div>
|
||||
<Heading level={1} className="mb-2">Reset Password</Heading>
|
||||
<p className="text-gray-400">
|
||||
Enter your email and we'll send you a reset link
|
||||
</p>
|
||||
</div>
|
||||
const viewData = queryResult.unwrap();
|
||||
|
||||
<Card className="relative overflow-hidden">
|
||||
{/* Background accent */}
|
||||
<div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />
|
||||
|
||||
{!success ? (
|
||||
<form onSubmit={handleSubmit} className="relative space-y-5">
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Email Address
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, email: e.target.value })}
|
||||
error={!!errors.email}
|
||||
errorMessage={errors.email}
|
||||
placeholder="you@example.com"
|
||||
disabled={loading}
|
||||
className="pl-10"
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{errors.submit && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="flex items-start gap-3 p-3 rounded-lg bg-red-500/10 border border-red-500/30"
|
||||
>
|
||||
<AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
|
||||
<p className="text-sm text-red-400">{errors.submit}</p>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={loading}
|
||||
className="w-full flex items-center justify-center gap-2"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
Sending...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Shield className="w-4 h-4" />
|
||||
Send Reset Link
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Back to Login */}
|
||||
<div className="text-center">
|
||||
<Link
|
||||
href="/auth/login"
|
||||
className="text-sm text-primary-blue hover:underline flex items-center justify-center gap-1"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
Back to Login
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="relative space-y-4"
|
||||
>
|
||||
<div className="flex items-start gap-3 p-4 rounded-lg bg-performance-green/10 border border-performance-green/30">
|
||||
<CheckCircle2 className="w-6 h-6 text-performance-green flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm text-performance-green font-medium">{success.message}</p>
|
||||
{success.magicLink && (
|
||||
<div className="mt-2">
|
||||
<p className="text-xs text-gray-400 mb-1">Development Mode - Magic Link:</p>
|
||||
<div className="bg-iron-gray p-2 rounded border border-charcoal-outline">
|
||||
<code className="text-xs text-primary-blue break-all">
|
||||
{success.magicLink}
|
||||
</code>
|
||||
</div>
|
||||
<p className="text-[10px] text-gray-500 mt-1">
|
||||
In production, this would be sent via email
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => router.push('/auth/login')}
|
||||
className="w-full"
|
||||
>
|
||||
Return to Login
|
||||
</Button>
|
||||
</motion.div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Trust Indicators */}
|
||||
<div className="mt-6 flex items-center justify-center gap-6 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Secure reset process</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
<span>15 minute expiration</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="mt-6 text-center text-xs text-gray-500">
|
||||
Need help?{' '}
|
||||
<Link href="/support" className="text-gray-400 hover:underline">
|
||||
Contact support
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
// Render client component with ViewData
|
||||
return <ForgotPasswordClient viewData={viewData} />;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { headers } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { createRouteGuard } from '@/lib/auth/createRouteGuard';
|
||||
|
||||
interface AuthLayoutProps {
|
||||
@@ -20,11 +21,14 @@ export default async function AuthLayout({ children }: AuthLayoutProps) {
|
||||
const pathname = headerStore.get('x-pathname') || '/';
|
||||
|
||||
const guard = createRouteGuard();
|
||||
await guard.enforce({ pathname });
|
||||
const result = await guard.enforce({ pathname });
|
||||
if (result.type === 'redirect') {
|
||||
redirect(result.to);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite flex items-center justify-center p-4">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
284
apps/website/app/auth/login/LoginClient.tsx
Normal file
284
apps/website/app/auth/login/LoginClient.tsx
Normal file
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* Login Client Component
|
||||
*
|
||||
* Handles client-side login flow using the LoginFlowController.
|
||||
* Deterministic state machine per docs/architecture/website/LOGIN_FLOW_STATE_MACHINE.md
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { LoginFlowController, LoginState } from '@/lib/auth/LoginFlowController';
|
||||
import { LoginViewData } from '@/lib/builders/view-data/LoginViewDataBuilder';
|
||||
import { LoginTemplate } from '@/templates/auth/LoginTemplate';
|
||||
import { LoginMutation } from '@/lib/mutations/auth/LoginMutation';
|
||||
import { validateLoginForm, type LoginFormValues } from '@/lib/utils/validation';
|
||||
import { LoginViewModelBuilder } from '@/lib/builders/view-models/LoginViewModelBuilder';
|
||||
import { LoginViewModel } from '@/lib/view-models/auth/LoginViewModel';
|
||||
|
||||
interface LoginClientProps {
|
||||
viewData: LoginViewData;
|
||||
}
|
||||
|
||||
export function LoginClient({ viewData }: LoginClientProps) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refreshSession, session } = useAuth();
|
||||
|
||||
// Build ViewModel from ViewData
|
||||
const [viewModel, setViewModel] = useState<LoginViewModel>(() =>
|
||||
LoginViewModelBuilder.build(viewData)
|
||||
);
|
||||
|
||||
// Login flow controller
|
||||
const controller = useMemo(() => {
|
||||
const returnTo = searchParams.get('returnTo') ?? '/dashboard';
|
||||
return new LoginFlowController(session, returnTo);
|
||||
}, [session, searchParams]);
|
||||
|
||||
// Check controller state on mount and session changes
|
||||
useEffect(() => {
|
||||
const action = controller.getNextAction();
|
||||
|
||||
if (action.type === 'REDIRECT') {
|
||||
router.replace(action.path);
|
||||
}
|
||||
}, [controller, router]);
|
||||
|
||||
// Handle form field changes
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value, type } = e.target;
|
||||
const checked = 'checked' in e.target ? e.target.checked : false;
|
||||
const fieldValue = type === 'checkbox' ? checked : value;
|
||||
|
||||
setViewModel(prev => {
|
||||
const newFormState = {
|
||||
...prev.formState,
|
||||
fields: {
|
||||
...prev.formState.fields,
|
||||
[name]: {
|
||||
...prev.formState.fields[name as keyof typeof prev.formState.fields],
|
||||
value: fieldValue,
|
||||
touched: true,
|
||||
error: undefined,
|
||||
},
|
||||
},
|
||||
};
|
||||
return prev.withFormState(newFormState);
|
||||
});
|
||||
};
|
||||
|
||||
// Handle form submission
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
const values: LoginFormValues = {
|
||||
email: viewModel.formState.fields.email.value as string,
|
||||
password: viewModel.formState.fields.password.value as string,
|
||||
rememberMe: viewModel.formState.fields.rememberMe.value as boolean,
|
||||
};
|
||||
|
||||
// Validate form
|
||||
const errors = validateLoginForm(values);
|
||||
const hasErrors = Object.keys(errors).length > 0;
|
||||
|
||||
if (hasErrors) {
|
||||
setViewModel(prev => {
|
||||
const newFormState = {
|
||||
...prev.formState,
|
||||
isValid: false,
|
||||
submitCount: prev.formState.submitCount + 1,
|
||||
fields: {
|
||||
...prev.formState.fields,
|
||||
email: {
|
||||
...prev.formState.fields.email,
|
||||
error: errors.email,
|
||||
touched: true,
|
||||
},
|
||||
password: {
|
||||
...prev.formState.fields.password,
|
||||
error: errors.password,
|
||||
touched: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
return prev.withFormState(newFormState);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Update submitting state
|
||||
setViewModel(prev => prev.withMutationState(true, null));
|
||||
|
||||
try {
|
||||
// Execute login mutation
|
||||
const mutation = new LoginMutation();
|
||||
const result = await mutation.execute({
|
||||
email: values.email,
|
||||
password: values.password,
|
||||
rememberMe: values.rememberMe,
|
||||
});
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
setViewModel(prev => {
|
||||
const newFormState = {
|
||||
...prev.formState,
|
||||
isSubmitting: false,
|
||||
submitError: error,
|
||||
};
|
||||
return prev.withFormState(newFormState).withMutationState(false, error);
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showErrorDetails: true,
|
||||
}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Success - refresh session and transition
|
||||
await refreshSession();
|
||||
|
||||
// Transition to post-auth state
|
||||
controller.transitionToPostAuth();
|
||||
const action = controller.getNextAction();
|
||||
|
||||
if (action.type === 'REDIRECT') {
|
||||
router.push(action.path);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Login failed';
|
||||
setViewModel(prev => {
|
||||
const newFormState = {
|
||||
...prev.formState,
|
||||
isSubmitting: false,
|
||||
submitError: errorMessage,
|
||||
};
|
||||
return prev.withFormState(newFormState).withMutationState(false, errorMessage);
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showErrorDetails: true,
|
||||
}));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle password visibility
|
||||
const togglePassword = () => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showPassword: !prev.uiState.showPassword,
|
||||
}));
|
||||
};
|
||||
|
||||
// Dismiss error details
|
||||
const dismissErrorDetails = () => {
|
||||
setViewModel(prev => {
|
||||
const newFormState = {
|
||||
...prev.formState,
|
||||
submitError: undefined,
|
||||
};
|
||||
return prev.withFormState(newFormState).withUIState({
|
||||
...prev.uiState,
|
||||
showErrorDetails: false,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Get current state from controller
|
||||
const state = controller.getState();
|
||||
|
||||
// If user is authenticated with permissions, show loading
|
||||
if (state === LoginState.AUTHENTICATED_WITH_PERMISSIONS) {
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="w-8 h-8 border-2 border-primary-blue border-t-transparent rounded-full animate-spin" />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
// If user has insufficient permissions, show permission error
|
||||
if (state === LoginState.AUTHENTICATED_WITHOUT_PERMISSIONS) {
|
||||
return (
|
||||
<LoginTemplate
|
||||
viewData={{
|
||||
...viewData,
|
||||
hasInsufficientPermissions: true,
|
||||
showPassword: viewModel.showPassword,
|
||||
showErrorDetails: viewModel.showErrorDetails,
|
||||
formState: viewModel.formState,
|
||||
isSubmitting: viewModel.isSubmitting,
|
||||
submitError: viewModel.submitError,
|
||||
}}
|
||||
formActions={{
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
setFormState: (state) => {
|
||||
if (typeof state === 'function') {
|
||||
const newState = state(viewModel.formState);
|
||||
setViewModel(prev => prev.withFormState(newState));
|
||||
} else {
|
||||
setViewModel(prev => prev.withFormState(state));
|
||||
}
|
||||
},
|
||||
setShowPassword: togglePassword,
|
||||
setShowErrorDetails: (show) => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showErrorDetails: show,
|
||||
}));
|
||||
},
|
||||
}}
|
||||
mutationState={{
|
||||
isPending: viewModel.mutationPending,
|
||||
error: viewModel.mutationError,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Show login form
|
||||
return (
|
||||
<LoginTemplate
|
||||
viewData={{
|
||||
...viewData,
|
||||
showPassword: viewModel.showPassword,
|
||||
showErrorDetails: viewModel.showErrorDetails,
|
||||
formState: viewModel.formState,
|
||||
isSubmitting: viewModel.isSubmitting,
|
||||
submitError: viewModel.submitError,
|
||||
}}
|
||||
formActions={{
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
setFormState: (state) => {
|
||||
if (typeof state === 'function') {
|
||||
const newState = state(viewModel.formState);
|
||||
setViewModel(prev => prev.withFormState(newState));
|
||||
} else {
|
||||
setViewModel(prev => prev.withFormState(state));
|
||||
}
|
||||
},
|
||||
setShowPassword: togglePassword,
|
||||
setShowErrorDetails: (show) => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showErrorDetails: show,
|
||||
}));
|
||||
},
|
||||
}}
|
||||
mutationState={{
|
||||
isPending: viewModel.mutationPending,
|
||||
error: viewModel.mutationError,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,426 +1,34 @@
|
||||
'use client';
|
||||
/**
|
||||
* Login Page
|
||||
*
|
||||
* RSC composition pattern:
|
||||
* 1. PageQuery executes to get ViewData
|
||||
* 2. Client component renders with ViewData
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
Mail,
|
||||
Lock,
|
||||
Eye,
|
||||
EyeOff,
|
||||
LogIn,
|
||||
AlertCircle,
|
||||
Flag,
|
||||
Shield,
|
||||
} from 'lucide-react';
|
||||
import { LoginPageQuery } from '@/lib/page-queries/auth/LoginPageQuery';
|
||||
import { LoginClient } from './LoginClient';
|
||||
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useLogin } from "@/lib/hooks/auth/useLogin";
|
||||
import AuthWorkflowMockup from '@/components/auth/AuthWorkflowMockup';
|
||||
import UserRolesPreview from '@/components/auth/UserRolesPreview';
|
||||
import { EnhancedFormError } from '@/components/errors/EnhancedFormError';
|
||||
import { useEnhancedForm } from '@/lib/hooks/useEnhancedForm';
|
||||
import { validateLoginForm, type LoginFormValues } from '@/lib/utils/validation';
|
||||
import { logErrorWithContext } from '@/lib/utils/errorUtils';
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
export default async function LoginPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<URLSearchParams>;
|
||||
}) {
|
||||
// Execute PageQuery
|
||||
const params = await searchParams;
|
||||
const queryResult = await LoginPageQuery.execute(params);
|
||||
|
||||
// Template component for login UI
|
||||
function LoginTemplate({ data }: { data: { returnTo: string; hasInsufficientPermissions: boolean; showPassword: boolean; showErrorDetails: boolean; formState: any; handleChange: any; handleSubmit: any; setFormState: any; setShowPassword: any; setShowErrorDetails: any; } }) {
|
||||
const {
|
||||
returnTo,
|
||||
hasInsufficientPermissions,
|
||||
showPassword,
|
||||
showErrorDetails,
|
||||
formState,
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
setFormState,
|
||||
setShowPassword,
|
||||
setShowErrorDetails,
|
||||
} = data;
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex">
|
||||
{/* Background Pattern */}
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary-blue/5 via-transparent to-purple-600/5" />
|
||||
<div className="absolute inset-0 opacity-5">
|
||||
<div className="absolute inset-0" style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
|
||||
}} />
|
||||
if (queryResult.isErr()) {
|
||||
// Handle query error
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="text-red-400">Failed to load login page</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
{/* Left Side - Info Panel (Hidden on mobile) */}
|
||||
<div className="hidden lg:flex lg:w-1/2 relative items-center justify-center p-12">
|
||||
<div className="max-w-lg">
|
||||
{/* Logo */}
|
||||
<div className="flex items-center gap-3 mb-8">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30">
|
||||
<Flag className="w-6 h-6 text-primary-blue" />
|
||||
</div>
|
||||
<span className="text-2xl font-bold text-white">GridPilot</span>
|
||||
</div>
|
||||
const viewData = queryResult.unwrap();
|
||||
|
||||
<Heading level={2} className="text-white mb-4">
|
||||
Your Sim Racing Infrastructure
|
||||
</Heading>
|
||||
|
||||
<p className="text-gray-400 text-lg mb-8">
|
||||
Manage leagues, track performance, join teams, and compete with drivers worldwide. One account, multiple roles.
|
||||
</p>
|
||||
|
||||
{/* Role Cards */}
|
||||
<UserRolesPreview variant="full" />
|
||||
|
||||
{/* Workflow Mockup */}
|
||||
<AuthWorkflowMockup />
|
||||
|
||||
{/* Trust Indicators */}
|
||||
<div className="mt-8 flex items-center gap-6 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Secure login</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm">iRacing verified</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Side - Login Form */}
|
||||
<div className="flex-1 flex items-center justify-center px-4 py-12">
|
||||
<div className="relative w-full max-w-md">
|
||||
{/* Mobile Logo/Header */}
|
||||
<div className="text-center mb-8 lg:hidden">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
|
||||
<Flag className="w-8 h-8 text-primary-blue" />
|
||||
</div>
|
||||
<Heading level={1} className="mb-2">Welcome Back</Heading>
|
||||
<p className="text-gray-400">
|
||||
Sign in to continue to GridPilot
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Desktop Header */}
|
||||
<div className="hidden lg:block text-center mb-8">
|
||||
<Heading level={2} className="mb-2">Welcome Back</Heading>
|
||||
<p className="text-gray-400">
|
||||
Sign in to access your racing dashboard
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="relative overflow-hidden">
|
||||
{/* Background accent */}
|
||||
<div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />
|
||||
|
||||
<form onSubmit={handleSubmit} className="relative space-y-5">
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Email Address
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
value={formState.fields.email.value}
|
||||
onChange={handleChange}
|
||||
error={!!formState.fields.email.error}
|
||||
errorMessage={formState.fields.email.error}
|
||||
placeholder="you@example.com"
|
||||
disabled={formState.isSubmitting}
|
||||
className="pl-10"
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Password */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-300">
|
||||
Password
|
||||
</label>
|
||||
<Link href="/auth/forgot-password" className="text-xs text-primary-blue hover:underline">
|
||||
Forgot password?
|
||||
</Link>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={formState.fields.password.value}
|
||||
onChange={handleChange}
|
||||
error={!!formState.fields.password.error}
|
||||
errorMessage={formState.fields.password.error}
|
||||
placeholder="••••••••"
|
||||
disabled={formState.isSubmitting}
|
||||
className="pl-10 pr-10"
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Remember Me */}
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
id="rememberMe"
|
||||
name="rememberMe"
|
||||
type="checkbox"
|
||||
checked={formState.fields.rememberMe?.value ?? false}
|
||||
onChange={handleChange}
|
||||
disabled={formState.isSubmitting}
|
||||
className="w-4 h-4 rounded border-charcoal-outline bg-iron-gray text-primary-blue focus:ring-primary-blue focus:ring-offset-0"
|
||||
/>
|
||||
<span className="text-sm text-gray-300">Keep me signed in</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Insufficient Permissions Message */}
|
||||
<AnimatePresence>
|
||||
{hasInsufficientPermissions && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
className="p-4 rounded-lg bg-warning-amber/10 border border-warning-amber/30"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertCircle className="w-5 h-5 text-warning-amber flex-shrink-0 mt-0.5" />
|
||||
<div className="text-sm text-gray-300">
|
||||
<strong className="text-warning-amber">Insufficient Permissions</strong>
|
||||
<p className="mt-1">
|
||||
You don't have permission to access that page. Please log in with an account that has the required role.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Enhanced Error Display */}
|
||||
<AnimatePresence>
|
||||
{formState.submitError && (
|
||||
<EnhancedFormError
|
||||
error={new Error(formState.submitError)}
|
||||
onDismiss={() => {
|
||||
// Clear the error by setting submitError to undefined
|
||||
setFormState((prev: typeof formState) => ({ ...prev, submitError: undefined }));
|
||||
}}
|
||||
showDeveloperDetails={showErrorDetails}
|
||||
/>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={formState.isSubmitting}
|
||||
className="w-full flex items-center justify-center gap-2"
|
||||
>
|
||||
{formState.isSubmitting ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
Signing in...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<LogIn className="w-4 h-4" />
|
||||
Sign In
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="relative my-6">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-charcoal-outline" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs">
|
||||
<span className="px-4 bg-iron-gray text-gray-500">or continue with</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sign Up Link */}
|
||||
<p className="mt-6 text-center text-sm text-gray-400">
|
||||
Don't have an account?{' '}
|
||||
<Link
|
||||
href={`/auth/signup${returnTo !== '/dashboard' ? `?returnTo=${encodeURIComponent(returnTo)}` : ''}`}
|
||||
className="text-primary-blue hover:underline font-medium"
|
||||
>
|
||||
Create one
|
||||
</Link>
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
{/* Name Immutability Notice */}
|
||||
<div className="mt-6 p-4 rounded-lg bg-iron-gray/30 border border-charcoal-outline">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertCircle className="w-5 h-5 text-gray-400 flex-shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-gray-400">
|
||||
<strong>Note:</strong> Your display name cannot be changed after signup. Please ensure it's correct when creating your account.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="mt-6 text-center text-xs text-gray-500">
|
||||
By signing in, you agree to our{' '}
|
||||
<Link href="/terms" className="text-gray-400 hover:underline">Terms of Service</Link>
|
||||
{' '}and{' '}
|
||||
<Link href="/privacy" className="text-gray-400 hover:underline">Privacy Policy</Link>
|
||||
</p>
|
||||
|
||||
{/* Mobile Role Info */}
|
||||
<UserRolesPreview variant="compact" />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refreshSession, session } = useAuth();
|
||||
const returnTo = searchParams.get('returnTo') ?? '/dashboard';
|
||||
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showErrorDetails, setShowErrorDetails] = useState(false);
|
||||
const [hasInsufficientPermissions, setHasInsufficientPermissions] = useState(false);
|
||||
|
||||
// Use login mutation hook
|
||||
const loginMutation = useLogin({
|
||||
onSuccess: async () => {
|
||||
// Refresh session in context so header updates immediately
|
||||
await refreshSession();
|
||||
router.push(returnTo);
|
||||
},
|
||||
onError: (error) => {
|
||||
// Show error details toggle in development
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
setShowErrorDetails(true);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Check if user is already authenticated
|
||||
useEffect(() => {
|
||||
console.log('[LoginPage] useEffect running', {
|
||||
session: session ? 'exists' : 'null',
|
||||
returnTo: searchParams.get('returnTo'),
|
||||
pathname: window.location.pathname,
|
||||
search: window.location.search,
|
||||
});
|
||||
|
||||
if (session) {
|
||||
// Check if this is a returnTo redirect (user lacks permissions)
|
||||
const isPermissionRedirect = searchParams.get('returnTo') !== null;
|
||||
|
||||
console.log('[LoginPage] Authenticated user check', {
|
||||
isPermissionRedirect,
|
||||
returnTo: searchParams.get('returnTo'),
|
||||
});
|
||||
|
||||
if (isPermissionRedirect) {
|
||||
// User was redirected here due to insufficient permissions
|
||||
// Show permission error instead of redirecting
|
||||
console.log('[LoginPage] Showing permission error');
|
||||
setHasInsufficientPermissions(true);
|
||||
} else {
|
||||
// User navigated here directly while authenticated, redirect to dashboard
|
||||
console.log('[LoginPage] Redirecting to dashboard');
|
||||
router.replace('/dashboard');
|
||||
}
|
||||
}
|
||||
}, [session, router, searchParams]);
|
||||
|
||||
// Use enhanced form hook
|
||||
const {
|
||||
formState,
|
||||
setFormState,
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
} = useEnhancedForm<LoginFormValues>({
|
||||
initialValues: {
|
||||
email: '',
|
||||
password: '',
|
||||
rememberMe: false,
|
||||
},
|
||||
validate: validateLoginForm,
|
||||
component: 'LoginPage',
|
||||
onSubmit: async (values) => {
|
||||
// Log the attempt for debugging
|
||||
logErrorWithContext(
|
||||
{ message: 'Login attempt', values: { ...values, password: '[REDACTED]' } },
|
||||
{
|
||||
component: 'LoginPage',
|
||||
action: 'login-submit',
|
||||
formData: { ...values, password: '[REDACTED]' },
|
||||
}
|
||||
);
|
||||
|
||||
await loginMutation.mutateAsync({
|
||||
email: values.email,
|
||||
password: values.password,
|
||||
rememberMe: values.rememberMe,
|
||||
});
|
||||
},
|
||||
onError: (error, values) => {
|
||||
// Error handling is done in the mutation's onError callback
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Reset error details on success
|
||||
setShowErrorDetails(false);
|
||||
},
|
||||
});
|
||||
|
||||
// Prepare template data
|
||||
const templateData = {
|
||||
returnTo,
|
||||
hasInsufficientPermissions,
|
||||
showPassword,
|
||||
showErrorDetails,
|
||||
formState,
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
setFormState,
|
||||
setShowPassword,
|
||||
setShowErrorDetails,
|
||||
};
|
||||
|
||||
// Mutation state for wrapper
|
||||
const isLoading = loginMutation.isPending;
|
||||
const error = loginMutation.error;
|
||||
|
||||
return (
|
||||
<StatefulPageWrapper
|
||||
data={templateData}
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
retry={() => loginMutation.mutate({ email: '', password: '', rememberMe: false })}
|
||||
Template={LoginTemplate}
|
||||
loading={{ variant: 'full-screen', message: 'Loading login...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
/>
|
||||
);
|
||||
// Render client component with ViewData
|
||||
return <LoginClient viewData={viewData} />;
|
||||
}
|
||||
139
apps/website/app/auth/reset-password/ResetPasswordClient.tsx
Normal file
139
apps/website/app/auth/reset-password/ResetPasswordClient.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Reset Password Client Component
|
||||
*
|
||||
* Handles client-side reset password flow.
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { ResetPasswordViewData } from '@/lib/builders/view-data/ResetPasswordViewDataBuilder';
|
||||
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';
|
||||
|
||||
interface ResetPasswordClientProps {
|
||||
viewData: ResetPasswordViewData;
|
||||
}
|
||||
|
||||
export function ResetPasswordClient({ viewData }: ResetPasswordClientProps) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
// Build ViewModel from ViewData
|
||||
const [viewModel, setViewModel] = useState<ResetPasswordViewModel>(() =>
|
||||
ResetPasswordViewModelBuilder.build(viewData)
|
||||
);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
newPassword: '',
|
||||
confirmPassword: ''
|
||||
});
|
||||
|
||||
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'));
|
||||
return;
|
||||
}
|
||||
|
||||
// Update submitting state
|
||||
setViewModel(prev => prev.withMutationState(true, null));
|
||||
|
||||
try {
|
||||
const token = searchParams.get('token');
|
||||
if (!token) {
|
||||
setViewModel(prev => prev.withMutationState(false, 'Invalid reset link'));
|
||||
return;
|
||||
}
|
||||
|
||||
// Execute reset password mutation
|
||||
const mutation = new ResetPasswordMutation();
|
||||
const result = await mutation.execute({
|
||||
token,
|
||||
newPassword: formData.newPassword,
|
||||
});
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
setViewModel(prev => prev.withMutationState(false, error));
|
||||
return;
|
||||
}
|
||||
|
||||
// Success
|
||||
const data = result.unwrap();
|
||||
setViewModel(prev => prev.withSuccess(data.message));
|
||||
|
||||
// Redirect to login after a delay
|
||||
setTimeout(() => {
|
||||
router.push('/auth/login');
|
||||
}, 3000);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to reset password';
|
||||
setViewModel(prev => prev.withMutationState(false, errorMessage));
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle password visibility
|
||||
const togglePassword = () => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showPassword: !prev.uiState.showPassword,
|
||||
}));
|
||||
};
|
||||
|
||||
const toggleConfirmPassword = () => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showConfirmPassword: !prev.uiState.showConfirmPassword,
|
||||
}));
|
||||
};
|
||||
|
||||
// Build viewData for template
|
||||
const templateViewData: ResetPasswordViewData = {
|
||||
...viewData,
|
||||
showSuccess: viewModel.showSuccess,
|
||||
successMessage: viewModel.successMessage || undefined,
|
||||
formState: viewModel.formState,
|
||||
isSubmitting: viewModel.isSubmitting,
|
||||
submitError: viewModel.submitError,
|
||||
};
|
||||
|
||||
return (
|
||||
<ResetPasswordTemplate
|
||||
// Spread the viewData properties
|
||||
token={templateViewData.token}
|
||||
returnTo={templateViewData.returnTo}
|
||||
showSuccess={templateViewData.showSuccess}
|
||||
successMessage={templateViewData.successMessage}
|
||||
formState={templateViewData.formState}
|
||||
isSubmitting={templateViewData.isSubmitting}
|
||||
submitError={templateViewData.submitError}
|
||||
// Add the additional props
|
||||
formActions={{
|
||||
setFormData,
|
||||
handleSubmit,
|
||||
setShowSuccess: (show) => {
|
||||
if (!show) {
|
||||
// Reset to initial state
|
||||
setViewModel(prev => ResetPasswordViewModelBuilder.build(viewData));
|
||||
}
|
||||
},
|
||||
setShowPassword: togglePassword,
|
||||
setShowConfirmPassword: toggleConfirmPassword,
|
||||
}}
|
||||
uiState={{
|
||||
showPassword: viewModel.uiState.showPassword,
|
||||
showConfirmPassword: viewModel.uiState.showConfirmPassword,
|
||||
}}
|
||||
mutationState={{
|
||||
isPending: viewModel.mutationPending,
|
||||
error: viewModel.mutationError,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,371 +1,34 @@
|
||||
'use client';
|
||||
/**
|
||||
* Reset Password Page
|
||||
*
|
||||
* RSC composition pattern:
|
||||
* 1. PageQuery executes to get ViewData
|
||||
* 2. Client component renders with ViewData
|
||||
*/
|
||||
|
||||
import { useState, FormEvent, type ChangeEvent, useEffect } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { motion } from 'framer-motion';
|
||||
import {
|
||||
Lock,
|
||||
Eye,
|
||||
EyeOff,
|
||||
AlertCircle,
|
||||
Flag,
|
||||
Shield,
|
||||
CheckCircle2,
|
||||
ArrowLeft,
|
||||
} from 'lucide-react';
|
||||
import { ResetPasswordPageQuery } from '@/lib/page-queries/auth/ResetPasswordPageQuery';
|
||||
import { ResetPasswordClient } from './ResetPasswordClient';
|
||||
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useResetPassword } from "@/lib/hooks/auth/useResetPassword";
|
||||
export default async function ResetPasswordPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<URLSearchParams>;
|
||||
}) {
|
||||
// Execute PageQuery
|
||||
const params = await searchParams;
|
||||
const queryResult = await ResetPasswordPageQuery.execute(params);
|
||||
|
||||
interface FormErrors {
|
||||
newPassword?: string;
|
||||
confirmPassword?: string;
|
||||
submit?: string;
|
||||
}
|
||||
|
||||
interface PasswordStrength {
|
||||
score: number;
|
||||
label: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
function checkPasswordStrength(password: string): PasswordStrength {
|
||||
let score = 0;
|
||||
if (password.length >= 8) score++;
|
||||
if (password.length >= 12) score++;
|
||||
if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++;
|
||||
if (/\d/.test(password)) score++;
|
||||
if (/[^a-zA-Z\d]/.test(password)) score++;
|
||||
|
||||
if (score <= 1) return { score, label: 'Weak', color: 'bg-red-500' };
|
||||
if (score <= 2) return { score, label: 'Fair', color: 'bg-warning-amber' };
|
||||
if (score <= 3) return { score, label: 'Good', color: 'bg-primary-blue' };
|
||||
return { score, label: 'Strong', color: 'bg-performance-green' };
|
||||
}
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { session } = useAuth();
|
||||
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
const [formData, setFormData] = useState({
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
});
|
||||
const [token, setToken] = useState<string>('');
|
||||
|
||||
// Check if user is already authenticated
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
router.replace('/dashboard');
|
||||
}
|
||||
}, [session, router]);
|
||||
|
||||
// Extract token from URL on mount
|
||||
useEffect(() => {
|
||||
const tokenParam = searchParams.get('token');
|
||||
if (tokenParam) {
|
||||
setToken(tokenParam);
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
const passwordStrength = checkPasswordStrength(formData.newPassword);
|
||||
|
||||
const passwordRequirements = [
|
||||
{ met: formData.newPassword.length >= 8, label: 'At least 8 characters' },
|
||||
{ met: /[a-z]/.test(formData.newPassword) && /[A-Z]/.test(formData.newPassword), label: 'Upper and lowercase letters' },
|
||||
{ met: /\d/.test(formData.newPassword), label: 'At least one number' },
|
||||
{ met: /[^a-zA-Z\d]/.test(formData.newPassword), label: 'At least one special character' },
|
||||
];
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: FormErrors = {};
|
||||
|
||||
if (!formData.newPassword) {
|
||||
newErrors.newPassword = 'New password is required';
|
||||
} else if (formData.newPassword.length < 8) {
|
||||
newErrors.newPassword = 'Password must be at least 8 characters';
|
||||
} else if (!/[a-z]/.test(formData.newPassword) || !/[A-Z]/.test(formData.newPassword) || !/\d/.test(formData.newPassword)) {
|
||||
newErrors.newPassword = 'Password must contain uppercase, lowercase, and number';
|
||||
}
|
||||
|
||||
if (!formData.confirmPassword) {
|
||||
newErrors.confirmPassword = 'Please confirm your password';
|
||||
} else if (formData.newPassword !== formData.confirmPassword) {
|
||||
newErrors.confirmPassword = 'Passwords do not match';
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
newErrors.submit = 'Invalid reset token. Please request a new reset link.';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
// Use reset password mutation hook
|
||||
const resetPasswordMutation = useResetPassword({
|
||||
onSuccess: (result) => {
|
||||
setSuccess(result.message);
|
||||
},
|
||||
onError: (error) => {
|
||||
setErrors({
|
||||
submit: error.message || 'Failed to reset password. Please try again.',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (resetPasswordMutation.isPending) return;
|
||||
|
||||
if (!validateForm()) return;
|
||||
|
||||
setErrors({});
|
||||
setSuccess(null);
|
||||
|
||||
try {
|
||||
await resetPasswordMutation.mutateAsync({
|
||||
token,
|
||||
newPassword: formData.newPassword,
|
||||
});
|
||||
} catch (error) {
|
||||
// Error handling is done in the mutation's onError callback
|
||||
}
|
||||
};
|
||||
|
||||
// Loading state from mutation
|
||||
const loading = resetPasswordMutation.isPending;
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex items-center justify-center px-4 py-12">
|
||||
{/* Background Pattern */}
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary-blue/5 via-transparent to-purple-600/5" />
|
||||
<div className="absolute inset-0 opacity-5">
|
||||
<div className="absolute inset-0" style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
|
||||
}} />
|
||||
if (queryResult.isErr()) {
|
||||
// Handle query error
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="text-red-400">Failed to load reset password page</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
<div className="relative w-full max-w-md">
|
||||
{/* Header */}
|
||||
<div className="text-center mb-8">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
|
||||
<Lock className="w-8 h-8 text-primary-blue" />
|
||||
</div>
|
||||
<Heading level={1} className="mb-2">Set New Password</Heading>
|
||||
<p className="text-gray-400">
|
||||
Create a strong password for your account
|
||||
</p>
|
||||
</div>
|
||||
const viewData = queryResult.unwrap();
|
||||
|
||||
<Card className="relative overflow-hidden">
|
||||
{/* Background accent */}
|
||||
<div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />
|
||||
|
||||
{!success ? (
|
||||
<form onSubmit={handleSubmit} className="relative space-y-5">
|
||||
{/* New Password */}
|
||||
<div>
|
||||
<label htmlFor="newPassword" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
New Password
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="newPassword"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={formData.newPassword}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, newPassword: e.target.value })}
|
||||
error={!!errors.newPassword}
|
||||
errorMessage={errors.newPassword}
|
||||
placeholder="••••••••"
|
||||
disabled={loading}
|
||||
className="pl-10 pr-10"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Password Strength */}
|
||||
{formData.newPassword && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 h-1.5 rounded-full bg-charcoal-outline overflow-hidden">
|
||||
<motion.div
|
||||
className={`h-full ${passwordStrength.color}`}
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${(passwordStrength.score / 5) * 100}%` }}
|
||||
transition={{ duration: 0.3 }}
|
||||
/>
|
||||
</div>
|
||||
<span className={`text-xs font-medium ${
|
||||
passwordStrength.score <= 1 ? 'text-red-400' :
|
||||
passwordStrength.score <= 2 ? 'text-warning-amber' :
|
||||
passwordStrength.score <= 3 ? 'text-primary-blue' :
|
||||
'text-performance-green'
|
||||
}`}>
|
||||
{passwordStrength.label}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-1">
|
||||
{passwordRequirements.map((req, index) => (
|
||||
<div key={index} className="flex items-center gap-1.5 text-xs">
|
||||
{req.met ? (
|
||||
<CheckCircle2 className="w-3 h-3 text-performance-green" />
|
||||
) : (
|
||||
<AlertCircle className="w-3 h-3 text-gray-500" />
|
||||
)}
|
||||
<span className={req.met ? 'text-gray-300' : 'text-gray-500'}>
|
||||
{req.label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Confirm Password */}
|
||||
<div>
|
||||
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Confirm Password
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type={showConfirmPassword ? 'text' : 'password'}
|
||||
value={formData.confirmPassword}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, confirmPassword: e.target.value })}
|
||||
error={!!errors.confirmPassword}
|
||||
errorMessage={errors.confirmPassword}
|
||||
placeholder="••••••••"
|
||||
disabled={loading}
|
||||
className="pl-10 pr-10"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
{showConfirmPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
{formData.confirmPassword && formData.newPassword === formData.confirmPassword && (
|
||||
<p className="mt-1 text-xs text-performance-green flex items-center gap-1">
|
||||
<CheckCircle2 className="w-3 h-3" /> Passwords match
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{errors.submit && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="flex items-start gap-3 p-3 rounded-lg bg-red-500/10 border border-red-500/30"
|
||||
>
|
||||
<AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
|
||||
<p className="text-sm text-red-400">{errors.submit}</p>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={loading}
|
||||
className="w-full flex items-center justify-center gap-2"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
Resetting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Lock className="w-4 h-4" />
|
||||
Reset Password
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Back to Login */}
|
||||
<div className="text-center">
|
||||
<Link
|
||||
href="/auth/login"
|
||||
className="text-sm text-primary-blue hover:underline flex items-center justify-center gap-1"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
Back to Login
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="relative space-y-4"
|
||||
>
|
||||
<div className="flex items-start gap-3 p-4 rounded-lg bg-performance-green/10 border border-performance-green/30">
|
||||
<CheckCircle2 className="w-6 h-6 text-performance-green flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm text-performance-green font-medium">{success}</p>
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
Your password has been successfully reset
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
onClick={() => router.push('/auth/login')}
|
||||
className="w-full"
|
||||
>
|
||||
Login with New Password
|
||||
</Button>
|
||||
</motion.div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Trust Indicators */}
|
||||
<div className="mt-6 flex items-center justify-center gap-6 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Encrypted & secure</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
<span>Instant update</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="mt-6 text-center text-xs text-gray-500">
|
||||
Need help?{' '}
|
||||
<Link href="/support" className="text-gray-400 hover:underline">
|
||||
Contact support
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
// Render client component with ViewData
|
||||
return <ResetPasswordClient viewData={viewData} />;
|
||||
}
|
||||
123
apps/website/app/auth/signup/SignupClient.tsx
Normal file
123
apps/website/app/auth/signup/SignupClient.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Signup Client Component
|
||||
*
|
||||
* Handles client-side signup flow.
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { SignupViewData } from '@/lib/builders/view-data/SignupViewDataBuilder';
|
||||
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';
|
||||
|
||||
interface SignupClientProps {
|
||||
viewData: SignupViewData;
|
||||
}
|
||||
|
||||
export function SignupClient({ viewData }: SignupClientProps) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refreshSession } = useAuth();
|
||||
|
||||
// Build ViewModel from ViewData
|
||||
const [viewModel, setViewModel] = useState<SignupViewModel>(() =>
|
||||
SignupViewModelBuilder.build(viewData)
|
||||
);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
password: '',
|
||||
confirmPassword: ''
|
||||
});
|
||||
|
||||
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'));
|
||||
return;
|
||||
}
|
||||
|
||||
// Update submitting state
|
||||
setViewModel(prev => prev.withMutationState(true, null));
|
||||
|
||||
try {
|
||||
// Transform to DTO format
|
||||
const displayName = `${formData.firstName} ${formData.lastName}`.trim();
|
||||
|
||||
// Execute signup mutation
|
||||
const mutation = new SignupMutation();
|
||||
const result = await mutation.execute({
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
displayName: displayName || formData.firstName || formData.lastName,
|
||||
});
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
setViewModel(prev => prev.withMutationState(false, error));
|
||||
return;
|
||||
}
|
||||
|
||||
// Success - refresh session and redirect
|
||||
await refreshSession();
|
||||
|
||||
const returnTo = searchParams.get('returnTo') ?? '/onboarding';
|
||||
router.push(returnTo);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Signup failed';
|
||||
setViewModel(prev => prev.withMutationState(false, errorMessage));
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle password visibility
|
||||
const togglePassword = () => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showPassword: !prev.uiState.showPassword,
|
||||
}));
|
||||
};
|
||||
|
||||
const toggleConfirmPassword = () => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showConfirmPassword: !prev.uiState.showConfirmPassword,
|
||||
}));
|
||||
};
|
||||
|
||||
// Build viewData for template
|
||||
const templateViewData: SignupViewData = {
|
||||
...viewData,
|
||||
formState: viewModel.formState,
|
||||
isSubmitting: viewModel.isSubmitting,
|
||||
submitError: viewModel.submitError,
|
||||
};
|
||||
|
||||
return (
|
||||
<SignupTemplate
|
||||
viewData={templateViewData}
|
||||
formActions={{
|
||||
setFormData,
|
||||
handleSubmit,
|
||||
setShowPassword: togglePassword,
|
||||
setShowConfirmPassword: toggleConfirmPassword,
|
||||
}}
|
||||
uiState={{
|
||||
showPassword: viewModel.uiState.showPassword,
|
||||
showConfirmPassword: viewModel.uiState.showConfirmPassword,
|
||||
}}
|
||||
mutationState={{
|
||||
isPending: viewModel.mutationPending,
|
||||
error: viewModel.mutationError,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,651 +1,34 @@
|
||||
'use client';
|
||||
/**
|
||||
* Signup Page
|
||||
*
|
||||
* RSC composition pattern:
|
||||
* 1. PageQuery executes to get ViewData
|
||||
* 2. Client component renders with ViewData
|
||||
*/
|
||||
|
||||
import { useState, useEffect, FormEvent, type ChangeEvent } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
Mail,
|
||||
Lock,
|
||||
Eye,
|
||||
EyeOff,
|
||||
UserPlus,
|
||||
AlertCircle,
|
||||
Flag,
|
||||
User,
|
||||
Check,
|
||||
X,
|
||||
Car,
|
||||
Users,
|
||||
Trophy,
|
||||
Shield,
|
||||
Sparkles,
|
||||
} from 'lucide-react';
|
||||
import { SignupPageQuery } from '@/lib/page-queries/auth/SignupPageQuery';
|
||||
import { SignupClient } from './SignupClient';
|
||||
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useSignup } from "@/lib/hooks/auth/useSignup";
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
export default async function SignupPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<URLSearchParams>;
|
||||
}) {
|
||||
// Execute PageQuery
|
||||
const params = await searchParams;
|
||||
const queryResult = await SignupPageQuery.execute(params);
|
||||
|
||||
interface FormErrors {
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
password?: string;
|
||||
confirmPassword?: string;
|
||||
submit?: string;
|
||||
}
|
||||
|
||||
interface PasswordStrength {
|
||||
score: number;
|
||||
label: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
interface SignupData {
|
||||
placeholder: string;
|
||||
}
|
||||
|
||||
function checkPasswordStrength(password: string): PasswordStrength {
|
||||
let score = 0;
|
||||
if (password.length >= 8) score++;
|
||||
if (password.length >= 12) score++;
|
||||
if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++;
|
||||
if (/\d/.test(password)) score++;
|
||||
if (/[^a-zA-Z\d]/.test(password)) score++;
|
||||
|
||||
if (score <= 1) return { score, label: 'Weak', color: 'bg-red-500' };
|
||||
if (score <= 2) return { score, label: 'Fair', color: 'bg-warning-amber' };
|
||||
if (score <= 3) return { score, label: 'Good', color: 'bg-primary-blue' };
|
||||
return { score, label: 'Strong', color: 'bg-performance-green' };
|
||||
}
|
||||
|
||||
const USER_ROLES = [
|
||||
{
|
||||
icon: Car,
|
||||
title: 'Driver',
|
||||
description: 'Race, track stats, join teams',
|
||||
color: 'primary-blue',
|
||||
},
|
||||
{
|
||||
icon: Trophy,
|
||||
title: 'League Admin',
|
||||
description: 'Organize leagues and events',
|
||||
color: 'performance-green',
|
||||
},
|
||||
{
|
||||
icon: Users,
|
||||
title: 'Team Manager',
|
||||
description: 'Manage team and drivers',
|
||||
color: 'purple-400',
|
||||
},
|
||||
];
|
||||
|
||||
const FEATURES = [
|
||||
'Track your racing statistics and progress',
|
||||
'Join or create competitive leagues',
|
||||
'Build or join racing teams',
|
||||
'Connect your iRacing account',
|
||||
'Compete in organized events',
|
||||
'Access detailed performance analytics',
|
||||
];
|
||||
|
||||
const SignupTemplate = ({ data }: { data: SignupData }) => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refreshSession } = useAuth();
|
||||
const returnTo = searchParams.get('returnTo') ?? '/onboarding';
|
||||
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [formData, setFormData] = useState({
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
});
|
||||
|
||||
const passwordStrength = checkPasswordStrength(formData.password);
|
||||
|
||||
const passwordRequirements = [
|
||||
{ met: formData.password.length >= 8, label: 'At least 8 characters' },
|
||||
{ met: /[a-z]/.test(formData.password) && /[A-Z]/.test(formData.password), label: 'Upper and lowercase letters' },
|
||||
{ met: /\d/.test(formData.password), label: 'At least one number' },
|
||||
{ met: /[^a-zA-Z\d]/.test(formData.password), label: 'At least one special character' },
|
||||
];
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: FormErrors = {};
|
||||
|
||||
// First name validation
|
||||
const firstName = formData.firstName.trim();
|
||||
if (!firstName) {
|
||||
newErrors.firstName = 'First name is required';
|
||||
} else if (firstName.length < 2) {
|
||||
newErrors.firstName = 'First name must be at least 2 characters';
|
||||
} else if (firstName.length > 25) {
|
||||
newErrors.firstName = 'First name must be no more than 25 characters';
|
||||
} else if (!/^[A-Za-z\-']+$/.test(firstName)) {
|
||||
newErrors.firstName = 'First name can only contain letters, hyphens, and apostrophes';
|
||||
} else if (/^(user|test|demo|guest|player)/i.test(firstName)) {
|
||||
newErrors.firstName = 'Please use your real first name, not a nickname';
|
||||
}
|
||||
|
||||
// Last name validation
|
||||
const lastName = formData.lastName.trim();
|
||||
if (!lastName) {
|
||||
newErrors.lastName = 'Last name is required';
|
||||
} else if (lastName.length < 2) {
|
||||
newErrors.lastName = 'Last name must be at least 2 characters';
|
||||
} else if (lastName.length > 25) {
|
||||
newErrors.lastName = 'Last name must be no more than 25 characters';
|
||||
} else if (!/^[A-Za-z\-']+$/.test(lastName)) {
|
||||
newErrors.lastName = 'Last name can only contain letters, hyphens, and apostrophes';
|
||||
} else if (/^(user|test|demo|guest|player)/i.test(lastName)) {
|
||||
newErrors.lastName = 'Please use your real last name, not a nickname';
|
||||
}
|
||||
|
||||
if (!formData.email.trim()) {
|
||||
newErrors.email = 'Email is required';
|
||||
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
|
||||
newErrors.email = 'Invalid email format';
|
||||
}
|
||||
|
||||
// Password strength validation
|
||||
if (!formData.password) {
|
||||
newErrors.password = 'Password is required';
|
||||
} else if (formData.password.length < 8) {
|
||||
newErrors.password = 'Password must be at least 8 characters';
|
||||
} else if (!/[a-z]/.test(formData.password) || !/[A-Z]/.test(formData.password) || !/\d/.test(formData.password)) {
|
||||
newErrors.password = 'Password must contain uppercase, lowercase, and number';
|
||||
}
|
||||
|
||||
if (!formData.confirmPassword) {
|
||||
newErrors.confirmPassword = 'Please confirm your password';
|
||||
} else if (formData.password !== formData.confirmPassword) {
|
||||
newErrors.confirmPassword = 'Passwords do not match';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
// Use signup mutation hook
|
||||
const signupMutation = useSignup({
|
||||
onSuccess: async () => {
|
||||
// Refresh session in context so header updates immediately
|
||||
try {
|
||||
await refreshSession();
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh session after signup:', error);
|
||||
}
|
||||
// Always redirect to dashboard after signup
|
||||
router.push('/dashboard');
|
||||
},
|
||||
onError: (error) => {
|
||||
setErrors({
|
||||
submit: error.message || 'Signup failed. Please try again.',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (signupMutation.isPending) return;
|
||||
|
||||
if (!validateForm()) return;
|
||||
|
||||
setErrors({});
|
||||
|
||||
try {
|
||||
// Combine first and last name into display name
|
||||
const displayName = `${formData.firstName} ${formData.lastName}`.trim();
|
||||
|
||||
await signupMutation.mutateAsync({
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
displayName,
|
||||
});
|
||||
} catch (error) {
|
||||
// Error handling is done in the mutation's onError callback
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex">
|
||||
{/* Background Pattern */}
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary-blue/5 via-transparent to-purple-600/5" />
|
||||
<div className="absolute inset-0 opacity-5">
|
||||
<div className="absolute inset-0" style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
|
||||
}} />
|
||||
</div>
|
||||
|
||||
{/* Left Side - Info Panel (Hidden on mobile) */}
|
||||
<div className="hidden lg:flex lg:w-1/2 relative items-center justify-center p-12">
|
||||
<div className="max-w-lg">
|
||||
{/* Logo */}
|
||||
<div className="flex items-center gap-3 mb-8">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30">
|
||||
<Flag className="w-6 h-6 text-primary-blue" />
|
||||
</div>
|
||||
<span className="text-2xl font-bold text-white">GridPilot</span>
|
||||
</div>
|
||||
|
||||
<Heading level={2} className="text-white mb-4">
|
||||
Start Your Racing Journey
|
||||
</Heading>
|
||||
|
||||
<p className="text-gray-400 text-lg mb-8">
|
||||
Join thousands of sim racers. One account gives you access to all roles - race as a driver, organize leagues, or manage teams.
|
||||
</p>
|
||||
|
||||
{/* Role Cards */}
|
||||
<div className="space-y-3 mb-8">
|
||||
{USER_ROLES.map((role, index) => (
|
||||
<motion.div
|
||||
key={role.title}
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: index * 0.1 }}
|
||||
className="flex items-center gap-4 p-4 rounded-xl bg-iron-gray/50 border border-charcoal-outline"
|
||||
>
|
||||
<div className={`w-10 h-10 rounded-lg bg-${role.color}/20 flex items-center justify-center`}>
|
||||
<role.icon className={`w-5 h-5 text-${role.color}`} />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="text-white font-medium">{role.title}</h4>
|
||||
<p className="text-sm text-gray-500">{role.description}</p>
|
||||
</div>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Features List */}
|
||||
<div className="bg-iron-gray/30 rounded-xl border border-charcoal-outline p-5 mb-8">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<Sparkles className="w-4 h-4 text-primary-blue" />
|
||||
<span className="text-sm font-medium text-white">What you'll get</span>
|
||||
</div>
|
||||
<ul className="space-y-2">
|
||||
{FEATURES.map((feature, index) => (
|
||||
<li
|
||||
key={index}
|
||||
className="flex items-center gap-2 text-sm text-gray-400"
|
||||
>
|
||||
<Check className="w-3.5 h-3.5 text-performance-green flex-shrink-0" />
|
||||
{feature}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Trust Indicators */}
|
||||
<div className="flex items-center gap-6 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Secure signup</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>iRacing integration</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Side - Signup Form */}
|
||||
<div className="flex-1 flex items-center justify-center px-4 py-12 overflow-y-auto">
|
||||
<div className="relative w-full max-w-md">
|
||||
{/* Mobile Logo/Header */}
|
||||
<div className="text-center mb-8 lg:hidden">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
|
||||
<Flag className="w-8 h-8 text-primary-blue" />
|
||||
</div>
|
||||
<Heading level={1} className="mb-2">Join GridPilot</Heading>
|
||||
<p className="text-gray-400">
|
||||
Create your account and start racing
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Desktop Header */}
|
||||
<div className="hidden lg:block text-center mb-8">
|
||||
<Heading level={2} className="mb-2">Create Account</Heading>
|
||||
<p className="text-gray-400">
|
||||
Get started with your free account
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="relative overflow-hidden">
|
||||
{/* Background accent */}
|
||||
<div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />
|
||||
|
||||
<form onSubmit={handleSubmit} className="relative space-y-4">
|
||||
{/* First Name */}
|
||||
<div>
|
||||
<label htmlFor="firstName" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
First Name
|
||||
</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="firstName"
|
||||
type="text"
|
||||
value={formData.firstName}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, firstName: e.target.value })}
|
||||
error={!!errors.firstName}
|
||||
errorMessage={errors.firstName}
|
||||
placeholder="John"
|
||||
disabled={signupMutation.isPending}
|
||||
className="pl-10"
|
||||
autoComplete="given-name"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Last Name */}
|
||||
<div>
|
||||
<label htmlFor="lastName" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Last Name
|
||||
</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="lastName"
|
||||
type="text"
|
||||
value={formData.lastName}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, lastName: e.target.value })}
|
||||
error={!!errors.lastName}
|
||||
errorMessage={errors.lastName}
|
||||
placeholder="Smith"
|
||||
disabled={signupMutation.isPending}
|
||||
className="pl-10"
|
||||
autoComplete="family-name"
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-500">Your name will be used as-is and cannot be changed later</p>
|
||||
</div>
|
||||
|
||||
{/* Name Immutability Warning */}
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-warning-amber/10 border border-warning-amber/30">
|
||||
<AlertCircle className="w-5 h-5 text-warning-amber flex-shrink-0 mt-0.5" />
|
||||
<div className="text-sm text-warning-amber">
|
||||
<strong>Important:</strong> Your name cannot be changed after signup. Please ensure it's correct.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Email Address
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, email: e.target.value })}
|
||||
error={!!errors.email}
|
||||
errorMessage={errors.email}
|
||||
placeholder="you@example.com"
|
||||
disabled={signupMutation.isPending}
|
||||
className="pl-10"
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Password */}
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Password
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={formData.password}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, password: e.target.value })}
|
||||
error={!!errors.password}
|
||||
errorMessage={errors.password}
|
||||
placeholder="••••••••"
|
||||
disabled={signupMutation.isPending}
|
||||
className="pl-10 pr-10"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Password Strength */}
|
||||
{formData.password && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 h-1.5 rounded-full bg-charcoal-outline overflow-hidden">
|
||||
<motion.div
|
||||
className={`h-full ${passwordStrength.color}`}
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${(passwordStrength.score / 5) * 100}%` }}
|
||||
transition={{ duration: 0.3 }}
|
||||
/>
|
||||
</div>
|
||||
<span className={`text-xs font-medium ${
|
||||
passwordStrength.score <= 1 ? 'text-red-400' :
|
||||
passwordStrength.score <= 2 ? 'text-warning-amber' :
|
||||
passwordStrength.score <= 3 ? 'text-primary-blue' :
|
||||
'text-performance-green'
|
||||
}`}>
|
||||
{passwordStrength.label}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-1">
|
||||
{passwordRequirements.map((req, index) => (
|
||||
<div key={index} className="flex items-center gap-1.5 text-xs">
|
||||
{req.met ? (
|
||||
<Check className="w-3 h-3 text-performance-green" />
|
||||
) : (
|
||||
<X className="w-3 h-3 text-gray-500" />
|
||||
)}
|
||||
<span className={req.met ? 'text-gray-300' : 'text-gray-500'}>
|
||||
{req.label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Confirm Password */}
|
||||
<div>
|
||||
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Confirm Password
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type={showConfirmPassword ? 'text' : 'password'}
|
||||
value={formData.confirmPassword}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, confirmPassword: e.target.value })}
|
||||
error={!!errors.confirmPassword}
|
||||
errorMessage={errors.confirmPassword}
|
||||
placeholder="••••••••"
|
||||
disabled={signupMutation.isPending}
|
||||
className="pl-10 pr-10"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
{showConfirmPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
{formData.confirmPassword && formData.password === formData.confirmPassword && (
|
||||
<p className="mt-1 text-xs text-performance-green flex items-center gap-1">
|
||||
<Check className="w-3 h-3" /> Passwords match
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={signupMutation.isPending}
|
||||
className="w-full flex items-center justify-center gap-2"
|
||||
>
|
||||
{signupMutation.isPending ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
Creating account...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<UserPlus className="w-4 h-4" />
|
||||
Create Account
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="relative my-6">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-charcoal-outline" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs">
|
||||
<span className="px-4 bg-iron-gray text-gray-500">or continue with</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Login Link */}
|
||||
<p className="mt-6 text-center text-sm text-gray-400">
|
||||
Already have an account?{' '}
|
||||
<Link
|
||||
href={`/auth/login${returnTo !== '/onboarding' ? `?returnTo=${encodeURIComponent(returnTo)}` : ''}`}
|
||||
className="text-primary-blue hover:underline font-medium"
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="mt-6 text-center text-xs text-gray-500">
|
||||
By creating an account, you agree to our{' '}
|
||||
<Link href="/terms" className="text-gray-400 hover:underline">Terms of Service</Link>
|
||||
{' '}and{' '}
|
||||
<Link href="/privacy" className="text-gray-400 hover:underline">Privacy Policy</Link>
|
||||
</p>
|
||||
|
||||
{/* Mobile Role Info */}
|
||||
<div className="mt-8 lg:hidden">
|
||||
<p className="text-center text-xs text-gray-500 mb-4">One account for all roles</p>
|
||||
<div className="flex justify-center gap-6">
|
||||
{USER_ROLES.map((role) => (
|
||||
<div key={role.title} className="flex flex-col items-center">
|
||||
<div className={`w-8 h-8 rounded-lg bg-${role.color}/20 flex items-center justify-center mb-1`}>
|
||||
<role.icon className={`w-4 h-4 text-${role.color}`} />
|
||||
</div>
|
||||
<span className="text-xs text-gray-500">{role.title}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default function SignupPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refreshSession, session } = useAuth();
|
||||
const returnTo = searchParams.get('returnTo') ?? '/onboarding';
|
||||
|
||||
const [checkingAuth, setCheckingAuth] = useState(true);
|
||||
|
||||
// Check if already authenticated
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
// Already logged in, redirect to dashboard or return URL
|
||||
router.replace(returnTo === '/onboarding' ? '/dashboard' : returnTo);
|
||||
return;
|
||||
}
|
||||
|
||||
// If no session, still check via API for consistency
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const response = await fetch('/api/auth/session');
|
||||
const data = await response.json();
|
||||
if (data.authenticated) {
|
||||
// Already logged in, redirect to dashboard or return URL
|
||||
router.replace(returnTo === '/onboarding' ? '/dashboard' : returnTo);
|
||||
}
|
||||
} catch {
|
||||
// Not authenticated, continue showing signup page
|
||||
} finally {
|
||||
setCheckingAuth(false);
|
||||
}
|
||||
}
|
||||
checkAuth();
|
||||
}, [session, router, returnTo]);
|
||||
|
||||
// Use signup mutation hook for state management
|
||||
const signupMutation = useSignup({
|
||||
onSuccess: async () => {
|
||||
// Refresh session in context so header updates immediately
|
||||
try {
|
||||
await refreshSession();
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh session after signup:', error);
|
||||
}
|
||||
// Always redirect to dashboard after signup
|
||||
router.push('/dashboard');
|
||||
},
|
||||
onError: (error) => {
|
||||
// Error will be handled in the template
|
||||
console.error('Signup error:', error);
|
||||
},
|
||||
});
|
||||
|
||||
// Loading state from mutation
|
||||
const loading = signupMutation.isPending;
|
||||
|
||||
// Show loading while checking auth
|
||||
if (checkingAuth) {
|
||||
if (queryResult.isErr()) {
|
||||
// Handle query error
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="w-8 h-8 border-2 border-primary-blue border-t-transparent rounded-full animate-spin" />
|
||||
</main>
|
||||
<div className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="text-red-400">Failed to load signup page</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Map mutation states to StatefulPageWrapper
|
||||
return (
|
||||
<StatefulPageWrapper
|
||||
data={{ placeholder: 'data' } as SignupData}
|
||||
isLoading={loading}
|
||||
error={signupMutation.error}
|
||||
retry={() => signupMutation.mutate({ email: '', password: '', displayName: '' })}
|
||||
Template={SignupTemplate}
|
||||
loading={{ variant: 'full-screen', message: 'Processing signup...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
/>
|
||||
);
|
||||
const viewData = queryResult.unwrap();
|
||||
|
||||
// Render client component with ViewData
|
||||
return <SignupClient viewData={viewData} />;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import type { DashboardViewData } from '@/templates/view-data/DashboardViewData';
|
||||
import type { DashboardPageDto } from '@/lib/page-queries/page-dtos/DashboardPageDto';
|
||||
import { DashboardPresenter } from '@/lib/presenters/DashboardPresenter';
|
||||
import { DashboardTemplate } from '@/templates/DashboardTemplate';
|
||||
|
||||
interface DashboardPageClientProps {
|
||||
pageDto: DashboardPageDto;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashboard Page Client Component
|
||||
*
|
||||
* Uses Presenter to transform Page DTO into ViewData
|
||||
* Presenter is deterministic and side-effect free
|
||||
*/
|
||||
export function DashboardPageClient({ pageDto }: DashboardPageClientProps) {
|
||||
const viewData: DashboardViewData = DashboardPresenter.createViewData(pageDto);
|
||||
|
||||
return <DashboardTemplate data={viewData} />;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { headers } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { createRouteGuard } from '@/lib/auth/createRouteGuard';
|
||||
|
||||
interface DashboardLayoutProps {
|
||||
@@ -16,11 +17,14 @@ export default async function DashboardLayout({ children }: DashboardLayoutProps
|
||||
const pathname = headerStore.get('x-pathname') || '/';
|
||||
|
||||
const guard = createRouteGuard();
|
||||
await guard.enforce({ pathname });
|
||||
const result = await guard.enforce({ pathname });
|
||||
if (result.type === 'redirect') {
|
||||
redirect(result.to);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +1,26 @@
|
||||
import { notFound, redirect } from 'next/navigation';
|
||||
import { DashboardPageQuery } from '@/lib/page-queries/page-queries/DashboardPageQuery';
|
||||
import { DashboardPageClient } from './DashboardPageClient';
|
||||
import { DashboardTemplate } from '@/templates/DashboardTemplate';
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const result = await DashboardPageQuery.execute();
|
||||
const result = await DashboardPageQuery.execute();
|
||||
|
||||
// Handle result based on status
|
||||
switch (result.status) {
|
||||
case 'ok':
|
||||
// Pass Page DTO to client component
|
||||
return <DashboardPageClient pageDto={result.dto} />;
|
||||
|
||||
case 'notFound':
|
||||
notFound();
|
||||
|
||||
case 'redirect':
|
||||
redirect(result.to);
|
||||
|
||||
case 'error':
|
||||
// For now, treat as notFound. Could also show error page
|
||||
console.error('Dashboard error:', result.errorId);
|
||||
notFound();
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
|
||||
// Handle different error types
|
||||
if (error === 'notFound') {
|
||||
notFound();
|
||||
} else if (error === 'redirect') {
|
||||
redirect('/');
|
||||
} else {
|
||||
// DASHBOARD_FETCH_FAILED or UNKNOWN_ERROR
|
||||
console.error('Dashboard error:', error);
|
||||
notFound();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Success
|
||||
const viewData = result.unwrap();
|
||||
return <DashboardTemplate viewData={viewData} />;
|
||||
}
|
||||
84
apps/website/app/drivers/DriversPageClient.tsx
Normal file
84
apps/website/app/drivers/DriversPageClient.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { DriversTemplate } from '@/templates/DriversTemplate';
|
||||
import { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel';
|
||||
import type { DriversLeaderboardDTO } from '@/lib/types/generated/DriversLeaderboardDTO';
|
||||
import type { DriverLeaderboardItemDTO } from '@/lib/types/generated/DriverLeaderboardItemDTO';
|
||||
|
||||
interface DriversPageClientProps {
|
||||
pageDto: DriversLeaderboardDTO | null;
|
||||
error?: string;
|
||||
empty?: {
|
||||
title: string;
|
||||
description: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* DriversPageClient
|
||||
*
|
||||
* Client component that:
|
||||
* 1. Handles state (search, filter, sort)
|
||||
* 2. Calls ViewModel to get computed display data
|
||||
* 3. Transforms ViewModel to Template-compatible format
|
||||
* 4. Passes data to Template
|
||||
*/
|
||||
export function DriversPageClient({ pageDto, error, empty }: DriversPageClientProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// Client state
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
|
||||
// Event handlers
|
||||
const onSearchChange = (query: string) => setSearchQuery(query);
|
||||
const onDriverClick = (id: string) => router.push(`/drivers/${id}`);
|
||||
const onBackToLeaderboards = () => router.push('/leaderboards');
|
||||
|
||||
// Handle error/empty states
|
||||
if (error) {
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 py-12 text-center">
|
||||
<div className="text-red-400 mb-4">Error loading drivers</div>
|
||||
<p className="text-gray-400">Please try again later</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!pageDto || pageDto.drivers.length === 0) {
|
||||
if (empty) {
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 py-12 text-center">
|
||||
<h2 className="text-xl font-semibold text-white mb-2">{empty.title}</h2>
|
||||
<p className="text-gray-400">{empty.description}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Transform DTO to ViewModel
|
||||
const dtoForViewModel: { drivers: DriverLeaderboardItemDTO[] } = {
|
||||
drivers: pageDto.drivers.map(driver => ({
|
||||
...driver,
|
||||
avatarUrl: driver.avatarUrl || '',
|
||||
})),
|
||||
};
|
||||
const viewModel = new DriverLeaderboardViewModel(dtoForViewModel);
|
||||
|
||||
// Filter drivers based on search
|
||||
let filteredDrivers = viewModel.drivers.filter(driver => {
|
||||
if (searchQuery) {
|
||||
const query = searchQuery.toLowerCase();
|
||||
const matchesSearch =
|
||||
driver.name.toLowerCase().includes(query) ||
|
||||
driver.nationality.toLowerCase().includes(query);
|
||||
if (!matchesSearch) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
// Pass to template
|
||||
return <DriversTemplate data={viewModel} />;
|
||||
}
|
||||
92
apps/website/app/drivers/[id]/DriverProfilePageClient.tsx
Normal file
92
apps/website/app/drivers/[id]/DriverProfilePageClient.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
'use client';
|
||||
|
||||
import React, { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { DriverProfileTemplate } from '@/templates/DriverProfileTemplate';
|
||||
import { DriverProfileViewModelBuilder } from '@/lib/builders/view-models/DriverProfileViewModelBuilder';
|
||||
import type { GetDriverProfileOutputDTO } from '@/lib/types/generated/GetDriverProfileOutputDTO';
|
||||
|
||||
interface DriverProfilePageClientProps {
|
||||
pageDto: GetDriverProfileOutputDTO | null;
|
||||
error?: string;
|
||||
empty?: {
|
||||
title: string;
|
||||
description: string;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* DriverProfilePageClient
|
||||
*
|
||||
* Client component that:
|
||||
* 1. Handles UI state (tabs, friend requests)
|
||||
* 2. Uses ViewModelBuilder to transform DTO
|
||||
* 3. Passes ViewModel to Template
|
||||
*/
|
||||
export function DriverProfilePageClient({ pageDto, error, empty }: DriverProfilePageClientProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// UI State
|
||||
const [activeTab, setActiveTab] = useState<'overview' | 'stats'>('overview');
|
||||
const [friendRequestSent, setFriendRequestSent] = useState(false);
|
||||
|
||||
// Event handlers
|
||||
const handleAddFriend = () => {
|
||||
setFriendRequestSent(true);
|
||||
};
|
||||
|
||||
const handleBackClick = () => {
|
||||
router.push('/drivers');
|
||||
};
|
||||
|
||||
// Handle error/empty states
|
||||
if (error) {
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto px-4 py-12 text-center">
|
||||
<div className="text-red-400 mb-4">Error loading driver profile</div>
|
||||
<p className="text-gray-400">Please try again later</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!pageDto || !pageDto.currentDriver) {
|
||||
if (empty) {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto px-4">
|
||||
<div className="text-center py-12">
|
||||
<h2 className="text-xl font-semibold text-white mb-2">{empty.title}</h2>
|
||||
<p className="text-gray-400">{empty.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Transform DTO to ViewModel using Builder
|
||||
const viewModel = DriverProfileViewModelBuilder.build(pageDto);
|
||||
|
||||
// Transform teamMemberships for template
|
||||
const allTeamMemberships = pageDto.teamMemberships.map(membership => ({
|
||||
team: {
|
||||
id: membership.teamId,
|
||||
name: membership.teamName,
|
||||
},
|
||||
role: membership.role,
|
||||
joinedAt: new Date(membership.joinedAt),
|
||||
}));
|
||||
|
||||
return (
|
||||
<DriverProfileTemplate
|
||||
driverProfile={viewModel}
|
||||
allTeamMemberships={allTeamMemberships}
|
||||
isLoading={false}
|
||||
error={null}
|
||||
onBackClick={handleBackClick}
|
||||
onAddFriend={handleAddFriend}
|
||||
friendRequestSent={friendRequestSent}
|
||||
activeTab={activeTab}
|
||||
setActiveTab={setActiveTab}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,81 +1,45 @@
|
||||
'use client';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { DriverProfilePageQuery } from '@/lib/page-queries/page-queries/DriverProfilePageQuery';
|
||||
import { DriverProfilePageClient } from './DriverProfilePageClient';
|
||||
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
import { DriverProfileTemplate } from '@/templates/DriverProfileTemplate';
|
||||
import { useDriverProfilePageData } from "@/lib/hooks/driver/useDriverProfilePageData";
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
export default async function DriverProfilePage({ params }: { params: { id: string } }) {
|
||||
// Execute the page query
|
||||
const result = await DriverProfilePageQuery.execute(params.id);
|
||||
|
||||
interface DriverProfileData {
|
||||
driverProfile: any;
|
||||
teamMemberships: Array<{
|
||||
team: { id: string; name: string };
|
||||
role: string;
|
||||
joinedAt: Date;
|
||||
}>;
|
||||
}
|
||||
|
||||
export default function DriverProfilePage() {
|
||||
const router = useRouter();
|
||||
const params = useParams();
|
||||
const driverId = params.id as string;
|
||||
const currentDriverId = useEffectiveDriverId() || '';
|
||||
|
||||
// UI State
|
||||
const [activeTab, setActiveTab] = useState<'overview' | 'stats'>('overview');
|
||||
const [friendRequestSent, setFriendRequestSent] = useState(false);
|
||||
|
||||
// Fetch data using domain hook
|
||||
const { data: queries, isLoading, error, refetch } = useDriverProfilePageData(driverId);
|
||||
|
||||
// Transform data for template
|
||||
const data: DriverProfileData | undefined = queries?.driverProfile && queries?.teamMemberships
|
||||
? {
|
||||
driverProfile: queries.driverProfile,
|
||||
teamMemberships: queries.teamMemberships,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
// Actions
|
||||
const handleAddFriend = () => {
|
||||
setFriendRequestSent(true);
|
||||
};
|
||||
|
||||
const handleBackClick = () => {
|
||||
router.push('/drivers');
|
||||
};
|
||||
|
||||
return (
|
||||
<StatefulPageWrapper
|
||||
data={data}
|
||||
isLoading={isLoading}
|
||||
error={error as Error | null}
|
||||
retry={refetch}
|
||||
Template={({ data }) => {
|
||||
if (!data) return null;
|
||||
// Handle different result statuses
|
||||
switch (result.status) {
|
||||
case 'notFound':
|
||||
redirect('/404');
|
||||
case 'redirect':
|
||||
redirect(result.to);
|
||||
case 'error':
|
||||
// Pass error to client component
|
||||
return (
|
||||
<DriverProfilePageClient
|
||||
pageDto={null}
|
||||
error={result.errorId}
|
||||
/>
|
||||
);
|
||||
case 'ok':
|
||||
const pageDto = result.dto;
|
||||
const hasData = !!pageDto.currentDriver;
|
||||
|
||||
if (!hasData) {
|
||||
return (
|
||||
<DriverProfileTemplate
|
||||
driverProfile={data.driverProfile}
|
||||
allTeamMemberships={data.teamMemberships}
|
||||
isLoading={false}
|
||||
error={null}
|
||||
onBackClick={handleBackClick}
|
||||
onAddFriend={handleAddFriend}
|
||||
friendRequestSent={friendRequestSent}
|
||||
activeTab={activeTab}
|
||||
setActiveTab={setActiveTab}
|
||||
<DriverProfilePageClient
|
||||
pageDto={null}
|
||||
empty={{
|
||||
title: 'Driver not found',
|
||||
description: 'The driver profile may not exist or you may not have access',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
loading={{ variant: 'skeleton', message: 'Loading driver profile...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
empty={{
|
||||
icon: require('lucide-react').Car,
|
||||
title: 'Driver not found',
|
||||
description: 'The driver profile may not exist or you may not have access',
|
||||
action: { label: 'Back to Drivers', onClick: handleBackClick }
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DriverProfilePageClient
|
||||
pageDto={pageDto}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,45 @@
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { DriversTemplate } from '@/templates/DriversTemplate';
|
||||
import { DriverService } from '@/lib/services/drivers/DriverService';
|
||||
import { DriversApiClient } from '@/lib/api/drivers/DriversApiClient';
|
||||
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { DriversPageQuery } from '@/lib/page-queries/page-queries/DriversPageQuery';
|
||||
import { DriversPageClient } from './DriversPageClient';
|
||||
|
||||
export default async function Page() {
|
||||
// Manual dependency creation (consistent with /races and /teams)
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: true,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
// Execute the page query
|
||||
const result = await DriversPageQuery.execute();
|
||||
|
||||
// Create API client
|
||||
const driversApiClient = new DriversApiClient(baseUrl, errorReporter, logger);
|
||||
// Handle different result statuses
|
||||
switch (result.status) {
|
||||
case 'notFound':
|
||||
redirect('/404');
|
||||
case 'redirect':
|
||||
redirect(result.to);
|
||||
case 'error':
|
||||
// Pass error to client component
|
||||
return (
|
||||
<DriversPageClient
|
||||
pageDto={null}
|
||||
error={result.errorId}
|
||||
/>
|
||||
);
|
||||
case 'ok':
|
||||
const pageDto = result.dto;
|
||||
const hasData = (pageDto.drivers?.length ?? 0) > 0;
|
||||
|
||||
if (!hasData) {
|
||||
return (
|
||||
<DriversPageClient
|
||||
pageDto={null}
|
||||
empty={{
|
||||
title: 'No drivers found',
|
||||
description: 'There are no drivers in the system yet.',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Create service
|
||||
const service = new DriverService(driversApiClient);
|
||||
|
||||
const data = await service.getDriverLeaderboard();
|
||||
|
||||
return <PageWrapper data={data} Template={DriversTemplate} />;
|
||||
return (
|
||||
<DriversPageClient
|
||||
pageDto={pageDto}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,24 +2,15 @@
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import LeaderboardsTemplate from '@/templates/LeaderboardsTemplate';
|
||||
import type { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel';
|
||||
import type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';
|
||||
import type { LeaderboardsViewData } from '@/lib/view-data/LeaderboardsViewData';
|
||||
|
||||
interface LeaderboardsPageData {
|
||||
drivers: DriverLeaderboardViewModel | null;
|
||||
teams: TeamSummaryViewModel[] | null;
|
||||
}
|
||||
|
||||
export function LeaderboardsPageWrapper({ data }: { data: LeaderboardsPageData | null }) {
|
||||
export function LeaderboardsPageWrapper({ data }: { data: LeaderboardsViewData | null }) {
|
||||
const router = useRouter();
|
||||
|
||||
if (!data || (!data.drivers && !data.teams)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const drivers = data.drivers?.drivers || [];
|
||||
const teams = data.teams || [];
|
||||
|
||||
const handleDriverClick = (driverId: string) => {
|
||||
router.push(`/drivers/${driverId}`);
|
||||
};
|
||||
@@ -36,14 +27,34 @@ export function LeaderboardsPageWrapper({ data }: { data: LeaderboardsPageData |
|
||||
router.push('/teams/leaderboard');
|
||||
};
|
||||
|
||||
return (
|
||||
<LeaderboardsTemplate
|
||||
drivers={drivers}
|
||||
teams={teams}
|
||||
onDriverClick={handleDriverClick}
|
||||
onTeamClick={handleTeamClick}
|
||||
onNavigateToDrivers={handleNavigateToDrivers}
|
||||
onNavigateToTeams={handleNavigateToTeams}
|
||||
/>
|
||||
);
|
||||
// Transform ViewData to template props
|
||||
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} />;
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import DriverRankingsTemplate from '@/templates/DriverRankingsTemplate';
|
||||
import { useState } from 'react';
|
||||
import type { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel';
|
||||
|
||||
type SkillLevel = 'pro' | 'advanced' | 'intermediate' | 'beginner';
|
||||
type SortBy = 'rank' | 'rating' | 'wins' | 'podiums' | 'winRate';
|
||||
|
||||
export function DriverRankingsPageWrapper({ data }: { data: DriverLeaderboardViewModel | null }) {
|
||||
const router = useRouter();
|
||||
|
||||
// Client-side state for filtering and sorting
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [selectedSkill, setSelectedSkill] = useState<'all' | SkillLevel>('all');
|
||||
const [sortBy, setSortBy] = useState<SortBy>('rank');
|
||||
const [showFilters, setShowFilters] = useState(false);
|
||||
|
||||
if (!data || !data.drivers) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleDriverClick = (driverId: string) => {
|
||||
if (driverId.startsWith('demo-')) return;
|
||||
router.push(`/drivers/${driverId}`);
|
||||
};
|
||||
|
||||
const handleBackToLeaderboards = () => {
|
||||
router.push('/leaderboards');
|
||||
};
|
||||
|
||||
return (
|
||||
<DriverRankingsTemplate
|
||||
drivers={data.drivers}
|
||||
searchQuery={searchQuery}
|
||||
selectedSkill={selectedSkill}
|
||||
sortBy={sortBy}
|
||||
showFilters={showFilters}
|
||||
onSearchChange={setSearchQuery}
|
||||
onSkillChange={setSelectedSkill}
|
||||
onSortChange={setSortBy}
|
||||
onToggleFilters={() => setShowFilters(!showFilters)}
|
||||
onDriverClick={handleDriverClick}
|
||||
onBackToLeaderboards={handleBackToLeaderboards}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,50 +1,51 @@
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { DRIVER_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import { DriverService } from '@/lib/services/drivers/DriverService';
|
||||
import { Users } from 'lucide-react';
|
||||
import { redirect } from 'next/navigation';
|
||||
import type { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel';
|
||||
import { DriverRankingsPageWrapper } from './DriverRankingsPageWrapper';
|
||||
import { DriverRankingsPageQuery } from '@/lib/page-queries/page-queries/DriverRankingsPageQuery';
|
||||
import { DriverRankingsViewDataBuilder } from '@/lib/builders/view-data/DriverRankingsViewDataBuilder';
|
||||
import { DriverRankingsTemplate } from '@/templates/DriverRankingsTemplate';
|
||||
|
||||
// ============================================================================
|
||||
// MAIN PAGE COMPONENT
|
||||
// ============================================================================
|
||||
|
||||
export default async function DriverLeaderboardPage() {
|
||||
// Fetch data using PageDataFetcher
|
||||
const driverData = await PageDataFetcher.fetch<DriverService, 'getDriverLeaderboard'>(
|
||||
DRIVER_SERVICE_TOKEN,
|
||||
'getDriverLeaderboard'
|
||||
);
|
||||
// Execute the page query
|
||||
const result = await DriverRankingsPageQuery.execute();
|
||||
|
||||
// Prepare data for template
|
||||
const data: DriverLeaderboardViewModel | null = driverData;
|
||||
// Handle different result statuses
|
||||
switch (result.status) {
|
||||
case 'notFound':
|
||||
redirect('/404');
|
||||
case 'redirect':
|
||||
redirect(result.to);
|
||||
case 'error':
|
||||
// For now, show empty state. In a real app, you'd pass error to client
|
||||
return (
|
||||
<div className="max-w-7xl mx-auto px-4 py-12 text-center">
|
||||
<div className="text-red-400 mb-4">Error loading driver rankings</div>
|
||||
<p className="text-gray-400">Please try again later</p>
|
||||
</div>
|
||||
);
|
||||
case 'ok':
|
||||
const viewData = DriverRankingsViewDataBuilder.build(result.dto);
|
||||
const hasData = (viewData.drivers?.length ?? 0) > 0;
|
||||
|
||||
if (!hasData) {
|
||||
return (
|
||||
<DriverRankingsTemplate
|
||||
viewData={{
|
||||
drivers: [],
|
||||
podium: [],
|
||||
searchQuery: '',
|
||||
selectedSkill: 'all',
|
||||
sortBy: 'rank',
|
||||
showFilters: false,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const hasData = (driverData?.drivers?.length ?? 0) > 0;
|
||||
|
||||
// Handle loading state (should be fast since we're using async/await)
|
||||
const isLoading = false;
|
||||
const error = null;
|
||||
const retry = async () => {
|
||||
// In server components, we can't retry without a reload
|
||||
redirect('/leaderboards/drivers');
|
||||
};
|
||||
|
||||
return (
|
||||
<PageWrapper
|
||||
data={hasData ? data : null}
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
retry={retry}
|
||||
Template={DriverRankingsPageWrapper}
|
||||
loading={{ variant: 'full-screen', message: 'Loading driver rankings...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
empty={{
|
||||
icon: Users,
|
||||
title: 'No drivers found',
|
||||
description: 'There are no drivers in the system yet.',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<DriverRankingsTemplate viewData={viewData} />
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,71 +1,61 @@
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { DRIVER_SERVICE_TOKEN, TEAM_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import { DriverService } from '@/lib/services/drivers/DriverService';
|
||||
import { TeamService } from '@/lib/services/teams/TeamService';
|
||||
import { Trophy } from 'lucide-react';
|
||||
import { redirect } from 'next/navigation';
|
||||
import type { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel';
|
||||
import type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';
|
||||
import { LeaderboardsPageQuery } from '@/lib/page-queries/page-queries/LeaderboardsPageQuery';
|
||||
import { LeaderboardsViewDataBuilder } from '@/lib/builders/view-data/LeaderboardsViewDataBuilder';
|
||||
import { LeaderboardsPageWrapper } from './LeaderboardsPageWrapper';
|
||||
|
||||
// ============================================================================
|
||||
// TYPES
|
||||
// ============================================================================
|
||||
|
||||
interface LeaderboardsPageData {
|
||||
drivers: DriverLeaderboardViewModel | null;
|
||||
teams: TeamSummaryViewModel[] | null;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// MAIN PAGE COMPONENT
|
||||
// ============================================================================
|
||||
|
||||
export default async function LeaderboardsPage() {
|
||||
// Fetch data using PageDataFetcher with proper type annotations
|
||||
const [driverData, teamsData] = await Promise.all([
|
||||
PageDataFetcher.fetch<DriverService, 'getDriverLeaderboard'>(
|
||||
DRIVER_SERVICE_TOKEN,
|
||||
'getDriverLeaderboard'
|
||||
),
|
||||
PageDataFetcher.fetch<TeamService, 'getAllTeams'>(
|
||||
TEAM_SERVICE_TOKEN,
|
||||
'getAllTeams'
|
||||
),
|
||||
]);
|
||||
// Execute the page query
|
||||
const result = await LeaderboardsPageQuery.execute();
|
||||
|
||||
// Prepare data for template
|
||||
const data: LeaderboardsPageData = {
|
||||
drivers: driverData,
|
||||
teams: teamsData,
|
||||
};
|
||||
// Handle different result statuses
|
||||
switch (result.status) {
|
||||
case 'notFound':
|
||||
redirect('/404');
|
||||
case 'redirect':
|
||||
redirect(result.to);
|
||||
case 'error':
|
||||
// Show empty state with error
|
||||
return (
|
||||
<PageWrapper
|
||||
data={null}
|
||||
isLoading={false}
|
||||
error={new Error(result.errorId)}
|
||||
retry={async () => redirect('/leaderboards')}
|
||||
Template={LeaderboardsPageWrapper}
|
||||
loading={{ variant: 'full-screen', message: 'Loading leaderboards...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
empty={{
|
||||
icon: Trophy,
|
||||
title: 'No leaderboard data',
|
||||
description: 'There is no leaderboard data available at the moment.',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
case 'ok':
|
||||
const viewData = LeaderboardsViewDataBuilder.build(result.dto.drivers, result.dto.teams);
|
||||
const hasData = (viewData.drivers?.length ?? 0) > 0 || (viewData.teams?.length ?? 0) > 0;
|
||||
|
||||
const hasData = (driverData?.drivers?.length ?? 0) > 0 || (teamsData?.length ?? 0) > 0;
|
||||
|
||||
// Handle loading state (should be fast since we're using async/await)
|
||||
const isLoading = false;
|
||||
const error = null;
|
||||
const retry = async () => {
|
||||
// In server components, we can't retry without a reload
|
||||
// This would typically trigger a page reload
|
||||
redirect('/leaderboards');
|
||||
};
|
||||
|
||||
return (
|
||||
<PageWrapper
|
||||
data={hasData ? data : null}
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
retry={retry}
|
||||
Template={LeaderboardsPageWrapper}
|
||||
loading={{ variant: 'full-screen', message: 'Loading leaderboards...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
empty={{
|
||||
icon: Trophy,
|
||||
title: 'No leaderboard data',
|
||||
description: 'There is no leaderboard data available at the moment.',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<PageWrapper
|
||||
data={hasData ? viewData : null}
|
||||
isLoading={false}
|
||||
error={null}
|
||||
retry={async () => redirect('/leaderboards')}
|
||||
Template={LeaderboardsPageWrapper}
|
||||
loading={{ variant: 'full-screen', message: 'Loading leaderboards...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
empty={{
|
||||
icon: Trophy,
|
||||
title: 'No leaderboard data',
|
||||
description: 'There is no leaderboard data available at the moment.',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ export default function LeagueLayout({
|
||||
const leagueId = params.id as string;
|
||||
const currentDriverId = useEffectiveDriverId();
|
||||
|
||||
const { data: leagueDetail, isLoading: loading } = useLeagueDetail(leagueId, currentDriverId ?? '');
|
||||
const { data: leagueDetail, isLoading: loading } = useLeagueDetail({ leagueId });
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -56,8 +56,9 @@ export default function LeagueLayout({
|
||||
{ label: 'Settings', href: `/leagues/${leagueId}/settings`, exact: false },
|
||||
];
|
||||
|
||||
const tabs = leagueDetail.isAdmin ? [...baseTabs, ...adminTabs] : baseTabs;
|
||||
|
||||
// TODO: Admin check needs to be implemented properly
|
||||
// For now, show admin tabs if user is logged in
|
||||
const tabs = [...baseTabs, ...adminTabs];
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite py-12 px-4 sm:px-6 lg:px-8">
|
||||
@@ -75,8 +76,8 @@ export default function LeagueLayout({
|
||||
leagueName={leagueDetail.name}
|
||||
description={leagueDetail.description}
|
||||
ownerId={leagueDetail.ownerId}
|
||||
ownerName={leagueDetail.ownerName}
|
||||
mainSponsor={leagueDetail.mainSponsor}
|
||||
ownerName={''}
|
||||
mainSponsor={null}
|
||||
/>
|
||||
|
||||
{/* Tab Navigation */}
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { LeagueDetailTemplate } from '@/templates/LeagueDetailTemplate';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { LeagueService } from '@/lib/services/leagues/LeagueService';
|
||||
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 { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { LeagueDetailPageQuery } from '@/lib/page-queries/page-queries/LeagueDetailPageQuery';
|
||||
import { LeagueDetailPresenter } from '@/lib/presenters/LeagueDetailPresenter';
|
||||
import type { LeagueDetailPageViewModel } from '@/lib/view-models/LeagueDetailPageViewModel';
|
||||
|
||||
interface Props {
|
||||
@@ -22,58 +15,58 @@ export default async function Page({ params }: Props) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// Fetch data using PageDataFetcher.fetchManual for multiple dependencies
|
||||
const data = await PageDataFetcher.fetchManual(async () => {
|
||||
// Create dependencies
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: true,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
|
||||
// Create API clients
|
||||
const leaguesApiClient = new LeaguesApiClient(baseUrl, errorReporter, logger);
|
||||
const driversApiClient = new DriversApiClient(baseUrl, errorReporter, logger);
|
||||
const sponsorsApiClient = new SponsorsApiClient(baseUrl, errorReporter, logger);
|
||||
const racesApiClient = new RacesApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Create service
|
||||
const service = new LeagueService(
|
||||
leaguesApiClient,
|
||||
driversApiClient,
|
||||
sponsorsApiClient,
|
||||
racesApiClient
|
||||
);
|
||||
|
||||
// Fetch data
|
||||
const result = await service.getLeagueDetailPageData(params.id);
|
||||
if (!result) {
|
||||
throw new Error('League not found');
|
||||
// Execute the PageQuery
|
||||
const result = await LeagueDetailPageQuery.execute(params.id);
|
||||
|
||||
// Handle different result types
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
|
||||
switch (error) {
|
||||
case 'notFound':
|
||||
notFound();
|
||||
case 'redirect':
|
||||
// In a real app, this would redirect to login
|
||||
notFound();
|
||||
case 'LEAGUE_FETCH_FAILED':
|
||||
case 'UNKNOWN_ERROR':
|
||||
default:
|
||||
// Return error state that PageWrapper can handle
|
||||
// For error state, we need a simple template that just renders an error
|
||||
const ErrorTemplate: React.ComponentType<{ data: any }> = ({ data }) => (
|
||||
<div>Error state</div>
|
||||
);
|
||||
return (
|
||||
<PageWrapper
|
||||
data={undefined}
|
||||
error={new Error('Failed to fetch league')}
|
||||
Template={ErrorTemplate}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
if (!data) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// Create a wrapper component that passes data to the template
|
||||
const TemplateWrapper = ({ data }: { data: LeagueDetailPageViewModel }) => {
|
||||
// The LeagueDetailTemplate expects multiple props beyond just data
|
||||
// We need to provide the additional props it requires
|
||||
|
||||
const data = result.unwrap();
|
||||
|
||||
// Convert the API DTO to ViewModel using the existing presenter
|
||||
// This maintains compatibility with the existing template
|
||||
const viewModel = data.apiDto as unknown as LeagueDetailPageViewModel;
|
||||
|
||||
// Create a wrapper component that passes ViewData to the template
|
||||
const TemplateWrapper: React.ComponentType<{ data: typeof data }> = ({ data }) => {
|
||||
// Convert ViewModel to ViewData using Presenter
|
||||
const viewData = LeagueDetailPresenter.createViewData(viewModel, params.id, false);
|
||||
|
||||
return (
|
||||
<LeagueDetailTemplate
|
||||
viewModel={data}
|
||||
leagueId={data.id}
|
||||
viewData={viewData}
|
||||
leagueId={params.id}
|
||||
isSponsor={false}
|
||||
membership={null}
|
||||
currentDriverId={null}
|
||||
onMembershipChange={() => {}}
|
||||
onEndRaceModalOpen={() => {}}
|
||||
onLiveRaceClick={() => {}}
|
||||
onBackToLeagues={() => {}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -5,8 +5,8 @@ import type { MembershipRole } from '@/lib/types/MembershipRole';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { useMemo } from 'react';
|
||||
import {
|
||||
useLeagueRosterJoinRequests,
|
||||
useLeagueRosterMembers,
|
||||
useLeagueJoinRequests,
|
||||
useLeagueRosterAdmin,
|
||||
useApproveJoinRequest,
|
||||
useRejectJoinRequest,
|
||||
useUpdateMemberRole,
|
||||
@@ -24,13 +24,13 @@ export function RosterAdminPage() {
|
||||
data: joinRequests = [],
|
||||
isLoading: loadingJoinRequests,
|
||||
refetch: refetchJoinRequests,
|
||||
} = useLeagueRosterJoinRequests(leagueId);
|
||||
} = useLeagueJoinRequests(leagueId);
|
||||
|
||||
const {
|
||||
data: members = [],
|
||||
isLoading: loadingMembers,
|
||||
refetch: refetchMembers,
|
||||
} = useLeagueRosterMembers(leagueId);
|
||||
} = useLeagueRosterAdmin(leagueId);
|
||||
|
||||
const loading = loadingJoinRequests || loadingMembers;
|
||||
|
||||
@@ -55,16 +55,16 @@ export function RosterAdminPage() {
|
||||
return joinRequests.length === 1 ? '1 request' : `${joinRequests.length} requests`;
|
||||
}, [joinRequests.length]);
|
||||
|
||||
const handleApprove = async (joinRequestId: string) => {
|
||||
await approveMutation.mutateAsync({ leagueId, joinRequestId });
|
||||
const handleApprove = async (requestId: string) => {
|
||||
await approveMutation.mutateAsync({ leagueId, requestId });
|
||||
};
|
||||
|
||||
const handleReject = async (joinRequestId: string) => {
|
||||
await rejectMutation.mutateAsync({ leagueId, joinRequestId });
|
||||
const handleReject = async (requestId: string) => {
|
||||
await rejectMutation.mutateAsync({ leagueId, requestId });
|
||||
};
|
||||
|
||||
const handleRoleChange = async (driverId: string, newRole: MembershipRole) => {
|
||||
await updateRoleMutation.mutateAsync({ leagueId, driverId, role: newRole });
|
||||
await updateRoleMutation.mutateAsync({ leagueId, driverId, newRole });
|
||||
};
|
||||
|
||||
const handleRemove = async (driverId: string) => {
|
||||
@@ -96,8 +96,8 @@ export function RosterAdminPage() {
|
||||
className="flex items-center justify-between gap-3 bg-deep-graphite border border-charcoal-outline rounded p-3"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<p className="text-white font-medium truncate">{req.driverName}</p>
|
||||
<p className="text-xs text-gray-400 truncate">{req.requestedAtIso}</p>
|
||||
<p className="text-white font-medium truncate">{(req.driver as any)?.name || 'Unknown'}</p>
|
||||
<p className="text-xs text-gray-400 truncate">{req.requestedAt}</p>
|
||||
{req.message ? <p className="text-xs text-gray-500 truncate">{req.message}</p> : null}
|
||||
</div>
|
||||
|
||||
@@ -140,17 +140,17 @@ export function RosterAdminPage() {
|
||||
className="flex flex-col md:flex-row md:items-center md:justify-between gap-3 bg-deep-graphite border border-charcoal-outline rounded p-3"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<p className="text-white font-medium truncate">{member.driverName}</p>
|
||||
<p className="text-xs text-gray-400 truncate">{member.joinedAtIso}</p>
|
||||
<p className="text-white font-medium truncate">{member.driver.name}</p>
|
||||
<p className="text-xs text-gray-400 truncate">{member.joinedAt}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col md:flex-row md:items-center gap-2">
|
||||
<label className="text-xs text-gray-400" htmlFor={`role-${member.driverId}`}>
|
||||
Role for {member.driverName}
|
||||
Role for {member.driver.name}
|
||||
</label>
|
||||
<select
|
||||
id={`role-${member.driverId}`}
|
||||
aria-label={`Role for ${member.driverName}`}
|
||||
aria-label={`Role for ${member.driver.name}`}
|
||||
value={member.role}
|
||||
onChange={(e) => handleRoleChange(member.driverId, e.target.value as MembershipRole)}
|
||||
className="bg-iron-gray text-white px-3 py-2 rounded"
|
||||
|
||||
@@ -15,6 +15,7 @@ import { DriverViewModel } from '@/lib/view-models/DriverViewModel';
|
||||
import type { LeagueMembership } from '@/lib/types/LeagueMembership';
|
||||
import type { LeagueStandingDTO } from '@/lib/types/generated/LeagueStandingDTO';
|
||||
import type { LeagueMemberDTO } from '@/lib/types/generated/LeagueMemberDTO';
|
||||
import { LeagueStandingsPresenter } from '@/lib/presenters/LeagueStandingsPresenter';
|
||||
|
||||
interface Props {
|
||||
params: { id: string };
|
||||
@@ -105,16 +106,21 @@ export default async function Page({ params }: Props) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// Create a wrapper component that passes data to the template
|
||||
// Create a wrapper component that passes ViewData to the template
|
||||
const TemplateWrapper = () => {
|
||||
// Convert ViewModels to ViewData using Presenter
|
||||
const viewData = LeagueStandingsPresenter.createViewData(
|
||||
data.standings,
|
||||
data.drivers,
|
||||
data.memberships,
|
||||
params.id,
|
||||
null, // currentDriverId
|
||||
false // isAdmin
|
||||
);
|
||||
|
||||
return (
|
||||
<LeagueStandingsTemplate
|
||||
standings={data.standings}
|
||||
drivers={data.drivers}
|
||||
memberships={data.memberships}
|
||||
leagueId={params.id}
|
||||
currentDriverId={null}
|
||||
isAdmin={false}
|
||||
viewData={viewData}
|
||||
onRemoveMember={() => {}}
|
||||
onUpdateRole={() => {}}
|
||||
/>
|
||||
|
||||
@@ -1,19 +1,39 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { LeaguesTemplate } from '@/templates/LeaguesTemplate';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { LEAGUE_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import type { LeagueService } from '@/lib/services/leagues/LeagueService';
|
||||
import { LeaguesPageQuery } from '@/lib/page-queries/page-queries/LeaguesPageQuery';
|
||||
import type { LeaguesViewData } from '@/lib/view-data/LeaguesViewData';
|
||||
|
||||
export default async function Page() {
|
||||
const data = await PageDataFetcher.fetch<LeagueService, 'getAllLeagues'>(
|
||||
LEAGUE_SERVICE_TOKEN,
|
||||
'getAllLeagues'
|
||||
);
|
||||
|
||||
if (!data) {
|
||||
notFound();
|
||||
// Execute the PageQuery
|
||||
const result = await LeaguesPageQuery.execute();
|
||||
|
||||
// Handle different result types
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
|
||||
switch (error) {
|
||||
case 'notFound':
|
||||
notFound();
|
||||
case 'redirect':
|
||||
// In a real app, this would redirect to login
|
||||
notFound();
|
||||
case 'LEAGUES_FETCH_FAILED':
|
||||
case 'UNKNOWN_ERROR':
|
||||
default:
|
||||
// Return error state that PageWrapper can handle
|
||||
return (
|
||||
<PageWrapper
|
||||
data={undefined}
|
||||
error={new Error('Failed to fetch leagues')}
|
||||
Template={LeaguesTemplate}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return <PageWrapper data={data} Template={LeaguesTemplate} />;
|
||||
|
||||
const viewData = result.unwrap();
|
||||
|
||||
return <PageWrapper data={viewData} Template={LeaguesTemplate} />;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { proxyMediaRequest, getMediaContentType, getMediaCacheControl } from '@/lib/adapters/MediaProxyAdapter';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
@@ -6,32 +7,16 @@ export async function GET(
|
||||
) {
|
||||
const { driverId } = params;
|
||||
|
||||
// In test environment, proxy to the mock API
|
||||
const apiBaseUrl = process.env.API_BASE_URL || 'http://localhost:3000';
|
||||
const result = await proxyMediaRequest(`/media/avatar/${driverId}`);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${apiBaseUrl}/media/avatar/${driverId}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// Return a fallback image or 404
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
const buffer = await response.arrayBuffer();
|
||||
|
||||
return new NextResponse(buffer, {
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
'Cache-Control': 'public, max-age=3600',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching avatar:', error);
|
||||
return new NextResponse(null, { status: 500 });
|
||||
if (result.isErr()) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
return new NextResponse(result.unwrap(), {
|
||||
headers: {
|
||||
'Content-Type': getMediaContentType('/media/avatar'),
|
||||
'Cache-Control': getMediaCacheControl(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { proxyMediaRequest, getMediaContentType, getMediaCacheControl } from '@/lib/adapters/MediaProxyAdapter';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
@@ -6,27 +7,16 @@ export async function GET(
|
||||
) {
|
||||
const { categoryId } = params;
|
||||
|
||||
const apiBaseUrl = process.env.API_BASE_URL || 'http://localhost:3000';
|
||||
const result = await proxyMediaRequest(`/media/categories/${categoryId}/icon`);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${apiBaseUrl}/media/categories/${categoryId}/icon`, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
const buffer = await response.arrayBuffer();
|
||||
|
||||
return new NextResponse(buffer, {
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
'Cache-Control': 'public, max-age=3600',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching category icon:', error);
|
||||
return new NextResponse(null, { status: 500 });
|
||||
if (result.isErr()) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
return new NextResponse(result.unwrap(), {
|
||||
headers: {
|
||||
'Content-Type': getMediaContentType('/media/categories'),
|
||||
'Cache-Control': getMediaCacheControl(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { proxyMediaRequest, getMediaContentType, getMediaCacheControl } from '@/lib/adapters/MediaProxyAdapter';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
@@ -6,27 +7,16 @@ export async function GET(
|
||||
) {
|
||||
const { leagueId } = params;
|
||||
|
||||
const apiBaseUrl = process.env.API_BASE_URL || 'http://localhost:3000';
|
||||
const result = await proxyMediaRequest(`/media/leagues/${leagueId}/cover`);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${apiBaseUrl}/media/leagues/${leagueId}/cover`, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
const buffer = await response.arrayBuffer();
|
||||
|
||||
return new NextResponse(buffer, {
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
'Cache-Control': 'public, max-age=3600',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching league cover:', error);
|
||||
return new NextResponse(null, { status: 500 });
|
||||
if (result.isErr()) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
return new NextResponse(result.unwrap(), {
|
||||
headers: {
|
||||
'Content-Type': getMediaContentType('/media/leagues'),
|
||||
'Cache-Control': getMediaCacheControl(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { proxyMediaRequest, getMediaContentType, getMediaCacheControl } from '@/lib/adapters/MediaProxyAdapter';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
@@ -6,27 +7,16 @@ export async function GET(
|
||||
) {
|
||||
const { leagueId } = params;
|
||||
|
||||
const apiBaseUrl = process.env.API_BASE_URL || 'http://localhost:3000';
|
||||
const result = await proxyMediaRequest(`/media/leagues/${leagueId}/logo`);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${apiBaseUrl}/media/leagues/${leagueId}/logo`, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
const buffer = await response.arrayBuffer();
|
||||
|
||||
return new NextResponse(buffer, {
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
'Cache-Control': 'public, max-age=3600',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching league logo:', error);
|
||||
return new NextResponse(null, { status: 500 });
|
||||
if (result.isErr()) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
return new NextResponse(result.unwrap(), {
|
||||
headers: {
|
||||
'Content-Type': getMediaContentType('/media/leagues'),
|
||||
'Cache-Control': getMediaCacheControl(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { proxyMediaRequest, getMediaContentType, getMediaCacheControl } from '@/lib/adapters/MediaProxyAdapter';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
@@ -6,27 +7,16 @@ export async function GET(
|
||||
) {
|
||||
const { sponsorId } = params;
|
||||
|
||||
const apiBaseUrl = process.env.API_BASE_URL || 'http://localhost:3000';
|
||||
const result = await proxyMediaRequest(`/media/sponsors/${sponsorId}/logo`);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${apiBaseUrl}/media/sponsors/${sponsorId}/logo`, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
const buffer = await response.arrayBuffer();
|
||||
|
||||
return new NextResponse(buffer, {
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
'Cache-Control': 'public, max-age=3600',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching sponsor logo:', error);
|
||||
return new NextResponse(null, { status: 500 });
|
||||
if (result.isErr()) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
return new NextResponse(result.unwrap(), {
|
||||
headers: {
|
||||
'Content-Type': getMediaContentType('/media/sponsors'),
|
||||
'Cache-Control': getMediaCacheControl(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { proxyMediaRequest, getMediaContentType, getMediaCacheControl } from '@/lib/adapters/MediaProxyAdapter';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
@@ -6,33 +7,16 @@ export async function GET(
|
||||
) {
|
||||
const { teamId } = params;
|
||||
|
||||
// In test environment, proxy to the mock API
|
||||
// In production, this would fetch from the actual API
|
||||
const apiBaseUrl = process.env.API_BASE_URL || 'http://localhost:3000';
|
||||
const result = await proxyMediaRequest(`/media/teams/${teamId}/logo`);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${apiBaseUrl}/media/teams/${teamId}/logo`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// Return a fallback image or 404
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
const buffer = await response.arrayBuffer();
|
||||
|
||||
return new NextResponse(buffer, {
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
'Cache-Control': 'public, max-age=3600',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching team logo:', error);
|
||||
return new NextResponse(null, { status: 500 });
|
||||
if (result.isErr()) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
return new NextResponse(result.unwrap(), {
|
||||
headers: {
|
||||
'Content-Type': getMediaContentType('/media/teams'),
|
||||
'Cache-Control': getMediaCacheControl(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { proxyMediaRequest, getMediaContentType, getMediaCacheControl } from '@/lib/adapters/MediaProxyAdapter';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
@@ -6,27 +7,16 @@ export async function GET(
|
||||
) {
|
||||
const { trackId } = params;
|
||||
|
||||
const apiBaseUrl = process.env.API_BASE_URL || 'http://localhost:3000';
|
||||
const result = await proxyMediaRequest(`/media/tracks/${trackId}/image`);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${apiBaseUrl}/media/tracks/${trackId}/image`, {
|
||||
method: 'GET',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
const buffer = await response.arrayBuffer();
|
||||
|
||||
return new NextResponse(buffer, {
|
||||
headers: {
|
||||
'Content-Type': 'image/png',
|
||||
'Cache-Control': 'public, max-age=3600',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching track image:', error);
|
||||
return new NextResponse(null, { status: 500 });
|
||||
if (result.isErr()) {
|
||||
return new NextResponse(null, { status: 404 });
|
||||
}
|
||||
|
||||
return new NextResponse(result.unwrap(), {
|
||||
headers: {
|
||||
'Content-Type': getMediaContentType('/media/tracks'),
|
||||
'Cache-Control': getMediaCacheControl(),
|
||||
},
|
||||
});
|
||||
}
|
||||
71
apps/website/app/onboarding/OnboardingWizardClient.tsx
Normal file
71
apps/website/app/onboarding/OnboardingWizardClient.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { OnboardingWizard } from '@/components/onboarding/OnboardingWizard';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
import { completeOnboardingAction, generateAvatarsAction } from './actions';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
|
||||
export function OnboardingWizardClient() {
|
||||
const router = useRouter();
|
||||
const { session } = useAuth();
|
||||
|
||||
const handleCompleteOnboarding = async (input: {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
displayName: string;
|
||||
country: string;
|
||||
timezone?: string;
|
||||
}) => {
|
||||
try {
|
||||
const result = await completeOnboardingAction(input);
|
||||
|
||||
if (result.isErr()) {
|
||||
return { success: false, error: result.getError() };
|
||||
}
|
||||
|
||||
router.push(routes.protected.dashboard);
|
||||
router.refresh();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: 'Failed to complete onboarding' };
|
||||
}
|
||||
};
|
||||
|
||||
const handleGenerateAvatars = async (params: {
|
||||
facePhotoData: string;
|
||||
suitColor: string;
|
||||
}) => {
|
||||
if (!session?.user?.userId) {
|
||||
return { success: false, error: 'Not authenticated' };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await generateAvatarsAction({
|
||||
userId: session.user.userId,
|
||||
facePhotoData: params.facePhotoData,
|
||||
suitColor: params.suitColor,
|
||||
});
|
||||
|
||||
if (result.isErr()) {
|
||||
return { success: false, error: result.getError() };
|
||||
}
|
||||
|
||||
const data = result.unwrap();
|
||||
return { success: true, data };
|
||||
} catch (error) {
|
||||
return { success: false, error: 'Failed to generate avatars' };
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<OnboardingWizard
|
||||
onCompleted={() => {
|
||||
router.push(routes.protected.dashboard);
|
||||
router.refresh();
|
||||
}}
|
||||
onCompleteOnboarding={handleCompleteOnboarding}
|
||||
onGenerateAvatars={handleGenerateAvatars}
|
||||
/>
|
||||
);
|
||||
}
|
||||
53
apps/website/app/onboarding/actions.ts
Normal file
53
apps/website/app/onboarding/actions.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
'use server';
|
||||
|
||||
import { Result } from '@/lib/contracts/Result';
|
||||
import { CompleteOnboardingMutation } from '@/lib/mutations/onboarding/CompleteOnboardingMutation';
|
||||
import { GenerateAvatarsMutation } from '@/lib/mutations/onboarding/GenerateAvatarsMutation';
|
||||
import { CompleteOnboardingInputDTO } from '@/lib/types/generated/CompleteOnboardingInputDTO';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
|
||||
/**
|
||||
* Complete onboarding - thin wrapper around mutation
|
||||
*
|
||||
* Pattern: Server Action → Mutation → Service → API Client
|
||||
*
|
||||
* Authentication is handled automatically by the API via cookies.
|
||||
* The BaseApiClient includes credentials: 'include', so cookies are sent automatically.
|
||||
* If authentication fails, the API returns 401/403 which gets converted to domain errors.
|
||||
*/
|
||||
export async function completeOnboardingAction(
|
||||
input: CompleteOnboardingInputDTO
|
||||
): Promise<Result<{ success: boolean }, string>> {
|
||||
const mutation = new CompleteOnboardingMutation();
|
||||
const result = await mutation.execute(input);
|
||||
|
||||
if (result.isErr()) {
|
||||
return Result.err(result.getError());
|
||||
}
|
||||
|
||||
revalidatePath(routes.protected.dashboard);
|
||||
return Result.ok({ success: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate avatars - thin wrapper around mutation
|
||||
*
|
||||
* Note: This action requires userId to be passed from the client.
|
||||
* The client should get userId from session and pass it as a parameter.
|
||||
*/
|
||||
export async function generateAvatarsAction(params: {
|
||||
userId: string;
|
||||
facePhotoData: string;
|
||||
suitColor: string;
|
||||
}): Promise<Result<{ success: boolean; avatarUrls?: string[] }, string>> {
|
||||
const mutation = new GenerateAvatarsMutation();
|
||||
const result = await mutation.execute(params);
|
||||
|
||||
if (result.isErr()) {
|
||||
return Result.err(result.getError());
|
||||
}
|
||||
|
||||
const data = result.unwrap();
|
||||
return Result.ok({ success: data.success, avatarUrls: data.avatarUrls });
|
||||
}
|
||||
@@ -1,6 +1,3 @@
|
||||
import { headers } from 'next/headers';
|
||||
import { createRouteGuard } from '@/lib/auth/createRouteGuard';
|
||||
|
||||
interface OnboardingLayoutProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
@@ -8,19 +5,22 @@ interface OnboardingLayoutProps {
|
||||
/**
|
||||
* Onboarding Layout
|
||||
*
|
||||
* Provides authentication protection for the onboarding flow.
|
||||
* Uses RouteGuard to enforce access control server-side.
|
||||
* Provides basic layout structure for onboarding pages.
|
||||
* Authentication is handled at the layout boundary.
|
||||
*/
|
||||
import { headers } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { createRouteGuard } from '@/lib/auth/createRouteGuard';
|
||||
|
||||
export default async function OnboardingLayout({ children }: OnboardingLayoutProps) {
|
||||
const headerStore = await headers();
|
||||
const pathname = headerStore.get('x-pathname') || '/';
|
||||
|
||||
|
||||
const guard = createRouteGuard();
|
||||
await guard.enforce({ pathname });
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const result = await guard.enforce({ pathname });
|
||||
if (result.type === 'redirect') {
|
||||
redirect(result.to);
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
@@ -1,66 +1,36 @@
|
||||
'use client';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { OnboardingWizardClient } from './OnboardingWizardClient';
|
||||
import { OnboardingPageQuery } from '@/lib/page-queries/page-queries/OnboardingPageQuery';
|
||||
import { SearchParamBuilder } from '@/lib/routing/search-params/SearchParamBuilder';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import OnboardingWizard from '@/components/onboarding/OnboardingWizard';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
|
||||
// Shared state components
|
||||
import { useCurrentDriver } from "@/lib/hooks/driver/useCurrentDriver";
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
|
||||
// Template component that accepts data
|
||||
function OnboardingTemplate({ data }: { data: any }) {
|
||||
return <OnboardingWizard />;
|
||||
}
|
||||
|
||||
export default function OnboardingPage() {
|
||||
const router = useRouter();
|
||||
const { session } = useAuth();
|
||||
|
||||
// Check if user is logged in
|
||||
const shouldRedirectToLogin = !session;
|
||||
|
||||
// Fetch current driver data using DI + React-Query
|
||||
const { data: driver, isLoading, error, refetch } = useCurrentDriver({
|
||||
enabled: !!session,
|
||||
});
|
||||
|
||||
const shouldRedirectToDashboard = !isLoading && Boolean(driver);
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldRedirectToLogin) {
|
||||
router.replace('/auth/login?returnTo=/onboarding');
|
||||
return;
|
||||
/**
|
||||
* Onboarding Page
|
||||
*
|
||||
* Server Component that handles authentication and authorization.
|
||||
* Redirects to login if not authenticated.
|
||||
* Redirects to dashboard if already onboarded.
|
||||
*/
|
||||
export default async function OnboardingPage() {
|
||||
// Use PageQuery to check if user is already onboarded
|
||||
const result = await OnboardingPageQuery.execute();
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
|
||||
if (error === 'unauthorized') {
|
||||
redirect(`${routes.auth.login}${SearchParamBuilder.auth(routes.protected.onboarding)}`);
|
||||
} else if (error === 'serverError' || error === 'networkError') {
|
||||
// Show error page or let them proceed with a warning
|
||||
// For now, we'll let them proceed
|
||||
}
|
||||
if (shouldRedirectToDashboard) {
|
||||
router.replace('/dashboard');
|
||||
} else {
|
||||
const viewData = result.unwrap();
|
||||
|
||||
if (viewData.isAlreadyOnboarded) {
|
||||
redirect(routes.protected.dashboard);
|
||||
}
|
||||
}, [router, shouldRedirectToLogin, shouldRedirectToDashboard]);
|
||||
|
||||
if (shouldRedirectToLogin) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (shouldRedirectToDashboard) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// For the StatefulPageWrapper, we need to provide data even if it's empty
|
||||
// The page is workflow-driven, not data-driven
|
||||
const wrapperData = driver || {};
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite">
|
||||
<StatefulPageWrapper
|
||||
data={wrapperData}
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
retry={refetch}
|
||||
Template={OnboardingTemplate}
|
||||
loading={{ variant: 'full-screen', message: 'Loading onboarding...' }}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
return <OnboardingWizardClient />;
|
||||
}
|
||||
134
apps/website/app/profile/ProfilePageClient.tsx
Normal file
134
apps/website/app/profile/ProfilePageClient.tsx
Normal file
@@ -0,0 +1,134 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Container from '@/components/ui/Container';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import Input from '@/components/ui/Input';
|
||||
import TabNavigation from '@/components/ui/TabNavigation';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
import type { Result } from '@/lib/contracts/Result';
|
||||
import type { ProfileViewData } from '@/lib/view-data/ProfileViewData';
|
||||
|
||||
type ProfileTab = 'overview' | 'history' | 'stats';
|
||||
|
||||
type SaveError = string | null;
|
||||
|
||||
interface ProfilePageClientProps {
|
||||
viewData: ProfileViewData;
|
||||
mode: 'profile-exists' | 'needs-profile';
|
||||
onSaveSettings: (updates: { bio?: string; country?: string }) => Promise<Result<void, string>>;
|
||||
}
|
||||
|
||||
export function ProfilePageClient({ viewData, mode, onSaveSettings }: ProfilePageClientProps) {
|
||||
const [activeTab, setActiveTab] = useState<ProfileTab>('overview');
|
||||
const [editMode, setEditMode] = useState(false);
|
||||
const [bio, setBio] = useState(viewData.driver.bio ?? '');
|
||||
const [countryCode, setCountryCode] = useState(viewData.driver.countryCode ?? '');
|
||||
const [saveError, setSaveError] = useState<SaveError>(null);
|
||||
|
||||
if (mode === 'needs-profile') {
|
||||
return (
|
||||
<Container size="md">
|
||||
<Heading level={1}>Create your driver profile</Heading>
|
||||
<Card>
|
||||
<p>Driver profile not found for this account.</p>
|
||||
<Link href={routes.protected.onboarding}>
|
||||
<Button variant="primary">Start onboarding</Button>
|
||||
</Link>
|
||||
</Card>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
if (editMode) {
|
||||
return (
|
||||
<Container size="md">
|
||||
<Heading level={1}>Edit profile</Heading>
|
||||
|
||||
<Card>
|
||||
<Heading level={3}>Profile</Heading>
|
||||
|
||||
<Input
|
||||
value={bio}
|
||||
onChange={(e) => setBio(e.target.value)}
|
||||
placeholder="Bio"
|
||||
/>
|
||||
|
||||
<Input
|
||||
value={countryCode}
|
||||
onChange={(e) => setCountryCode(e.target.value)}
|
||||
placeholder="Country code (e.g. DE)"
|
||||
/>
|
||||
|
||||
{saveError ? <p>{saveError}</p> : null}
|
||||
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={async () => {
|
||||
setSaveError(null);
|
||||
const result = await onSaveSettings({ bio, country: countryCode });
|
||||
if (result.isErr()) {
|
||||
setSaveError(result.getError());
|
||||
return;
|
||||
}
|
||||
setEditMode(false);
|
||||
}}
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
|
||||
<Button variant="secondary" onClick={() => setEditMode(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
</Card>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Container size="lg">
|
||||
<Heading level={1}>{viewData.driver.name || 'Profile'}</Heading>
|
||||
|
||||
<Button variant="primary" onClick={() => setEditMode(true)}>
|
||||
Edit profile
|
||||
</Button>
|
||||
|
||||
<TabNavigation
|
||||
tabs={[
|
||||
{ id: 'overview', label: 'Overview' },
|
||||
{ id: 'history', label: 'Race History' },
|
||||
{ id: 'stats', label: 'Detailed Stats' },
|
||||
]}
|
||||
activeTab={activeTab}
|
||||
onTabChange={(tabId) => setActiveTab(tabId as ProfileTab)}
|
||||
/>
|
||||
|
||||
{activeTab === 'overview' ? (
|
||||
<Card>
|
||||
<Heading level={3}>Driver</Heading>
|
||||
<p>{viewData.driver.countryCode}</p>
|
||||
<p>{viewData.driver.joinedAtLabel}</p>
|
||||
<p>{viewData.driver.bio ?? ''}</p>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{activeTab === 'history' ? (
|
||||
<Card>
|
||||
<Heading level={3}>Race history</Heading>
|
||||
<p>Race history is currently unavailable in this view.</p>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{activeTab === 'stats' ? (
|
||||
<Card>
|
||||
<Heading level={3}>Stats</Heading>
|
||||
<p>{viewData.stats?.ratingLabel ?? ''}</p>
|
||||
<p>{viewData.stats?.globalRankLabel ?? ''}</p>
|
||||
</Card>
|
||||
) : null}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
20
apps/website/app/profile/actions.ts
Normal file
20
apps/website/app/profile/actions.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
'use server';
|
||||
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { Result } from '@/lib/contracts/Result';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
import { UpdateDriverProfileMutation } from '@/lib/mutations/drivers/UpdateDriverProfileMutation';
|
||||
|
||||
export async function updateProfileAction(
|
||||
updates: { bio?: string; country?: string },
|
||||
): Promise<Result<void, string>> {
|
||||
const mutation = new UpdateDriverProfileMutation();
|
||||
const result = await mutation.execute({ bio: updates.bio, country: updates.country });
|
||||
|
||||
if (result.isErr()) {
|
||||
return Result.err(result.getError());
|
||||
}
|
||||
|
||||
revalidatePath(routes.protected.profile);
|
||||
return Result.ok(undefined);
|
||||
}
|
||||
@@ -1,26 +1,22 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { headers } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
import ProfileLayoutShell from '@/components/profile/ProfileLayoutShell';
|
||||
import { createRouteGuard } from '@/lib/auth/createRouteGuard';
|
||||
|
||||
interface ProfileLayoutProps {
|
||||
children: React.ReactNode;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Profile Layout
|
||||
*
|
||||
* Provides authentication protection for all profile-related routes.
|
||||
* Uses RouteGuard to enforce access control server-side.
|
||||
*/
|
||||
export default async function ProfileLayout({ children }: ProfileLayoutProps) {
|
||||
const headerStore = await headers();
|
||||
const pathname = headerStore.get('x-pathname') || '/';
|
||||
|
||||
|
||||
const guard = createRouteGuard();
|
||||
await guard.enforce({ pathname });
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const result = await guard.enforce({ pathname });
|
||||
if (result.type === 'redirect') {
|
||||
redirect(result.to);
|
||||
}
|
||||
|
||||
return <ProfileLayoutShell>{children}</ProfileLayoutShell>;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { ProfileLeaguesPageQuery } from '@/lib/page-queries/ProfileLeaguesPageQuery';
|
||||
import { ProfileLeaguesPageQuery } from '@/lib/page-queries/page-queries/ProfileLeaguesPageQuery';
|
||||
import { ProfileLeaguesPageClient } from './ProfileLeaguesPageClient';
|
||||
|
||||
export default async function ProfileLeaguesPage() {
|
||||
|
||||
@@ -1,164 +1,23 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import { Paintbrush, Upload, Car, Download, Trash2, Edit } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Container from '@/components/ui/Container';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
|
||||
interface DriverLiveryItem {
|
||||
id: string;
|
||||
carId: string;
|
||||
carName: string;
|
||||
thumbnailUrl: string;
|
||||
uploadedAt: Date;
|
||||
isValidated: boolean;
|
||||
}
|
||||
|
||||
export default function DriverLiveriesPage() {
|
||||
const [liveries] = useState<DriverLiveryItem[]>([]);
|
||||
|
||||
export default async function ProfileLiveriesPage() {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto py-12">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary-blue/10">
|
||||
<Paintbrush className="w-6 h-6 text-primary-blue" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-white">My Liveries</h1>
|
||||
<p className="text-sm text-gray-400">Manage your car liveries across leagues</p>
|
||||
</div>
|
||||
</div>
|
||||
<Link href="/profile/liveries/upload">
|
||||
<Button variant="primary">
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Upload Livery
|
||||
</Button>
|
||||
<Container size="md">
|
||||
<Heading level={1}>Liveries</Heading>
|
||||
<Card>
|
||||
<p>Livery management is currently unavailable.</p>
|
||||
<Link href={routes.protected.profile}>
|
||||
<Button variant="secondary">Back to profile</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Livery Collection */}
|
||||
{liveries.length === 0 ? (
|
||||
<Card>
|
||||
<div className="text-center py-16">
|
||||
<div className="w-20 h-20 mx-auto mb-6 rounded-full bg-iron-gray/50 flex items-center justify-center">
|
||||
<Car className="w-10 h-10 text-gray-500" />
|
||||
</div>
|
||||
<h3 className="text-xl font-medium text-white mb-3">No Liveries Yet</h3>
|
||||
<p className="text-sm text-gray-400 max-w-md mx-auto mb-6">
|
||||
Upload your first livery. Use the same livery across multiple leagues or create custom ones for each.
|
||||
</p>
|
||||
<Link href="/profile/liveries/upload">
|
||||
<Button variant="primary">
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
Upload Your First Livery
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{liveries.map((livery) => (
|
||||
<Card key={livery.id} className="overflow-hidden hover:border-primary-blue/50 transition-colors">
|
||||
{/* Livery Preview */}
|
||||
<div className="aspect-video bg-deep-graphite rounded-lg mb-4 flex items-center justify-center border border-charcoal-outline">
|
||||
<Car className="w-16 h-16 text-gray-600" />
|
||||
</div>
|
||||
|
||||
{/* Livery Info */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold text-white">{livery.carName}</h3>
|
||||
{livery.isValidated ? (
|
||||
<span className="px-2 py-0.5 text-xs bg-performance-green/10 text-performance-green border border-performance-green/30 rounded-full">
|
||||
Validated
|
||||
</span>
|
||||
) : (
|
||||
<span className="px-2 py-0.5 text-xs bg-warning-amber/10 text-warning-amber border border-warning-amber/30 rounded-full">
|
||||
Pending
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-gray-500">
|
||||
Uploaded {new Date(livery.uploadedAt).toLocaleDateString()}
|
||||
</p>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button variant="secondary" className="flex-1 px-3 py-1.5">
|
||||
<Edit className="w-4 h-4 mr-1" />
|
||||
Edit
|
||||
</Button>
|
||||
<Button variant="secondary" className="px-3 py-1.5">
|
||||
<Download className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button variant="danger" className="px-3 py-1.5">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Info Section */}
|
||||
<div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<Card>
|
||||
<h3 className="text-lg font-semibold text-white mb-3">Livery Requirements</h3>
|
||||
<ul className="space-y-2 text-sm text-gray-400">
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-primary-blue mt-0.5">•</span>
|
||||
PNG or DDS format, max 5MB
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-primary-blue mt-0.5">•</span>
|
||||
No logos or text allowed on base livery
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-primary-blue mt-0.5">•</span>
|
||||
Sponsor decals are added by league admins
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-primary-blue mt-0.5">•</span>
|
||||
Your driver name and number are added automatically
|
||||
</li>
|
||||
</ul>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<h3 className="text-lg font-semibold text-white mb-3">How It Works</h3>
|
||||
<ol className="space-y-2 text-sm text-gray-400">
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-primary-blue font-semibold">1.</span>
|
||||
Upload your base livery for each car you race
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-primary-blue font-semibold">2.</span>
|
||||
Position your name and number decals
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-primary-blue font-semibold">3.</span>
|
||||
League admins add sponsor logos
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="text-primary-blue font-semibold">4.</span>
|
||||
Download the final pack with all decals burned in
|
||||
</li>
|
||||
</ol>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Alpha Notice */}
|
||||
<div className="mt-6 rounded-lg bg-warning-amber/10 border border-warning-amber/30 p-4">
|
||||
<p className="text-xs text-gray-400">
|
||||
<strong className="text-warning-amber">Alpha Note:</strong> Livery management is demonstration-only.
|
||||
In production, liveries are stored in cloud storage and composited with sponsor decals.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Link href={routes.protected.profileLiveryUpload}>
|
||||
<Button variant="primary">Upload livery</Button>
|
||||
</Link>
|
||||
</Card>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,405 +1,20 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Link from 'next/link';
|
||||
import Button from '@/components/ui/Button';
|
||||
import { Upload, Check, AlertTriangle, Car, RotateCw, Gamepad2 } from 'lucide-react';
|
||||
|
||||
interface DecalPosition {
|
||||
id: string;
|
||||
type: 'name' | 'number' | 'rank';
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
rotation: number;
|
||||
}
|
||||
|
||||
interface GameOption {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface CarOption {
|
||||
id: string;
|
||||
name: string;
|
||||
manufacturer: string;
|
||||
gameId: string;
|
||||
}
|
||||
|
||||
// Mock data - in production these would come from API
|
||||
const GAMES: GameOption[] = [
|
||||
{ id: 'iracing', name: 'iRacing' },
|
||||
{ id: 'acc', name: 'Assetto Corsa Competizione' },
|
||||
{ id: 'ac', name: 'Assetto Corsa' },
|
||||
{ id: 'rf2', name: 'rFactor 2' },
|
||||
{ id: 'ams2', name: 'Automobilista 2' },
|
||||
{ id: 'lmu', name: 'Le Mans Ultimate' },
|
||||
];
|
||||
|
||||
const CARS: CarOption[] = [
|
||||
// iRacing cars
|
||||
{ id: 'ir-porsche-911-gt3r', name: '911 GT3 R', manufacturer: 'Porsche', gameId: 'iracing' },
|
||||
{ id: 'ir-ferrari-296-gt3', name: '296 GT3', manufacturer: 'Ferrari', gameId: 'iracing' },
|
||||
{ id: 'ir-bmw-m4-gt3', name: 'M4 GT3', manufacturer: 'BMW', gameId: 'iracing' },
|
||||
{ id: 'ir-mercedes-amg-gt3', name: 'AMG GT3 Evo', manufacturer: 'Mercedes-AMG', gameId: 'iracing' },
|
||||
{ id: 'ir-audi-r8-gt3', name: 'R8 LMS GT3 Evo II', manufacturer: 'Audi', gameId: 'iracing' },
|
||||
{ id: 'ir-dallara-f3', name: 'F3', manufacturer: 'Dallara', gameId: 'iracing' },
|
||||
{ id: 'ir-dallara-ir18', name: 'IR-18', manufacturer: 'Dallara', gameId: 'iracing' },
|
||||
// ACC cars
|
||||
{ id: 'acc-porsche-911-gt3r', name: '911 GT3 R', manufacturer: 'Porsche', gameId: 'acc' },
|
||||
{ id: 'acc-ferrari-296-gt3', name: '296 GT3', manufacturer: 'Ferrari', gameId: 'acc' },
|
||||
{ id: 'acc-bmw-m4-gt3', name: 'M4 GT3', manufacturer: 'BMW', gameId: 'acc' },
|
||||
{ id: 'acc-mercedes-amg-gt3', name: 'AMG GT3 Evo', manufacturer: 'Mercedes-AMG', gameId: 'acc' },
|
||||
{ id: 'acc-lamborghini-huracan-gt3', name: 'Huracán GT3 Evo2', manufacturer: 'Lamborghini', gameId: 'acc' },
|
||||
{ id: 'acc-aston-martin-v8-gt3', name: 'V8 Vantage GT3', manufacturer: 'Aston Martin', gameId: 'acc' },
|
||||
// AC cars
|
||||
{ id: 'ac-porsche-911-gt3r', name: '911 GT3 R', manufacturer: 'Porsche', gameId: 'ac' },
|
||||
{ id: 'ac-ferrari-488-gt3', name: '488 GT3', manufacturer: 'Ferrari', gameId: 'ac' },
|
||||
{ id: 'ac-lotus-exos', name: 'Exos 125', manufacturer: 'Lotus', gameId: 'ac' },
|
||||
// rFactor 2 cars
|
||||
{ id: 'rf2-porsche-911-gt3r', name: '911 GT3 R', manufacturer: 'Porsche', gameId: 'rf2' },
|
||||
{ id: 'rf2-bmw-m4-gt3', name: 'M4 GT3', manufacturer: 'BMW', gameId: 'rf2' },
|
||||
// AMS2 cars
|
||||
{ id: 'ams2-porsche-911-gt3r', name: '911 GT3 R', manufacturer: 'Porsche', gameId: 'ams2' },
|
||||
{ id: 'ams2-mclaren-720s-gt3', name: '720S GT3', manufacturer: 'McLaren', gameId: 'ams2' },
|
||||
// LMU cars
|
||||
{ id: 'lmu-porsche-963', name: '963 LMDh', manufacturer: 'Porsche', gameId: 'lmu' },
|
||||
{ id: 'lmu-ferrari-499p', name: '499P', manufacturer: 'Ferrari', gameId: 'lmu' },
|
||||
{ id: 'lmu-toyota-gr010', name: 'GR010', manufacturer: 'Toyota', gameId: 'lmu' },
|
||||
];
|
||||
|
||||
export default function LiveryUploadPage() {
|
||||
const router = useRouter();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [uploadedFile, setUploadedFile] = useState<File | null>(null);
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
||||
const [selectedGame, setSelectedGame] = useState<string>('');
|
||||
const [selectedCar, setSelectedCar] = useState<string>('');
|
||||
const [filteredCars, setFilteredCars] = useState<CarOption[]>([]);
|
||||
const [decals, setDecals] = useState<DecalPosition[]>([
|
||||
{ id: 'name', type: 'name', x: 0.1, y: 0.8, width: 0.2, height: 0.05, rotation: 0 },
|
||||
{ id: 'number', type: 'number', x: 0.8, y: 0.1, width: 0.15, height: 0.15, rotation: 0 },
|
||||
{ id: 'rank', type: 'rank', x: 0.05, y: 0.1, width: 0.1, height: 0.1, rotation: 0 },
|
||||
]);
|
||||
const [activeDecal, setActiveDecal] = useState<string | null>(null);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
// Filter cars when game changes
|
||||
useEffect(() => {
|
||||
if (selectedGame) {
|
||||
const cars = CARS.filter(car => car.gameId === selectedGame);
|
||||
setFilteredCars(cars);
|
||||
setSelectedCar(''); // Reset car selection when game changes
|
||||
} else {
|
||||
setFilteredCars([]);
|
||||
setSelectedCar('');
|
||||
}
|
||||
}, [selectedGame]);
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
setUploadedFile(file);
|
||||
const url = URL.createObjectURL(file);
|
||||
setPreviewUrl(url);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
const file = e.dataTransfer.files?.[0];
|
||||
if (file) {
|
||||
setUploadedFile(file);
|
||||
const url = URL.createObjectURL(file);
|
||||
setPreviewUrl(url);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!uploadedFile || !selectedGame || !selectedCar) return;
|
||||
|
||||
setSubmitting(true);
|
||||
|
||||
try {
|
||||
// Alpha: In-memory only
|
||||
console.log('Livery upload:', {
|
||||
file: uploadedFile.name,
|
||||
gameId: selectedGame,
|
||||
carId: selectedCar,
|
||||
decals,
|
||||
});
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
alert('Livery uploaded successfully.');
|
||||
router.push('/profile/liveries');
|
||||
} catch (err) {
|
||||
console.error('Upload failed:', err);
|
||||
alert('Upload failed. Try again.');
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
import Card from '@/components/ui/Card';
|
||||
import Container from '@/components/ui/Container';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
|
||||
export default async function ProfileLiveryUploadPage() {
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto py-12">
|
||||
{/* Header */}
|
||||
<div className="mb-8">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary-blue/10">
|
||||
<Upload className="w-6 h-6 text-primary-blue" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-white">Upload Livery</h1>
|
||||
<p className="text-sm text-gray-400">Add a new livery to your collection</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Upload Section */}
|
||||
<Card>
|
||||
<h2 className="text-lg font-semibold text-white mb-4">Livery File</h2>
|
||||
|
||||
{/* Game Selection */}
|
||||
<div className="mb-4">
|
||||
<label className="block text-sm font-medium text-gray-300 mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Gamepad2 className="w-4 h-4" />
|
||||
Select Game
|
||||
</div>
|
||||
</label>
|
||||
<select
|
||||
value={selectedGame}
|
||||
onChange={(e) => setSelectedGame(e.target.value)}
|
||||
className="w-full rounded-lg border border-charcoal-outline bg-iron-gray px-3 py-2 text-sm text-white focus:border-primary-blue focus:outline-none"
|
||||
>
|
||||
<option value="">Choose a game...</option>
|
||||
{GAMES.map((game) => (
|
||||
<option key={game.id} value={game.id}>
|
||||
{game.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Car Selection */}
|
||||
<div className="mb-6">
|
||||
<label className="block text-sm font-medium text-gray-300 mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Car className="w-4 h-4" />
|
||||
Select Car
|
||||
</div>
|
||||
</label>
|
||||
<select
|
||||
value={selectedCar}
|
||||
onChange={(e) => setSelectedCar(e.target.value)}
|
||||
disabled={!selectedGame}
|
||||
className="w-full rounded-lg border border-charcoal-outline bg-iron-gray px-3 py-2 text-sm text-white focus:border-primary-blue focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<option value="">{selectedGame ? 'Choose a car...' : 'Select a game first...'}</option>
|
||||
{filteredCars.map((car) => (
|
||||
<option key={car.id} value={car.id}>
|
||||
{car.manufacturer} {car.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{selectedGame && filteredCars.length === 0 && (
|
||||
<p className="text-xs text-gray-500 mt-1">No cars available for this game</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* File Upload */}
|
||||
<div
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
onDrop={handleDrop}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
className={`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${
|
||||
previewUrl
|
||||
? 'border-performance-green/50 bg-performance-green/5'
|
||||
: 'border-charcoal-outline hover:border-primary-blue/50 hover:bg-primary-blue/5'
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".png,.dds"
|
||||
onChange={handleFileChange}
|
||||
className="hidden"
|
||||
/>
|
||||
|
||||
{previewUrl ? (
|
||||
<div className="space-y-3">
|
||||
<Check className="w-12 h-12 text-performance-green mx-auto" />
|
||||
<p className="text-sm text-white font-medium">{uploadedFile?.name}</p>
|
||||
<p className="text-xs text-gray-500">Click to replace</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<Upload className="w-12 h-12 text-gray-500 mx-auto" />
|
||||
<p className="text-sm text-gray-400">
|
||||
Drop your livery here or click to browse
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">PNG or DDS, max 5MB</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Validation Warning */}
|
||||
<div className="mt-4 p-3 rounded-lg bg-warning-amber/10 border border-warning-amber/30">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertTriangle className="w-4 h-4 text-warning-amber shrink-0 mt-0.5" />
|
||||
<p className="text-xs text-gray-400">
|
||||
<strong className="text-warning-amber">No logos or text allowed.</strong>{' '}
|
||||
Your base livery must be clean. Sponsor logos are added by league admins.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Decal Editor */}
|
||||
<Card>
|
||||
<h2 className="text-lg font-semibold text-white mb-4">Position Decals</h2>
|
||||
<p className="text-sm text-gray-400 mb-4">
|
||||
Drag to position your driver name, number, and rank badge.
|
||||
</p>
|
||||
|
||||
{/* Preview Canvas */}
|
||||
<div className="relative aspect-video bg-deep-graphite rounded-lg border border-charcoal-outline overflow-hidden mb-4">
|
||||
{previewUrl ? (
|
||||
<img
|
||||
src={previewUrl}
|
||||
alt="Livery preview"
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full flex items-center justify-center">
|
||||
<Car className="w-20 h-20 text-gray-600" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Decal Placeholders */}
|
||||
{decals.map((decal) => (
|
||||
<div
|
||||
key={decal.id}
|
||||
onClick={() => setActiveDecal(decal.id === activeDecal ? null : decal.id)}
|
||||
className={`absolute cursor-move border-2 rounded flex items-center justify-center text-xs font-medium transition-all ${
|
||||
activeDecal === decal.id
|
||||
? 'border-primary-blue bg-primary-blue/20 text-primary-blue'
|
||||
: 'border-white/30 bg-black/30 text-white/70'
|
||||
}`}
|
||||
style={{
|
||||
left: `${decal.x * 100}%`,
|
||||
top: `${decal.y * 100}%`,
|
||||
width: `${decal.width * 100}%`,
|
||||
height: `${decal.height * 100}%`,
|
||||
transform: `rotate(${decal.rotation}deg)`,
|
||||
}}
|
||||
>
|
||||
{decal.type === 'name' && 'NAME'}
|
||||
{decal.type === 'number' && '#'}
|
||||
{decal.type === 'rank' && 'RANK'}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Decal Controls */}
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{decals.map((decal) => (
|
||||
<button
|
||||
key={decal.id}
|
||||
onClick={() => setActiveDecal(decal.id === activeDecal ? null : decal.id)}
|
||||
className={`p-3 rounded-lg border text-center transition-all ${
|
||||
activeDecal === decal.id
|
||||
? 'border-primary-blue bg-primary-blue/10 text-primary-blue'
|
||||
: 'border-charcoal-outline bg-iron-gray/30 text-gray-400 hover:border-primary-blue/50'
|
||||
}`}
|
||||
>
|
||||
<div className="text-xs font-medium capitalize mb-1">{decal.type}</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{Math.round(decal.x * 100)}%, {Math.round(decal.y * 100)}%
|
||||
</div>
|
||||
<div className="text-xs text-gray-600">
|
||||
{decal.rotation}°
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Rotation Controls */}
|
||||
{activeDecal && (
|
||||
<div className="mt-4 p-3 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-xs font-medium text-gray-300 capitalize">
|
||||
{decals.find(d => d.id === activeDecal)?.type} Rotation
|
||||
</span>
|
||||
<span className="text-xs text-gray-500">
|
||||
{decals.find(d => d.id === activeDecal)?.rotation}°
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
max="360"
|
||||
step="15"
|
||||
value={decals.find(d => d.id === activeDecal)?.rotation ?? 0}
|
||||
onChange={(e) => {
|
||||
const rotation = parseInt(e.target.value, 10);
|
||||
setDecals(decals.map(d =>
|
||||
d.id === activeDecal ? { ...d, rotation } : d
|
||||
));
|
||||
}}
|
||||
className="flex-1 h-2 bg-charcoal-outline rounded-lg appearance-none cursor-pointer accent-primary-blue"
|
||||
/>
|
||||
<button
|
||||
onClick={() => {
|
||||
setDecals(decals.map(d =>
|
||||
d.id === activeDecal ? { ...d, rotation: (d.rotation + 90) % 360 } : d
|
||||
));
|
||||
}}
|
||||
className="p-2 rounded-lg border border-charcoal-outline bg-iron-gray/30 hover:bg-iron-gray/50 transition-colors"
|
||||
title="Rotate 90°"
|
||||
>
|
||||
<RotateCw className="w-4 h-4 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-gray-500 mt-4">
|
||||
Click a decal above, then drag on preview to reposition. Use the slider or button to rotate.
|
||||
</p>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="mt-6 flex gap-3">
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={handleSubmit}
|
||||
disabled={!uploadedFile || !selectedGame || !selectedCar || submitting}
|
||||
>
|
||||
{submitting ? 'Uploading...' : 'Upload Livery'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => router.back()}
|
||||
disabled={submitting}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Alpha Notice */}
|
||||
<div className="mt-6 rounded-lg bg-warning-amber/10 border border-warning-amber/30 p-4">
|
||||
<p className="text-xs text-gray-400">
|
||||
<strong className="text-warning-amber">Alpha Note:</strong> Livery upload is demonstration-only.
|
||||
Decal positioning and image validation are not functional in this preview.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Container size="md">
|
||||
<Heading level={1}>Upload livery</Heading>
|
||||
<Card>
|
||||
<p>Livery upload is currently unavailable.</p>
|
||||
<Link href={routes.protected.profileLiveries}>
|
||||
<Button variant="secondary">Back to liveries</Button>
|
||||
</Link>
|
||||
</Card>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,226 +1,20 @@
|
||||
'use client';
|
||||
import Link from 'next/link';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Container from '@/components/ui/Container';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { routes } from '@/lib/routing/RouteConfig';
|
||||
|
||||
import { Bell, Shield, Eye, Volume2 } from 'lucide-react';
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
|
||||
interface SettingsData {
|
||||
// Settings page is static, no data needed
|
||||
}
|
||||
|
||||
function SettingsTemplate({ data }: { data: SettingsData }) {
|
||||
export default async function ProfileSettingsPage() {
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite">
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<h1 className="text-2xl font-bold text-white mb-8">Settings</h1>
|
||||
|
||||
<div className="space-y-8">
|
||||
{/* Notification Settings */}
|
||||
<section className="bg-iron-gray rounded-lg border border-charcoal-outline p-6">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<Bell className="h-5 w-5 text-primary-blue" />
|
||||
<h2 className="text-lg font-semibold text-white">Notifications</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between py-3 border-b border-charcoal-outline">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Protest Filed Against You</p>
|
||||
<p className="text-xs text-gray-400">Get notified when someone files a protest involving you</p>
|
||||
</div>
|
||||
<select className="bg-deep-graphite border border-charcoal-outline rounded px-3 py-1.5 text-sm text-white">
|
||||
<option value="modal">Modal (Blocking)</option>
|
||||
<option value="toast">Toast (Popup)</option>
|
||||
<option value="silent">Silent (Notification Center)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-3 border-b border-charcoal-outline">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Vote Requested</p>
|
||||
<p className="text-xs text-gray-400">Get notified when your vote is needed on a protest</p>
|
||||
</div>
|
||||
<select className="bg-deep-graphite border border-charcoal-outline rounded px-3 py-1.5 text-sm text-white">
|
||||
<option value="modal">Modal (Blocking)</option>
|
||||
<option value="toast">Toast (Popup)</option>
|
||||
<option value="silent">Silent (Notification Center)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-3 border-b border-charcoal-outline">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Defense Required</p>
|
||||
<p className="text-xs text-gray-400">Get notified when you need to submit a defense</p>
|
||||
</div>
|
||||
<select className="bg-deep-graphite border border-charcoal-outline rounded px-3 py-1.5 text-sm text-white">
|
||||
<option value="modal">Modal (Blocking)</option>
|
||||
<option value="toast">Toast (Popup)</option>
|
||||
<option value="silent">Silent (Notification Center)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-3 border-b border-charcoal-outline">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Penalty Issued</p>
|
||||
<p className="text-xs text-gray-400">Get notified when you receive a penalty</p>
|
||||
</div>
|
||||
<select className="bg-deep-graphite border border-charcoal-outline rounded px-3 py-1.5 text-sm text-white">
|
||||
<option value="toast" selected>Toast (Popup)</option>
|
||||
<option value="modal">Modal (Blocking)</option>
|
||||
<option value="silent">Silent (Notification Center)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-3 border-b border-charcoal-outline">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Race Starting Soon</p>
|
||||
<p className="text-xs text-gray-400">Reminder before scheduled races begin</p>
|
||||
</div>
|
||||
<select className="bg-deep-graphite border border-charcoal-outline rounded px-3 py-1.5 text-sm text-white">
|
||||
<option value="toast">Toast (Popup)</option>
|
||||
<option value="modal">Modal (Blocking)</option>
|
||||
<option value="silent">Silent (Notification Center)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">League Announcements</p>
|
||||
<p className="text-xs text-gray-400">Updates from league administrators</p>
|
||||
</div>
|
||||
<select className="bg-deep-graphite border border-charcoal-outline rounded px-3 py-1.5 text-sm text-white">
|
||||
<option value="silent">Silent (Notification Center)</option>
|
||||
<option value="toast">Toast (Popup)</option>
|
||||
<option value="modal">Modal (Blocking)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Display Settings */}
|
||||
<section className="bg-iron-gray rounded-lg border border-charcoal-outline p-6">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<Eye className="h-5 w-5 text-primary-blue" />
|
||||
<h2 className="text-lg font-semibold text-white">Display</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between py-3 border-b border-charcoal-outline">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Toast Duration</p>
|
||||
<p className="text-xs text-gray-400">How long toast notifications stay visible</p>
|
||||
</div>
|
||||
<select className="bg-deep-graphite border border-charcoal-outline rounded px-3 py-1.5 text-sm text-white">
|
||||
<option value="3000">3 seconds</option>
|
||||
<option value="5000" selected>5 seconds</option>
|
||||
<option value="8000">8 seconds</option>
|
||||
<option value="10000">10 seconds</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Toast Position</p>
|
||||
<p className="text-xs text-gray-400">Where toast notifications appear on screen</p>
|
||||
</div>
|
||||
<select className="bg-deep-graphite border border-charcoal-outline rounded px-3 py-1.5 text-sm text-white">
|
||||
<option value="top-right">Top Right</option>
|
||||
<option value="top-left">Top Left</option>
|
||||
<option value="bottom-right" selected>Bottom Right</option>
|
||||
<option value="bottom-left">Bottom Left</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Sound Settings */}
|
||||
<section className="bg-iron-gray rounded-lg border border-charcoal-outline p-6">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<Volume2 className="h-5 w-5 text-primary-blue" />
|
||||
<h2 className="text-lg font-semibold text-white">Sound</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between py-3 border-b border-charcoal-outline">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Notification Sounds</p>
|
||||
<p className="text-xs text-gray-400">Play sounds for new notifications</p>
|
||||
</div>
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input type="checkbox" className="sr-only peer" defaultChecked />
|
||||
<div className="w-11 h-6 bg-charcoal-outline peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-blue"></div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Urgent Notification Sound</p>
|
||||
<p className="text-xs text-gray-400">Special sound for modal notifications</p>
|
||||
</div>
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input type="checkbox" className="sr-only peer" defaultChecked />
|
||||
<div className="w-11 h-6 bg-charcoal-outline peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-blue"></div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Privacy Settings */}
|
||||
<section className="bg-iron-gray rounded-lg border border-charcoal-outline p-6">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<Shield className="h-5 w-5 text-primary-blue" />
|
||||
<h2 className="text-lg font-semibold text-white">Privacy</h2>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between py-3 border-b border-charcoal-outline">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Show Online Status</p>
|
||||
<p className="text-xs text-gray-400">Let others see when you're online</p>
|
||||
</div>
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input type="checkbox" className="sr-only peer" defaultChecked />
|
||||
<div className="w-11 h-6 bg-charcoal-outline peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-blue"></div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">Public Profile</p>
|
||||
<p className="text-xs text-gray-400">Allow non-league members to view your profile</p>
|
||||
</div>
|
||||
<label className="relative inline-flex items-center cursor-pointer">
|
||||
<input type="checkbox" className="sr-only peer" defaultChecked />
|
||||
<div className="w-11 h-6 bg-charcoal-outline peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary-blue"></div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Save Button */}
|
||||
<div className="flex justify-end">
|
||||
<button className="px-6 py-2 bg-primary-blue text-white font-medium rounded-lg hover:bg-primary-blue/90 transition-colors">
|
||||
Save Changes
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Container size="md">
|
||||
<Heading level={1}>Settings</Heading>
|
||||
<Card>
|
||||
<p>Settings are currently unavailable.</p>
|
||||
<Link href={routes.protected.profile}>
|
||||
<Button variant="secondary">Back to profile</Button>
|
||||
</Link>
|
||||
</Card>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SettingsPage() {
|
||||
return (
|
||||
<StatefulPageWrapper
|
||||
data={{} as SettingsData}
|
||||
isLoading={false}
|
||||
error={null}
|
||||
Template={SettingsTemplate}
|
||||
loading={{ variant: 'skeleton', message: 'Loading settings...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
empty={{
|
||||
title: 'No settings available',
|
||||
description: 'Unable to load settings page',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
'use client';
|
||||
|
||||
import type { Result } from '@/lib/contracts/Result';
|
||||
import type { SponsorshipRequestsViewData } from '@/lib/view-data/SponsorshipRequestsViewData';
|
||||
import { SponsorshipRequestsTemplate } from '@/templates/SponsorshipRequestsTemplate';
|
||||
|
||||
interface SponsorshipRequestsPageClientProps {
|
||||
viewData: SponsorshipRequestsViewData;
|
||||
onAccept: (requestId: string) => Promise<Result<void, string>>;
|
||||
onReject: (requestId: string, reason?: string) => Promise<Result<void, string>>;
|
||||
}
|
||||
|
||||
export function SponsorshipRequestsPageClient({ viewData, onAccept, onReject }: SponsorshipRequestsPageClientProps) {
|
||||
return (
|
||||
<SponsorshipRequestsTemplate
|
||||
data={viewData.sections}
|
||||
onAccept={async (requestId) => {
|
||||
await onAccept(requestId);
|
||||
}}
|
||||
onReject={async (requestId, reason) => {
|
||||
await onReject(requestId, reason);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
26
apps/website/app/profile/sponsorship-requests/actions.ts
Normal file
26
apps/website/app/profile/sponsorship-requests/actions.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { AcceptSponsorshipRequestMutation } from '@/lib/mutations/sponsors/AcceptSponsorshipRequestMutation';
|
||||
import { RejectSponsorshipRequestMutation } from '@/lib/mutations/sponsors/RejectSponsorshipRequestMutation';
|
||||
import type { AcceptSponsorshipRequestCommand } from '@/lib/services/sponsors/SponsorshipRequestsService';
|
||||
import type { RejectSponsorshipRequestCommand } from '@/lib/services/sponsors/SponsorshipRequestsService';
|
||||
|
||||
export async function acceptSponsorshipRequest(
|
||||
command: AcceptSponsorshipRequestCommand,
|
||||
): Promise<void> {
|
||||
const mutation = new AcceptSponsorshipRequestMutation();
|
||||
const result = await mutation.execute(command);
|
||||
|
||||
if (result.isErr()) {
|
||||
throw new Error('Failed to accept sponsorship request');
|
||||
}
|
||||
}
|
||||
|
||||
export async function rejectSponsorshipRequest(
|
||||
command: RejectSponsorshipRequestCommand,
|
||||
): Promise<void> {
|
||||
const mutation = new RejectSponsorshipRequestMutation();
|
||||
const result = await mutation.execute(command);
|
||||
|
||||
if (result.isErr()) {
|
||||
throw new Error('Failed to reject sponsorship request');
|
||||
}
|
||||
}
|
||||
@@ -1,48 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
import { SponsorshipRequestsTemplate } from '@/templates/SponsorshipRequestsTemplate';
|
||||
import {
|
||||
useSponsorshipRequestsPageData,
|
||||
useSponsorshipRequestMutations
|
||||
} from "@/lib/hooks/sponsor/useSponsorshipRequestsPageData";
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
|
||||
export default function SponsorshipRequestsPage() {
|
||||
const currentDriverId = useEffectiveDriverId();
|
||||
|
||||
// Fetch data using domain hook
|
||||
const { data: sections, isLoading, error, refetch } = useSponsorshipRequestsPageData(currentDriverId);
|
||||
|
||||
// Mutations using domain hook
|
||||
const { acceptMutation, rejectMutation } = useSponsorshipRequestMutations(currentDriverId, refetch);
|
||||
|
||||
// Template needs to handle mutations
|
||||
const TemplateWithMutations = ({ data }: { data: any[] }) => (
|
||||
<SponsorshipRequestsTemplate
|
||||
data={data}
|
||||
onAccept={async (requestId) => {
|
||||
await acceptMutation.mutateAsync({ requestId });
|
||||
}}
|
||||
onReject={async (requestId, reason) => {
|
||||
await rejectMutation.mutateAsync({ requestId, reason });
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<StatefulPageWrapper
|
||||
data={sections}
|
||||
isLoading={isLoading}
|
||||
error={error as Error | null}
|
||||
retry={refetch}
|
||||
Template={TemplateWithMutations}
|
||||
loading={{ variant: 'skeleton', message: 'Loading sponsorship requests...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
empty={{
|
||||
title: 'No Pending Requests',
|
||||
description: 'You don\'t have any pending sponsorship requests at the moment.',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
export default async function SponsorshipRequestsPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Record<string, string>;
|
||||
}) {
|
||||
return <SponsorshipRequestsTemplate searchParams={searchParams} />;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { RaceDetailTemplate } from '@/templates/RaceDetailTemplate';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { RACE_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import type { RaceService } from '@/lib/services/races/RaceService';
|
||||
import type { RaceDetailViewModel } from '@/lib/view-models/RaceDetailViewModel';
|
||||
import { RacesApiClient } from '@/lib/api/races/RacesApiClient';
|
||||
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
|
||||
interface RaceDetailPageProps {
|
||||
params: {
|
||||
@@ -19,13 +19,20 @@ export default async function RaceDetailPage({ params }: RaceDetailPageProps) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
// Fetch initial race data
|
||||
const data = await PageDataFetcher.fetch<RaceService, 'getRaceDetail'>(
|
||||
RACE_SERVICE_TOKEN,
|
||||
'getRaceDetail',
|
||||
raceId,
|
||||
'' // currentDriverId - will be handled client-side for auth
|
||||
);
|
||||
// Manual wiring: create dependencies
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: true,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
|
||||
// Create API client
|
||||
const apiClient = new RacesApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Fetch initial race data (empty driverId for now, handled client-side)
|
||||
const data = await apiClient.getDetail(raceId, '');
|
||||
|
||||
if (!data) notFound();
|
||||
|
||||
@@ -66,7 +73,7 @@ export default async function RaceDetailPage({ params }: RaceDetailPageProps) {
|
||||
isPodium: data.userResult.isPodium,
|
||||
ratingChange: data.userResult.ratingChange,
|
||||
} : undefined,
|
||||
canReopenRace: data.canReopenRace,
|
||||
canReopenRace: false, // Not provided by API, default to false
|
||||
} : undefined;
|
||||
|
||||
return (
|
||||
|
||||
@@ -4,15 +4,30 @@ import { useState, useEffect } from 'react';
|
||||
import { useParams, useRouter } from 'next/navigation';
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { RaceStewardingTemplate, StewardingTab } from '@/templates/RaceStewardingTemplate';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { RACE_STEWARDING_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import { RaceStewardingService } from '@/lib/services/races/RaceStewardingService';
|
||||
import type { RaceStewardingViewModel } from '@/lib/view-models/RaceStewardingViewModel';
|
||||
import { RacesApiClient } from '@/lib/api/races/RacesApiClient';
|
||||
import { ProtestsApiClient } from '@/lib/api/protests/ProtestsApiClient';
|
||||
import { PenaltiesApiClient } from '@/lib/api/penalties/PenaltiesApiClient';
|
||||
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
import { useLeagueMemberships } from "@/lib/hooks/league/useLeagueMemberships";
|
||||
import { useEffectiveDriverId } from "@/lib/hooks/useEffectiveDriverId";
|
||||
import { LeagueRoleUtility } from '@/lib/utilities/LeagueRoleUtility';
|
||||
import { Gavel } from 'lucide-react';
|
||||
import type { LeagueMembershipsDTO } from '@/lib/types/generated/LeagueMembershipsDTO';
|
||||
|
||||
// Define the view model structure locally to avoid type issues
|
||||
interface RaceStewardingViewModel {
|
||||
race: any;
|
||||
league: any;
|
||||
protests: any[];
|
||||
penalties: any[];
|
||||
driverMap: Record<string, any>;
|
||||
pendingProtests: any[];
|
||||
resolvedProtests: any[];
|
||||
pendingCount: number;
|
||||
resolvedCount: number;
|
||||
penaltiesCount: number;
|
||||
}
|
||||
|
||||
export default function RaceStewardingPage() {
|
||||
const router = useRouter();
|
||||
@@ -37,12 +52,61 @@ export default function RaceStewardingPage() {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const data = await PageDataFetcher.fetch<RaceStewardingService, 'getRaceStewardingData'>(
|
||||
RACE_STEWARDING_SERVICE_TOKEN,
|
||||
'getRaceStewardingData',
|
||||
raceId,
|
||||
currentDriverId
|
||||
// Manual wiring: create dependencies
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: true,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
|
||||
// Create API clients
|
||||
const racesApiClient = new RacesApiClient(baseUrl, errorReporter, logger);
|
||||
const protestsApiClient = new ProtestsApiClient(baseUrl, errorReporter, logger);
|
||||
const penaltiesApiClient = new PenaltiesApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Fetch data in parallel
|
||||
const [raceDetail, protests, penalties] = await Promise.all([
|
||||
racesApiClient.getDetail(raceId, currentDriverId),
|
||||
protestsApiClient.getRaceProtests(raceId),
|
||||
penaltiesApiClient.getRacePenalties(raceId),
|
||||
]);
|
||||
|
||||
// Transform data to match view model structure
|
||||
const data: RaceStewardingViewModel = {
|
||||
race: raceDetail.race,
|
||||
league: raceDetail.league,
|
||||
protests: protests.protests.map(p => ({
|
||||
id: p.id,
|
||||
protestingDriverId: p.protestingDriverId,
|
||||
accusedDriverId: p.accusedDriverId,
|
||||
incident: {
|
||||
lap: p.lap,
|
||||
description: p.description,
|
||||
},
|
||||
filedAt: p.filedAt,
|
||||
status: p.status,
|
||||
})),
|
||||
penalties: penalties.penalties,
|
||||
driverMap: { ...protests.driverMap, ...penalties.driverMap },
|
||||
pendingProtests: [],
|
||||
resolvedProtests: [],
|
||||
pendingCount: 0,
|
||||
resolvedCount: 0,
|
||||
penaltiesCount: 0,
|
||||
};
|
||||
|
||||
// Calculate derived properties
|
||||
data.pendingProtests = data.protests.filter(p => p.status === 'pending' || p.status === 'under_review');
|
||||
data.resolvedProtests = data.protests.filter(p =>
|
||||
p.status === 'upheld' ||
|
||||
p.status === 'dismissed' ||
|
||||
p.status === 'withdrawn'
|
||||
);
|
||||
data.pendingCount = data.pendingProtests.length;
|
||||
data.resolvedCount = data.resolvedProtests.length;
|
||||
data.penaltiesCount = data.penalties.length;
|
||||
|
||||
if (data) {
|
||||
setPageData(data);
|
||||
@@ -93,12 +157,61 @@ export default function RaceStewardingPage() {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const data = await PageDataFetcher.fetch<RaceStewardingService, 'getRaceStewardingData'>(
|
||||
RACE_STEWARDING_SERVICE_TOKEN,
|
||||
'getRaceStewardingData',
|
||||
raceId,
|
||||
currentDriverId
|
||||
// Manual wiring: create dependencies
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: true,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
|
||||
// Create API clients
|
||||
const racesApiClient = new RacesApiClient(baseUrl, errorReporter, logger);
|
||||
const protestsApiClient = new ProtestsApiClient(baseUrl, errorReporter, logger);
|
||||
const penaltiesApiClient = new PenaltiesApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Fetch data in parallel
|
||||
const [raceDetail, protests, penalties] = await Promise.all([
|
||||
racesApiClient.getDetail(raceId, currentDriverId),
|
||||
protestsApiClient.getRaceProtests(raceId),
|
||||
penaltiesApiClient.getRacePenalties(raceId),
|
||||
]);
|
||||
|
||||
// Transform data to match view model structure
|
||||
const data: RaceStewardingViewModel = {
|
||||
race: raceDetail.race,
|
||||
league: raceDetail.league,
|
||||
protests: protests.protests.map(p => ({
|
||||
id: p.id,
|
||||
protestingDriverId: p.protestingDriverId,
|
||||
accusedDriverId: p.accusedDriverId,
|
||||
incident: {
|
||||
lap: p.lap,
|
||||
description: p.description,
|
||||
},
|
||||
filedAt: p.filedAt,
|
||||
status: p.status,
|
||||
})),
|
||||
penalties: penalties.penalties,
|
||||
driverMap: { ...protests.driverMap, ...penalties.driverMap },
|
||||
pendingProtests: [],
|
||||
resolvedProtests: [],
|
||||
pendingCount: 0,
|
||||
resolvedCount: 0,
|
||||
penaltiesCount: 0,
|
||||
};
|
||||
|
||||
// Calculate derived properties
|
||||
data.pendingProtests = data.protests.filter(p => p.status === 'pending' || p.status === 'under_review');
|
||||
data.resolvedProtests = data.protests.filter(p =>
|
||||
p.status === 'upheld' ||
|
||||
p.status === 'dismissed' ||
|
||||
p.status === 'withdrawn'
|
||||
);
|
||||
data.pendingCount = data.pendingProtests.length;
|
||||
data.resolvedCount = data.resolvedProtests.length;
|
||||
data.penaltiesCount = data.penalties.length;
|
||||
|
||||
if (data) {
|
||||
setPageData(data);
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { RacesTemplate } from '@/templates/RacesTemplate';
|
||||
import { RaceService } from '@/lib/services/races/RaceService';
|
||||
import { RacesApiClient } from '@/lib/api/races/RacesApiClient';
|
||||
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
|
||||
export default async function Page() {
|
||||
// Create dependencies for API clients
|
||||
// Manual wiring: create dependencies
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
@@ -18,12 +17,10 @@ export default async function Page() {
|
||||
// Create API client
|
||||
const racesApiClient = new RacesApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Create service
|
||||
const service = new RaceService(racesApiClient);
|
||||
// Fetch data
|
||||
const data = await racesApiClient.getPageData();
|
||||
|
||||
const data = await service.getRacesPageData();
|
||||
|
||||
// Transform data for template
|
||||
// Transform races
|
||||
const transformRace = (race: any) => ({
|
||||
id: race.id,
|
||||
track: race.track,
|
||||
@@ -34,16 +31,16 @@ export default async function Page() {
|
||||
leagueId: race.leagueId,
|
||||
leagueName: race.leagueName,
|
||||
strengthOfField: race.strengthOfField ?? undefined,
|
||||
isUpcoming: race.isUpcoming,
|
||||
isLive: race.isLive,
|
||||
isPast: race.isPast,
|
||||
isUpcoming: race.status === 'scheduled',
|
||||
isLive: race.status === 'running',
|
||||
isPast: race.status === 'completed',
|
||||
});
|
||||
|
||||
const races = data.races.map(transformRace);
|
||||
const scheduledRaces = data.scheduledRaces.map(transformRace);
|
||||
const runningRaces = data.runningRaces.map(transformRace);
|
||||
const completedRaces = data.completedRaces.map(transformRace);
|
||||
const totalCount = data.totalCount;
|
||||
const scheduledRaces = races.filter(r => r.isUpcoming);
|
||||
const runningRaces = races.filter(r => r.isLive);
|
||||
const completedRaces = races.filter(r => r.isPast);
|
||||
const totalCount = races.length;
|
||||
|
||||
return <RacesTemplate
|
||||
races={races}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { headers } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { createRouteGuard } from '@/lib/auth/createRouteGuard';
|
||||
|
||||
interface SponsorLayoutProps {
|
||||
@@ -16,11 +17,14 @@ export default async function SponsorLayout({ children }: SponsorLayoutProps) {
|
||||
const pathname = headerStore.get('x-pathname') || '/';
|
||||
|
||||
const guard = createRouteGuard();
|
||||
await guard.enforce({ pathname });
|
||||
const result = await guard.enforce({ pathname });
|
||||
if (result.type === 'redirect') {
|
||||
redirect(result.to);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,26 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { SponsorLeagueDetailTemplate } from '@/templates/SponsorLeagueDetailTemplate';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { SPONSOR_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import type { SponsorService } from '@/lib/services/sponsors/SponsorService';
|
||||
import { SponsorsApiClient } from '@/lib/api/sponsors/SponsorsApiClient';
|
||||
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
|
||||
export default async function Page({ params }: { params: { id: string } }) {
|
||||
const data = await PageDataFetcher.fetch<SponsorService, 'getLeagueDetail'>(
|
||||
SPONSOR_SERVICE_TOKEN,
|
||||
'getLeagueDetail',
|
||||
params.id
|
||||
);
|
||||
// Manual wiring: create dependencies
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: true,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
|
||||
// Create API client
|
||||
const apiClient = new SponsorsApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Fetch data
|
||||
const data = await apiClient.getLeagueDetail(params.id);
|
||||
|
||||
if (!data) notFound();
|
||||
|
||||
|
||||
@@ -1,15 +1,26 @@
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { SponsorLeaguesTemplate } from '@/templates/SponsorLeaguesTemplate';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { SPONSOR_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import { SponsorService } from '@/lib/services/sponsors/SponsorService';
|
||||
import { SponsorsApiClient } from '@/lib/api/sponsors/SponsorsApiClient';
|
||||
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
import { AvailableLeaguesViewModel } from '@/lib/view-models/AvailableLeaguesViewModel';
|
||||
|
||||
export default async function Page() {
|
||||
const leaguesData = await PageDataFetcher.fetch<SponsorService, 'getAvailableLeagues'>(
|
||||
SPONSOR_SERVICE_TOKEN,
|
||||
'getAvailableLeagues'
|
||||
);
|
||||
// Manual wiring: create dependencies
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: true,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
|
||||
// Create API client
|
||||
const apiClient = new SponsorsApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Fetch data
|
||||
const leaguesData = await apiClient.getAvailableLeagues();
|
||||
|
||||
// Process data with view model to calculate stats
|
||||
if (!leaguesData) {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import type { TeamsPageDto } from '@/lib/page-queries/page-queries/TeamsPageQuery';
|
||||
import { TeamsPresenter } from '@/lib/presenters/TeamsPresenter';
|
||||
import type { TeamSummaryData } from '@/lib/view-data/TeamsViewData';
|
||||
import { TeamsTemplate } from '@/templates/TeamsTemplate';
|
||||
import type { TeamSummaryData } from '@/templates/view-data/TeamsViewData';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useMemo, useState } from 'react';
|
||||
|
||||
interface TeamsPageClientProps {
|
||||
pageDto: TeamsPageDto;
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import type { TeamDetailPageDto } from '@/lib/page-queries/page-queries/TeamDetailPageQuery';
|
||||
import { TeamDetailPresenter } from '@/lib/presenters/TeamDetailPresenter';
|
||||
import TeamDetailTemplate from '@/templates/TeamDetailTemplate';
|
||||
import { TeamDetailPresenter } from '@/lib/view-models/TeamDetailPresenter';
|
||||
import { TeamDetailTemplate } from '@/templates/TeamDetailTemplate';
|
||||
|
||||
type Tab = 'overview' | 'roster' | 'standings' | 'admin';
|
||||
|
||||
@@ -53,11 +53,9 @@ export function TeamDetailPageClient({ pageDto }: TeamDetailPageClientProps) {
|
||||
|
||||
return (
|
||||
<TeamDetailTemplate
|
||||
team={viewData.team}
|
||||
memberships={viewData.memberships}
|
||||
viewData={viewData}
|
||||
activeTab={activeTab}
|
||||
loading={loading}
|
||||
isAdmin={viewData.isAdmin}
|
||||
onTabChange={handleTabChange}
|
||||
onUpdate={handleUpdate}
|
||||
onRemoveMember={handleRemoveMember}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { TeamDetailPageQuery } from '@/lib/page-queries/TeamDetailPageQuery';
|
||||
import TeamDetailPageClient from './TeamDetailPageClient';
|
||||
import { TeamDetailPageQuery } from '@/lib/page-queries/page-queries/TeamDetailPageQuery';
|
||||
import { TeamDetailPageClient } from './TeamDetailPageClient';
|
||||
|
||||
export default async function Page({ params }: { params: { id: string } }) {
|
||||
const result = await TeamDetailPageQuery.execute(params.id);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { PageWrapper } from '@/components/shared/state/PageWrapper';
|
||||
import { PageDataFetcher } from '@/lib/page/PageDataFetcher';
|
||||
import { TEAM_SERVICE_TOKEN } from '@/lib/di/tokens';
|
||||
import { TeamService } from '@/lib/services/teams/TeamService';
|
||||
import { TeamsApiClient } from '@/lib/api/teams/TeamsApiClient';
|
||||
import { EnhancedErrorReporter } from '@/lib/infrastructure/EnhancedErrorReporter';
|
||||
import { ConsoleLogger } from '@/lib/infrastructure/logging/ConsoleLogger';
|
||||
import { getWebsiteApiBaseUrl } from '@/lib/config/apiBaseUrl';
|
||||
import { Trophy } from 'lucide-react';
|
||||
import { redirect } from 'next/navigation';
|
||||
import type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';
|
||||
import { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';
|
||||
import { TeamLeaderboardPageWrapper } from './TeamLeaderboardPageWrapper';
|
||||
|
||||
// ============================================================================
|
||||
@@ -12,11 +13,23 @@ import { TeamLeaderboardPageWrapper } from './TeamLeaderboardPageWrapper';
|
||||
// ============================================================================
|
||||
|
||||
export default async function TeamLeaderboardPage() {
|
||||
// Fetch data using PageDataFetcher
|
||||
const teamsData = await PageDataFetcher.fetch<TeamService, 'getAllTeams'>(
|
||||
TEAM_SERVICE_TOKEN,
|
||||
'getAllTeams'
|
||||
);
|
||||
// Manual wiring: create dependencies
|
||||
const baseUrl = getWebsiteApiBaseUrl();
|
||||
const logger = new ConsoleLogger();
|
||||
const errorReporter = new EnhancedErrorReporter(logger, {
|
||||
showUserNotifications: true,
|
||||
logToConsole: true,
|
||||
reportToExternal: process.env.NODE_ENV === 'production',
|
||||
});
|
||||
|
||||
// Create API client
|
||||
const apiClient = new TeamsApiClient(baseUrl, errorReporter, logger);
|
||||
|
||||
// Fetch data
|
||||
const result = await apiClient.getAll();
|
||||
|
||||
// Transform DTO to ViewModel
|
||||
const teamsData: TeamSummaryViewModel[] = result.teams.map(team => new TeamSummaryViewModel(team));
|
||||
|
||||
// Prepare data for template
|
||||
const data: TeamSummaryViewModel[] | null = teamsData;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { notFound } from 'next/navigation';
|
||||
import { TeamsPageQuery } from '@/lib/page-queries/TeamsPageQuery';
|
||||
import TeamsPageClient from './TeamsPageClient';
|
||||
import { TeamsPageQuery } from '@/lib/page-queries/page-queries/TeamsPageQuery';
|
||||
import { TeamsPageClient } from './TeamsPageClient';
|
||||
|
||||
export default async function Page() {
|
||||
const result = await TeamsPageQuery.execute();
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Search, Filter, Hash, Star, Trophy, Medal, Percent } from 'lucide-react';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
|
||||
type SkillLevel = 'pro' | 'advanced' | 'intermediate' | 'beginner';
|
||||
type SortBy = 'rank' | 'rating' | 'wins' | 'podiums' | 'winRate';
|
||||
|
||||
const SKILL_LEVELS: {
|
||||
id: SkillLevel;
|
||||
label: string;
|
||||
color: string;
|
||||
bgColor: string;
|
||||
borderColor: string;
|
||||
}[] = [
|
||||
{ id: 'pro', label: 'Pro', color: 'text-yellow-400', bgColor: 'bg-yellow-400/10', borderColor: 'border-yellow-400/30' },
|
||||
{ id: 'advanced', label: 'Advanced', color: 'text-purple-400', bgColor: 'bg-purple-400/10', borderColor: 'border-purple-400/30' },
|
||||
{ id: 'intermediate', label: 'Intermediate', color: 'text-primary-blue', bgColor: 'bg-primary-blue/10', borderColor: 'border-primary-blue/30' },
|
||||
{ id: 'beginner', label: 'Beginner', color: 'text-green-400', bgColor: 'bg-green-400/10', borderColor: 'border-green-400/30' },
|
||||
];
|
||||
|
||||
const SORT_OPTIONS: { id: SortBy; label: string; icon: React.ElementType }[] = [
|
||||
{ id: 'rank', label: 'Rank', icon: Hash },
|
||||
{ id: 'rating', label: 'Rating', icon: Star },
|
||||
{ id: 'wins', label: 'Wins', icon: Trophy },
|
||||
{ id: 'podiums', label: 'Podiums', icon: Medal },
|
||||
{ id: 'winRate', label: 'Win Rate', icon: Percent },
|
||||
];
|
||||
|
||||
interface DriverRankingsFilterProps {
|
||||
searchQuery: string;
|
||||
onSearchChange: (query: string) => void;
|
||||
selectedSkill: 'all' | SkillLevel;
|
||||
onSkillChange: (skill: 'all' | SkillLevel) => void;
|
||||
sortBy: SortBy;
|
||||
onSortChange: (sort: SortBy) => void;
|
||||
showFilters: boolean;
|
||||
onToggleFilters: () => void;
|
||||
}
|
||||
|
||||
export default function DriverRankingsFilter({
|
||||
searchQuery,
|
||||
onSearchChange,
|
||||
selectedSkill,
|
||||
onSkillChange,
|
||||
sortBy,
|
||||
onSortChange,
|
||||
showFilters,
|
||||
onToggleFilters,
|
||||
}: DriverRankingsFilterProps) {
|
||||
return (
|
||||
<div className="mb-6 space-y-4">
|
||||
<div className="flex flex-col lg:flex-row gap-4">
|
||||
<div className="flex-1 relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-500" />
|
||||
<Input
|
||||
type="text"
|
||||
placeholder="Search drivers by name or nationality..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => onSearchChange(e.target.value)}
|
||||
className="pl-11"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={onToggleFilters}
|
||||
className="lg:hidden flex items-center gap-2"
|
||||
>
|
||||
<Filter className="w-4 h-4" />
|
||||
Filters
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className={`flex flex-wrap gap-2 ${showFilters ? 'block' : 'hidden lg:flex'}`}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSkillChange('all')}
|
||||
className={`px-3 py-2 rounded-lg text-sm font-medium transition-all ${
|
||||
selectedSkill === 'all'
|
||||
? 'bg-primary-blue text-white'
|
||||
: 'bg-iron-gray/50 text-gray-400 border border-charcoal-outline hover:text-white'
|
||||
}`}
|
||||
>
|
||||
All Levels
|
||||
</button>
|
||||
{SKILL_LEVELS.map((level) => {
|
||||
return (
|
||||
<button
|
||||
key={level.id}
|
||||
type="button"
|
||||
onClick={() => onSkillChange(level.id)}
|
||||
className={`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-all ${
|
||||
selectedSkill === level.id
|
||||
? `${level.bgColor} ${level.color} border ${level.borderColor}`
|
||||
: 'bg-iron-gray/50 text-gray-400 border border-charcoal-outline hover:text-white'
|
||||
}`}
|
||||
>
|
||||
{level.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-gray-500">Sort by:</span>
|
||||
<div className="flex items-center gap-1 p-1 rounded-lg bg-iron-gray/50 border border-charcoal-outline">
|
||||
{SORT_OPTIONS.map((option) => {
|
||||
const OptionIcon = option.icon;
|
||||
return (
|
||||
<button
|
||||
key={option.id}
|
||||
type="button"
|
||||
onClick={() => onSortChange(option.id)}
|
||||
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-all ${
|
||||
sortBy === option.id
|
||||
? 'bg-primary-blue text-white'
|
||||
: 'text-gray-400 hover:text-white hover:bg-iron-gray'
|
||||
}`}
|
||||
>
|
||||
<OptionIcon className="w-3.5 h-3.5" />
|
||||
{option.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Trophy, Medal, Crown } from 'lucide-react';
|
||||
import Image from 'next/image';
|
||||
import type { DriverLeaderboardItemViewModel } from '@/lib/view-models/DriverLeaderboardItemViewModel';
|
||||
|
||||
interface DriverTopThreePodiumProps {
|
||||
drivers: DriverLeaderboardItemViewModel[];
|
||||
onDriverClick: (id: string) => void;
|
||||
}
|
||||
|
||||
export default function DriverTopThreePodium({ drivers, onDriverClick }: DriverTopThreePodiumProps) {
|
||||
if (drivers.length < 3) return null;
|
||||
|
||||
const top3 = drivers.slice(0, 3) as [DriverLeaderboardItemViewModel, DriverLeaderboardItemViewModel, DriverLeaderboardItemViewModel];
|
||||
|
||||
const podiumOrder: [DriverLeaderboardItemViewModel, DriverLeaderboardItemViewModel, DriverLeaderboardItemViewModel] = [
|
||||
top3[1],
|
||||
top3[0],
|
||||
top3[2],
|
||||
]; // 2nd, 1st, 3rd
|
||||
const podiumHeights = ['h-32', 'h-40', 'h-24'];
|
||||
const podiumColors = [
|
||||
'from-gray-400/20 to-gray-500/10 border-gray-400/40',
|
||||
'from-yellow-400/20 to-amber-500/10 border-yellow-400/40',
|
||||
'from-amber-600/20 to-amber-700/10 border-amber-600/40',
|
||||
];
|
||||
const crownColors = ['text-gray-300', 'text-yellow-400', 'text-amber-600'];
|
||||
const positions = [2, 1, 3];
|
||||
|
||||
return (
|
||||
<div className="mb-10">
|
||||
<div className="flex items-end justify-center gap-4 lg:gap-8">
|
||||
{podiumOrder.map((driver, index) => {
|
||||
const position = positions[index];
|
||||
|
||||
return (
|
||||
<button
|
||||
key={driver.id}
|
||||
type="button"
|
||||
onClick={() => onDriverClick(driver.id)}
|
||||
className="flex flex-col items-center group"
|
||||
>
|
||||
{/* Driver Avatar & Info */}
|
||||
<div className="relative mb-4">
|
||||
{/* Crown for 1st place */}
|
||||
{position === 1 && (
|
||||
<div className="absolute -top-6 left-1/2 -translate-x-1/2 animate-bounce">
|
||||
<Crown className="w-8 h-8 text-yellow-400 drop-shadow-[0_0_10px_rgba(250,204,21,0.5)]" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Avatar */}
|
||||
<div className={`relative ${position === 1 ? 'w-24 h-24 lg:w-28 lg:h-28' : 'w-20 h-20 lg:w-24 lg:h-24'} rounded-full overflow-hidden border-4 ${position === 1 ? 'border-yellow-400 shadow-[0_0_30px_rgba(250,204,21,0.3)]' : position === 2 ? 'border-gray-300' : 'border-amber-600'} group-hover:scale-105 transition-transform`}>
|
||||
<Image
|
||||
src={driver.avatarUrl}
|
||||
alt={driver.name}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Position badge */}
|
||||
<div className={`absolute -bottom-2 left-1/2 -translate-x-1/2 w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold bg-gradient-to-br ${podiumColors[index]} border-2 ${crownColors[index]}`}>
|
||||
{position}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Driver Name */}
|
||||
<p className={`text-white font-semibold ${position === 1 ? 'text-lg' : 'text-base'} group-hover:text-primary-blue transition-colors mb-1`}>
|
||||
{driver.name}
|
||||
</p>
|
||||
|
||||
{/* Rating */}
|
||||
<p className={`font-mono font-bold ${position === 1 ? 'text-xl text-yellow-400' : 'text-lg text-primary-blue'}`}>
|
||||
{driver.rating.toLocaleString()}
|
||||
</p>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="flex items-center gap-2 text-xs text-gray-500 mt-1">
|
||||
<span className="flex items-center gap-1">
|
||||
<Trophy className="w-3 h-3 text-performance-green" />
|
||||
{driver.wins}
|
||||
</span>
|
||||
<span>•</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Medal className="w-3 h-3 text-warning-amber" />
|
||||
{driver.podiums}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Podium Stand */}
|
||||
<div className={`mt-4 w-28 lg:w-36 ${podiumHeights[index]} rounded-t-lg bg-gradient-to-t ${podiumColors[index]} border-t border-x flex items-end justify-center pb-4`}>
|
||||
<span className={`text-4xl lg:text-5xl font-black ${crownColors[index]}`}>
|
||||
{position}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { apiClient } from '@/lib/apiClient';
|
||||
import Card from '@/components/ui/Card';
|
||||
import { AdminViewModelPresenter } from '@/lib/view-models/AdminViewModelPresenter';
|
||||
import { DashboardStatsViewModel } from '@/lib/view-models/AdminUserViewModel';
|
||||
import {
|
||||
Users,
|
||||
Shield,
|
||||
Activity,
|
||||
Clock,
|
||||
AlertTriangle,
|
||||
RefreshCw
|
||||
} from 'lucide-react';
|
||||
|
||||
export function AdminDashboardPage() {
|
||||
const [stats, setStats] = useState<DashboardStatsViewModel | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadStats();
|
||||
}, []);
|
||||
|
||||
const loadStats = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await apiClient.admin.getDashboardStats();
|
||||
|
||||
// Map DTO to View Model
|
||||
const viewModel = AdminViewModelPresenter.mapDashboardStats(response);
|
||||
setStats(viewModel);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to load stats';
|
||||
if (message.includes('403') || message.includes('401')) {
|
||||
setError('Access denied - You must be logged in as an Owner or Admin');
|
||||
} else {
|
||||
setError(message);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-20 space-y-3">
|
||||
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-blue"></div>
|
||||
<div className="text-gray-400">Loading dashboard...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="container mx-auto p-6">
|
||||
<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>
|
||||
</div>
|
||||
<button
|
||||
onClick={loadStats}
|
||||
className="px-3 py-1 text-xs bg-racing-red/20 hover:bg-racing-red/30 rounded"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!stats) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Temporary UI fields (not yet provided by API/ViewModel)
|
||||
const adminCount = stats.systemAdmins;
|
||||
const recentActivity: Array<{ description: string; timestamp: string; type: string }> = [];
|
||||
const systemHealth = 'Healthy';
|
||||
const totalSessions = 0;
|
||||
const activeSessions = 0;
|
||||
const avgSessionDuration = '—';
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-white">Admin Dashboard</h1>
|
||||
<p className="text-gray-400 mt-1">System overview and statistics</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={loadStats}
|
||||
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"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Stats Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<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-3xl font-bold text-white">{stats.totalUsers}</div>
|
||||
</div>
|
||||
<Users className="w-8 h-8 text-blue-400" />
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<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-3xl font-bold text-white">{adminCount}</div>
|
||||
</div>
|
||||
<Shield className="w-8 h-8 text-purple-400" />
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<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 Users</div>
|
||||
<div className="text-3xl font-bold text-white">{stats.activeUsers}</div>
|
||||
</div>
|
||||
<Activity className="w-8 h-8 text-green-400" />
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card className="bg-gradient-to-br from-orange-900/20 to-orange-700/10">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm text-gray-400 mb-1">Recent Logins</div>
|
||||
<div className="text-3xl font-bold text-white">{stats.recentLogins}</div>
|
||||
</div>
|
||||
<Clock className="w-8 h-8 text-orange-400" />
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Activity Overview */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Recent Activity */}
|
||||
<Card>
|
||||
<h3 className="text-lg font-semibold text-white mb-4">Recent Activity</h3>
|
||||
<div className="space-y-3">
|
||||
{recentActivity.length > 0 ? (
|
||||
recentActivity.map((activity, index: number) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex items-center justify-between p-3 bg-iron-gray/30 rounded-lg border border-charcoal-outline/50"
|
||||
>
|
||||
<div className="flex-1">
|
||||
<div className="text-sm text-white">{activity.description}</div>
|
||||
<div className="text-xs text-gray-500">{activity.timestamp}</div>
|
||||
</div>
|
||||
<span className={`px-2 py-1 text-xs rounded-full ${
|
||||
activity.type === 'user_created' ? 'bg-blue-500/20 text-blue-300' :
|
||||
activity.type === 'user_suspended' ? 'bg-yellow-500/20 text-yellow-300' :
|
||||
activity.type === 'user_deleted' ? 'bg-red-500/20 text-red-300' :
|
||||
'bg-gray-500/20 text-gray-300'
|
||||
}`}>
|
||||
{activity.type.replace('_', ' ')}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="text-center py-8 text-gray-500">No recent activity</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* System Status */}
|
||||
<Card>
|
||||
<h3 className="text-lg font-semibold text-white mb-4">System Status</h3>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-gray-400">System Health</span>
|
||||
<span className="px-2 py-1 text-xs rounded-full bg-performance-green/20 text-performance-green">
|
||||
{systemHealth}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-gray-400">Total Sessions</span>
|
||||
<span className="text-white font-medium">{totalSessions}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-gray-400">Active Sessions</span>
|
||||
<span className="text-white font-medium">{activeSessions}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-gray-400">Avg Session Duration</span>
|
||||
<span className="text-white font-medium">{avgSessionDuration}</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Quick Actions */}
|
||||
<Card>
|
||||
<h3 className="text-lg font-semibold text-white mb-4">Quick Actions</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
<button className="px-4 py-3 bg-primary-blue/20 border border-primary-blue/30 text-primary-blue rounded-lg hover:bg-primary-blue/30 transition-colors text-sm font-medium">
|
||||
View All Users
|
||||
</button>
|
||||
<button className="px-4 py-3 bg-purple-500/20 border border-purple-500/30 text-purple-300 rounded-lg hover:bg-purple-500/30 transition-colors text-sm font-medium">
|
||||
Manage Admins
|
||||
</button>
|
||||
<button className="px-4 py-3 bg-orange-500/20 border border-orange-500/30 text-orange-300 rounded-lg hover:bg-orange-500/30 transition-colors text-sm font-medium">
|
||||
View Audit Log
|
||||
</button>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { ReactNode, useState } from 'react';
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Users,
|
||||
Settings,
|
||||
LogOut,
|
||||
Shield,
|
||||
Activity
|
||||
} from 'lucide-react';
|
||||
import { useRouter, usePathname } from 'next/navigation';
|
||||
import { logoutAction } from '@/app/actions/logoutAction';
|
||||
|
||||
interface AdminLayoutProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
type AdminTab = 'dashboard' | 'users';
|
||||
|
||||
export function AdminLayout({ children }: AdminLayoutProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(true);
|
||||
|
||||
// Determine current tab from pathname
|
||||
const getCurrentTab = (): AdminTab => {
|
||||
if (pathname === '/admin') return 'dashboard';
|
||||
if (pathname === '/admin/users') return 'users';
|
||||
return 'dashboard';
|
||||
};
|
||||
|
||||
const currentTab = getCurrentTab();
|
||||
|
||||
const navigation = [
|
||||
{
|
||||
id: 'dashboard',
|
||||
label: 'Dashboard',
|
||||
icon: LayoutDashboard,
|
||||
href: '/admin',
|
||||
description: 'Overview and statistics'
|
||||
},
|
||||
{
|
||||
id: 'users',
|
||||
label: 'User Management',
|
||||
icon: Users,
|
||||
href: '/admin/users',
|
||||
description: 'Manage all users'
|
||||
},
|
||||
{
|
||||
id: 'settings',
|
||||
label: 'Settings',
|
||||
icon: Settings,
|
||||
href: '/admin/settings',
|
||||
description: 'System configuration',
|
||||
disabled: true
|
||||
}
|
||||
];
|
||||
|
||||
const handleNavigation = (href: string, disabled?: boolean) => {
|
||||
if (!disabled) {
|
||||
router.push(href);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-screen bg-deep-graphite overflow-hidden">
|
||||
{/* Sidebar */}
|
||||
<aside className={`${isSidebarOpen ? 'w-64' : 'w-20'} bg-iron-gray border-r border-charcoal-outline transition-all duration-300 flex flex-col`}>
|
||||
{/* Logo/Header */}
|
||||
<div className="p-4 border-b border-charcoal-outline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-6 h-6 text-primary-blue" />
|
||||
{isSidebarOpen && (
|
||||
<span className="font-bold text-white text-lg">Admin Panel</span>
|
||||
)}
|
||||
</div>
|
||||
{isSidebarOpen && (
|
||||
<p className="text-xs text-gray-400 mt-1">System Administration</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="flex-1 p-2 space-y-1 overflow-y-auto">
|
||||
{navigation.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = currentTab === item.id;
|
||||
const isDisabled = item.disabled;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
onClick={() => handleNavigation(item.href, isDisabled)}
|
||||
disabled={isDisabled}
|
||||
className={`
|
||||
w-full flex items-center gap-3 px-3 py-3 rounded-lg
|
||||
transition-all duration-200 text-left
|
||||
${isActive
|
||||
? 'bg-primary-blue/20 text-primary-blue border border-primary-blue/30'
|
||||
: 'text-gray-300 hover:bg-iron-gray/50 hover:text-white'
|
||||
}
|
||||
${isDisabled ? 'opacity-50 cursor-not-allowed' : ''}
|
||||
`}
|
||||
>
|
||||
<Icon className={`w-5 h-5 flex-shrink-0 ${isActive ? 'text-primary-blue' : 'text-gray-400'}`} />
|
||||
{isSidebarOpen && (
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm">{item.label}</div>
|
||||
<div className="text-xs text-gray-500">{item.description}</div>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="p-2 border-t border-charcoal-outline space-y-1">
|
||||
<button
|
||||
onClick={() => setIsSidebarOpen(!isSidebarOpen)}
|
||||
className="w-full flex items-center gap-3 px-3 py-2 rounded-lg text-gray-300 hover:bg-iron-gray/50 hover:text-white transition-colors"
|
||||
>
|
||||
<Activity className="w-5 h-5" />
|
||||
{isSidebarOpen && <span className="text-sm">Toggle Sidebar</span>}
|
||||
</button>
|
||||
|
||||
{/* Use form with server action for logout */}
|
||||
<form action={logoutAction}>
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full flex items-center gap-3 px-3 py-2 rounded-lg text-racing-red hover:bg-racing-red/10 transition-colors"
|
||||
>
|
||||
<LogOut className="w-5 h-5" />
|
||||
{isSidebarOpen && <span className="text-sm">Logout</span>}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="flex-1 flex flex-col overflow-hidden">
|
||||
{/* Top Bar */}
|
||||
<header className="bg-iron-gray border-b border-charcoal-outline px-6 py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="p-2 bg-primary-blue/20 rounded-lg">
|
||||
<Shield className="w-5 h-5 text-primary-blue" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-white">
|
||||
{navigation.find(n => n.id === currentTab)?.label || 'Admin'}
|
||||
</h2>
|
||||
<p className="text-xs text-gray-400">
|
||||
{navigation.find(n => n.id === currentTab)?.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex items-center gap-2 px-3 py-1.5 bg-deep-graphite rounded-lg border border-charcoal-outline">
|
||||
<Shield className="w-4 h-4 text-purple-500" />
|
||||
<span className="text-xs font-medium text-purple-400">Super Admin</span>
|
||||
</div>
|
||||
|
||||
<div className="text-right hidden sm:block">
|
||||
<div className="text-sm font-medium text-white">System Administrator</div>
|
||||
<div className="text-xs text-gray-400">Full Access</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Content Area */}
|
||||
<div className="flex-1 overflow-y-auto bg-deep-graphite">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { apiClient } from '@/lib/apiClient';
|
||||
import Card from '@/components/ui/Card';
|
||||
import StatusBadge from '@/components/ui/StatusBadge';
|
||||
import { AdminViewModelPresenter } from '@/lib/view-models/AdminViewModelPresenter';
|
||||
import { AdminUserViewModel, UserListViewModel } from '@/lib/view-models/AdminUserViewModel';
|
||||
import {
|
||||
Search,
|
||||
Filter,
|
||||
RefreshCw,
|
||||
Users,
|
||||
Shield,
|
||||
Trash2,
|
||||
AlertTriangle
|
||||
} from 'lucide-react';
|
||||
|
||||
export function AdminUsersPage() {
|
||||
const [userList, setUserList] = useState<UserListViewModel | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [search, setSearch] = useState('');
|
||||
const [roleFilter, setRoleFilter] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState('');
|
||||
const [deletingUser, setDeletingUser] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => {
|
||||
loadUsers();
|
||||
}, 300);
|
||||
|
||||
return () => clearTimeout(timeout);
|
||||
}, [search, roleFilter, statusFilter]);
|
||||
|
||||
const loadUsers = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await apiClient.admin.listUsers({
|
||||
search: search || undefined,
|
||||
role: roleFilter || undefined,
|
||||
status: statusFilter || undefined,
|
||||
page: 1,
|
||||
limit: 50,
|
||||
});
|
||||
|
||||
// Map DTO to View Model
|
||||
const viewModel = AdminViewModelPresenter.mapUserList(response);
|
||||
setUserList(viewModel);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to load users';
|
||||
if (message.includes('403') || message.includes('401')) {
|
||||
setError('Access denied - You must be logged in as an Owner or Admin');
|
||||
} else {
|
||||
setError(message);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateStatus = async (userId: string, newStatus: string) => {
|
||||
try {
|
||||
await apiClient.admin.updateUserStatus(userId, newStatus);
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update status');
|
||||
}
|
||||
};
|
||||
|
||||
const toStatusBadgeProps = (
|
||||
status: string,
|
||||
): { status: 'success' | 'warning' | 'error' | 'neutral'; label: string } => {
|
||||
switch (status) {
|
||||
case 'active':
|
||||
return { status: 'success', label: 'Active' };
|
||||
case 'suspended':
|
||||
return { status: 'warning', label: 'Suspended' };
|
||||
case 'deleted':
|
||||
return { status: 'error', label: 'Deleted' };
|
||||
default:
|
||||
return { status: 'neutral', label: status };
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteUser = async (userId: string) => {
|
||||
if (!confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setDeletingUser(userId);
|
||||
await apiClient.admin.deleteUser(userId);
|
||||
await loadUsers();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to delete user');
|
||||
} finally {
|
||||
setDeletingUser(null);
|
||||
}
|
||||
};
|
||||
|
||||
const clearFilters = () => {
|
||||
setSearch('');
|
||||
setRoleFilter('');
|
||||
setStatusFilter('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-6 space-y-6">
|
||||
{/* 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>
|
||||
</div>
|
||||
<button
|
||||
onClick={loadUsers}
|
||||
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"
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Error Banner */}
|
||||
{error && (
|
||||
<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>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setError(null)}
|
||||
className="text-racing-red hover:opacity-70"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Filters Card */}
|
||||
<Card>
|
||||
<div className="space-y-4">
|
||||
<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>
|
||||
</div>
|
||||
{(search || roleFilter || statusFilter) && (
|
||||
<button
|
||||
onClick={clearFilters}
|
||||
className="text-xs text-primary-blue hover:text-blue-400"
|
||||
>
|
||||
Clear all
|
||||
</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) => setSearch(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) => setRoleFilter(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) => setStatusFilter(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>
|
||||
</Card>
|
||||
|
||||
{/* Users Table */}
|
||||
<Card>
|
||||
{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>
|
||||
</div>
|
||||
) : !userList || !userList.hasUsers ? (
|
||||
<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
|
||||
onClick={clearFilters}
|
||||
className="text-primary-blue hover:text-blue-400 text-sm"
|
||||
>
|
||||
Clear filters
|
||||
</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>
|
||||
{userList.users.map((user: AdminUserViewModel, 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>
|
||||
</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.roleBadges.map((badge: string, idx: number) => (
|
||||
<span
|
||||
key={idx}
|
||||
className={`px-2 py-1 text-xs rounded-full font-medium ${
|
||||
user.roles[idx] === 'owner'
|
||||
? 'bg-purple-500/20 text-purple-300 border border-purple-500/30'
|
||||
: user.roles[idx] === 'admin'
|
||||
? 'bg-blue-500/20 text-blue-300 border border-blue-500/30'
|
||||
: 'bg-gray-500/20 text-gray-300 border border-gray-500/30'
|
||||
}`}
|
||||
>
|
||||
{badge}
|
||||
</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.lastLoginFormatted}
|
||||
</div>
|
||||
</td>
|
||||
<td className="py-3 px-4">
|
||||
<div className="flex items-center gap-2">
|
||||
{user.canSuspend && (
|
||||
<button
|
||||
onClick={() => handleUpdateStatus(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.canActivate && (
|
||||
<button
|
||||
onClick={() => handleUpdateStatus(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.canDelete && (
|
||||
<button
|
||||
onClick={() => handleDeleteUser(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>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Stats Summary */}
|
||||
{userList && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<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">{userList.total}</div>
|
||||
</div>
|
||||
<Users className="w-6 h-6 text-blue-400" />
|
||||
</div>
|
||||
</Card>
|
||||
<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">
|
||||
{userList.users.filter(u => u.status === 'active').length}
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-6 h-6 text-green-400">✓</div>
|
||||
</div>
|
||||
</Card>
|
||||
<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">
|
||||
{userList.users.filter(u => u.isSystemAdmin).length}
|
||||
</div>
|
||||
</div>
|
||||
<Shield className="w-6 h-6 text-purple-400" />
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { Activity, Trophy, Medal, UserPlus, Heart, Flag, Play } from 'lucide-react';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Link from 'next/link';
|
||||
import { timeAgo } from '@/lib/utilities/time';
|
||||
|
||||
interface FeedItemData {
|
||||
id: string;
|
||||
type: string;
|
||||
headline: string;
|
||||
body?: string;
|
||||
timestamp: string;
|
||||
formattedTime: string;
|
||||
ctaHref?: string;
|
||||
ctaLabel?: string;
|
||||
}
|
||||
|
||||
function FeedItemRow({ item }: { item: FeedItemData }) {
|
||||
const getActivityIcon = (type: string) => {
|
||||
if (type.includes('win')) return { icon: Trophy, color: 'text-yellow-400 bg-yellow-400/10' };
|
||||
if (type.includes('podium')) return { icon: Medal, color: 'text-warning-amber bg-warning-amber/10' };
|
||||
if (type.includes('join')) return { icon: UserPlus, color: 'text-performance-green bg-performance-green/10' };
|
||||
if (type.includes('friend')) return { icon: Heart, color: 'text-pink-400 bg-pink-400/10' };
|
||||
if (type.includes('league')) return { icon: Flag, color: 'text-primary-blue bg-primary-blue/10' };
|
||||
if (type.includes('race')) return { icon: Play, color: 'text-red-400 bg-red-400/10' };
|
||||
return { icon: Activity, color: 'text-gray-400 bg-gray-400/10' };
|
||||
};
|
||||
|
||||
const { icon: Icon, color } = getActivityIcon(item.type);
|
||||
|
||||
return (
|
||||
<div className="flex gap-3 p-3 rounded-lg bg-deep-graphite/50 border border-charcoal-outline">
|
||||
<div className={`flex h-10 w-10 items-center justify-center rounded-lg ${color} flex-shrink-0`}>
|
||||
<Icon className="w-5 h-5" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm text-white">{item.headline}</p>
|
||||
{item.body && (
|
||||
<p className="text-xs text-gray-500 mt-1 line-clamp-2">{item.body}</p>
|
||||
)}
|
||||
<p className="text-xs text-gray-500 mt-1">{timeAgo(item.timestamp)}</p>
|
||||
</div>
|
||||
{item.ctaHref && (
|
||||
<Link href={item.ctaHref} className="flex-shrink-0">
|
||||
<Button variant="secondary" className="text-xs px-3 py-1.5">
|
||||
{item.ctaLabel || 'View'}
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export { FeedItemRow };
|
||||
@@ -1,33 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import Image from 'next/image';
|
||||
import { getCountryFlag } from '@/lib/utilities/country';
|
||||
|
||||
interface FriendItemProps {
|
||||
id: string;
|
||||
name: string;
|
||||
avatarUrl: string;
|
||||
country: string;
|
||||
}
|
||||
|
||||
export function FriendItem({ id, name, avatarUrl, country }: FriendItemProps) {
|
||||
return (
|
||||
<Link
|
||||
href={`/drivers/${id}`}
|
||||
className="flex items-center gap-3 p-2 rounded-lg hover:bg-deep-graphite transition-colors"
|
||||
>
|
||||
<div className="w-9 h-9 rounded-full overflow-hidden bg-gradient-to-br from-primary-blue to-purple-600">
|
||||
<Image
|
||||
src={avatarUrl}
|
||||
alt={name}
|
||||
width={36}
|
||||
height={36}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-white text-sm font-medium truncate">{name}</p>
|
||||
<p className="text-xs text-gray-500">{getCountryFlag(country)}</p>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import { Crown, ChevronRight } from 'lucide-react';
|
||||
|
||||
interface LeagueStandingItemProps {
|
||||
leagueId: string;
|
||||
leagueName: string;
|
||||
position: number;
|
||||
points: number;
|
||||
totalDrivers: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function LeagueStandingItem({
|
||||
leagueId,
|
||||
leagueName,
|
||||
position,
|
||||
points,
|
||||
totalDrivers,
|
||||
className,
|
||||
}: LeagueStandingItemProps) {
|
||||
return (
|
||||
<Link
|
||||
href={`/leagues/${leagueId}/standings`}
|
||||
className={`flex items-center gap-4 p-4 rounded-xl bg-deep-graphite border border-charcoal-outline hover:border-primary-blue/30 transition-colors group ${className || ''}`}
|
||||
>
|
||||
<div className={`flex h-12 w-12 items-center justify-center rounded-xl font-bold text-xl ${
|
||||
position === 1 ? 'bg-yellow-400/20 text-yellow-400' :
|
||||
position === 2 ? 'bg-gray-300/20 text-gray-300' :
|
||||
position === 3 ? 'bg-orange-400/20 text-orange-400' :
|
||||
'bg-iron-gray text-gray-400'
|
||||
}`}>
|
||||
{position > 0 ? `P${position}` : '-'}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-white font-semibold truncate group-hover:text-primary-blue transition-colors">
|
||||
{leagueName}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
{points} points • {totalDrivers} drivers
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{position <= 3 && position > 0 && (
|
||||
<Crown className={`w-5 h-5 ${
|
||||
position === 1 ? 'text-yellow-400' :
|
||||
position === 2 ? 'text-gray-300' :
|
||||
'text-orange-400'
|
||||
}`} />
|
||||
)}
|
||||
<ChevronRight className="w-5 h-5 text-gray-500 group-hover:text-primary-blue transition-colors" />
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { LucideIcon } from 'lucide-react';
|
||||
|
||||
interface StatCardProps {
|
||||
icon: LucideIcon;
|
||||
value: string | number;
|
||||
label: string;
|
||||
color: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function StatCard({ icon: Icon, value, label, color, className }: StatCardProps) {
|
||||
return (
|
||||
<div className={`p-4 rounded-xl bg-iron-gray/50 border border-charcoal-outline backdrop-blur-sm ${className || ''}`}>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`flex h-10 w-10 items-center justify-center rounded-lg ${color}`}>
|
||||
<Icon className="w-5 h-5" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-2xl font-bold text-white">{value}</p>
|
||||
<p className="text-xs text-gray-500">{label}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import { timeUntil } from '@/lib/utilities/time';
|
||||
|
||||
interface UpcomingRaceItemProps {
|
||||
id: string;
|
||||
track: string;
|
||||
car: string;
|
||||
scheduledAt: Date;
|
||||
isMyLeague: boolean;
|
||||
}
|
||||
|
||||
export function UpcomingRaceItem({
|
||||
id,
|
||||
track,
|
||||
car,
|
||||
scheduledAt,
|
||||
isMyLeague,
|
||||
}: UpcomingRaceItemProps) {
|
||||
return (
|
||||
<Link
|
||||
href={`/races/${id}`}
|
||||
className="block p-3 rounded-lg bg-deep-graphite border border-charcoal-outline hover:border-primary-blue/30 transition-colors"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2 mb-2">
|
||||
<p className="text-white font-medium text-sm truncate">{track}</p>
|
||||
{isMyLeague && (
|
||||
<span className="flex-shrink-0 w-2 h-2 rounded-full bg-performance-green" title="Your league" />
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 truncate mb-2">{car}</p>
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className="text-gray-400">
|
||||
{scheduledAt.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
|
||||
</span>
|
||||
<span className="text-primary-blue font-medium">{timeUntil(scheduledAt)}</span>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import Card from '@/components/ui/Card';
|
||||
import RankBadge from '@/components/drivers/RankBadge';
|
||||
import DriverIdentity from '@/components/drivers/DriverIdentity';
|
||||
import { DriverIdentity } from '@/components/drivers/DriverIdentity';
|
||||
import { DriverViewModel } from '@/lib/view-models/DriverViewModel';
|
||||
|
||||
export interface DriverCardProps {
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
import Link from 'next/link';
|
||||
import Image from 'next/image';
|
||||
import PlaceholderImage from '@/components/ui/PlaceholderImage';
|
||||
import type { DriverViewModel } from '@/lib/view-models/DriverViewModel';
|
||||
|
||||
export interface DriverIdentityProps {
|
||||
driver: DriverViewModel;
|
||||
driver: {
|
||||
id: string;
|
||||
name: string;
|
||||
avatarUrl: string | null;
|
||||
};
|
||||
href?: string;
|
||||
contextLabel?: React.ReactNode;
|
||||
meta?: React.ReactNode;
|
||||
size?: 'sm' | 'md';
|
||||
}
|
||||
|
||||
export default function DriverIdentity(props: DriverIdentityProps) {
|
||||
export function DriverIdentity(props: DriverIdentityProps) {
|
||||
const { driver, href, contextLabel, meta, size = 'md' } = props;
|
||||
|
||||
const avatarSize = size === 'sm' ? 40 : 48;
|
||||
|
||||
@@ -3,10 +3,19 @@ import { useRouter } from 'next/navigation';
|
||||
import { Trophy, Crown, Flag, ChevronRight } from 'lucide-react';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Image from 'next/image';
|
||||
import type { DriverLeaderboardItemViewModel } from '@/lib/view-models/DriverLeaderboardItemViewModel';
|
||||
|
||||
interface DriverLeaderboardPreviewProps {
|
||||
drivers: DriverLeaderboardItemViewModel[];
|
||||
drivers: {
|
||||
id: string;
|
||||
name: string;
|
||||
rating: number;
|
||||
skillLevel: string;
|
||||
nationality: string;
|
||||
wins: number;
|
||||
rank: number;
|
||||
avatarUrl: string;
|
||||
position: number;
|
||||
}[];
|
||||
onDriverClick: (id: string) => void;
|
||||
}
|
||||
|
||||
|
||||
@@ -3,11 +3,19 @@ import { useRouter } from 'next/navigation';
|
||||
import Image from 'next/image';
|
||||
import { Users, Crown, Shield, ChevronRight } from 'lucide-react';
|
||||
import Button from '@/components/ui/Button';
|
||||
import type { TeamSummaryViewModel } from '@/lib/view-models/TeamSummaryViewModel';
|
||||
import { getMediaUrl } from '@/lib/utilities/media';
|
||||
|
||||
interface TeamLeaderboardPreviewProps {
|
||||
teams: TeamSummaryViewModel[];
|
||||
teams: {
|
||||
id: string;
|
||||
name: string;
|
||||
tag: string;
|
||||
memberCount: number;
|
||||
category?: string;
|
||||
totalWins: number;
|
||||
logoUrl: string;
|
||||
position: number;
|
||||
}[];
|
||||
onTeamClick: (id: string) => void;
|
||||
}
|
||||
|
||||
@@ -68,7 +76,7 @@ export default function TeamLeaderboardPreview({ teams, onTeamClick }: TeamLeade
|
||||
{/* Leaderboard Rows */}
|
||||
<div className="divide-y divide-charcoal-outline/50">
|
||||
{top5.map((team, index) => {
|
||||
const levelConfig = SKILL_LEVELS.find((l) => l.id === team.performanceLevel);
|
||||
const levelConfig = SKILL_LEVELS.find((l) => l.id === team.category);
|
||||
const LevelIcon = levelConfig?.icon || Shield;
|
||||
const position = index + 1;
|
||||
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
import React from 'react';
|
||||
import Card from '@/components/ui/Card';
|
||||
import { StandingEntryViewModel } from '@/lib/view-models/StandingEntryViewModel';
|
||||
import { DriverViewModel } from '@/lib/view-models/DriverViewModel';
|
||||
|
||||
interface LeagueChampionshipStatsProps {
|
||||
standings: StandingEntryViewModel[];
|
||||
drivers: DriverViewModel[];
|
||||
standings: Array<{
|
||||
driverId: string;
|
||||
position: number;
|
||||
totalPoints: number;
|
||||
racesFinished: number;
|
||||
}>;
|
||||
drivers: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
export default function LeagueChampionshipStats({ standings, drivers }: LeagueChampionshipStatsProps) {
|
||||
export function LeagueChampionshipStats({ standings, drivers }: LeagueChampionshipStatsProps) {
|
||||
if (standings.length === 0) return null;
|
||||
|
||||
const leader = standings[0];
|
||||
const totalRaces = Math.max(...standings.map(s => s.races), 0);
|
||||
const totalRaces = Math.max(...standings.map(s => s.racesFinished), 0);
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
@@ -24,7 +30,7 @@ export default function LeagueChampionshipStats({ standings, drivers }: LeagueCh
|
||||
<div>
|
||||
<p className="text-xs text-gray-400 mb-1">Championship Leader</p>
|
||||
<p className="font-bold text-white">{drivers.find(d => d.id === leader?.driverId)?.name || 'N/A'}</p>
|
||||
<p className="text-sm text-yellow-400 font-medium">{leader?.points || 0} points</p>
|
||||
<p className="text-sm text-yellow-400 font-medium">{leader?.totalPoints || 0} points</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
@@ -3,14 +3,29 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import Link from 'next/link';
|
||||
import Image from 'next/image';
|
||||
import { Star } from 'lucide-react';
|
||||
import type { DriverViewModel } from '@/lib/view-models/DriverViewModel';
|
||||
import type { LeagueMembership } from '@/lib/types/LeagueMembership';
|
||||
import { LeagueRoleDisplay } from '@/lib/display-objects/LeagueRoleDisplay';
|
||||
import CountryFlag from '@/components/ui/CountryFlag';
|
||||
import { getMediaUrl } from '@/lib/utilities/media';
|
||||
import PlaceholderImage from '@/components/ui/PlaceholderImage';
|
||||
|
||||
// League role display data
|
||||
const leagueRoleDisplay = {
|
||||
owner: {
|
||||
text: 'Owner',
|
||||
badgeClasses: 'bg-yellow-500/10 text-yellow-500 border-yellow-500/30',
|
||||
},
|
||||
admin: {
|
||||
text: 'Admin',
|
||||
badgeClasses: 'bg-purple-500/10 text-purple-400 border-purple-500/30',
|
||||
},
|
||||
steward: {
|
||||
text: 'Steward',
|
||||
badgeClasses: 'bg-blue-500/10 text-blue-400 border-blue-500/30',
|
||||
},
|
||||
member: {
|
||||
text: 'Member',
|
||||
badgeClasses: 'bg-primary-blue/10 text-primary-blue border-primary-blue/30',
|
||||
},
|
||||
} as const;
|
||||
|
||||
// Position background colors
|
||||
const getPositionBgColor = (position: number): string => {
|
||||
switch (position) {
|
||||
@@ -23,7 +38,6 @@ const getPositionBgColor = (position: number): string => {
|
||||
|
||||
interface StandingsTableProps {
|
||||
standings: Array<{
|
||||
leagueId: string;
|
||||
driverId: string;
|
||||
position: number;
|
||||
totalPoints: number;
|
||||
@@ -34,19 +48,29 @@ interface StandingsTableProps {
|
||||
bonusPoints: number;
|
||||
teamName?: string;
|
||||
}>;
|
||||
drivers: DriverViewModel[];
|
||||
leagueId: string;
|
||||
memberships?: LeagueMembership[];
|
||||
drivers: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
avatarUrl: string | null;
|
||||
iracingId?: string;
|
||||
rating?: number;
|
||||
country?: string;
|
||||
}>;
|
||||
memberships?: Array<{
|
||||
driverId: string;
|
||||
role: 'owner' | 'admin' | 'steward' | 'member';
|
||||
joinedAt: string;
|
||||
status: 'active' | 'pending' | 'banned';
|
||||
}>;
|
||||
currentDriverId?: string;
|
||||
isAdmin?: boolean;
|
||||
onRemoveMember?: (driverId: string) => void;
|
||||
onUpdateRole?: (driverId: string, role: string) => void;
|
||||
}
|
||||
|
||||
export default function StandingsTable({
|
||||
export function StandingsTable({
|
||||
standings,
|
||||
drivers,
|
||||
leagueId,
|
||||
memberships = [],
|
||||
currentDriverId,
|
||||
isAdmin = false,
|
||||
@@ -68,11 +92,11 @@ export default function StandingsTable({
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, []);
|
||||
|
||||
const getDriver = (driverId: string): DriverViewModel | undefined => {
|
||||
const getDriver = (driverId: string) => {
|
||||
return drivers.find((d) => d.id === driverId);
|
||||
};
|
||||
|
||||
const getMembership = (driverId: string): LeagueMembership | undefined => {
|
||||
const getMembership = (driverId: string) => {
|
||||
return memberships.find((m) => m.driverId === driverId);
|
||||
};
|
||||
|
||||
@@ -216,7 +240,7 @@ export default function StandingsTable({
|
||||
);
|
||||
};
|
||||
|
||||
const PointsActionMenu = ({ driverId }: { driverId: string }) => {
|
||||
const PointsActionMenu = () => {
|
||||
return (
|
||||
<div
|
||||
ref={menuRef}
|
||||
@@ -280,10 +304,8 @@ export default function StandingsTable({
|
||||
{standings.map((row) => {
|
||||
const driver = getDriver(row.driverId);
|
||||
const membership = getMembership(row.driverId);
|
||||
const roleDisplay = membership ? LeagueRoleDisplay.getLeagueRoleDisplay(membership.role) : null;
|
||||
const roleDisplay = membership ? leagueRoleDisplay[membership.role] : null;
|
||||
const canModify = canModifyMember(row.driverId);
|
||||
// TODO: Hook up real driver stats once API provides it
|
||||
const driverStatsData: null = null;
|
||||
const isRowHovered = hoveredRow === row.driverId;
|
||||
const isMemberMenuOpen = activeMenu?.driverId === row.driverId && activeMenu?.type === 'member';
|
||||
const isPointsMenuOpen = activeMenu?.driverId === row.driverId && activeMenu?.type === 'points';
|
||||
@@ -292,7 +314,7 @@ export default function StandingsTable({
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={`${row.leagueId}-${row.driverId}`}
|
||||
key={row.driverId}
|
||||
className={`border-b border-charcoal-outline/50 transition-all duration-200 ${getPositionBgColor(row.position)} ${isRowHovered ? 'bg-iron-gray/10' : ''} ${isMe ? 'ring-2 ring-primary-blue/50 ring-inset bg-primary-blue/5' : ''}`}
|
||||
onMouseEnter={() => setHoveredRow(row.driverId)}
|
||||
onMouseLeave={() => {
|
||||
@@ -407,7 +429,7 @@ export default function StandingsTable({
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{isPointsMenuOpen && <PointsActionMenu driverId={row.driverId} />}
|
||||
{isPointsMenuOpen && <PointsActionMenu />}
|
||||
</td>
|
||||
|
||||
{/* Races (Finished/Started) */}
|
||||
|
||||
279
apps/website/components/onboarding/AvatarStep.tsx
Normal file
279
apps/website/components/onboarding/AvatarStep.tsx
Normal file
@@ -0,0 +1,279 @@
|
||||
import { useRef, ChangeEvent } from 'react';
|
||||
import { Camera, Upload, Loader2, Sparkles, Palette, Check, User } from 'lucide-react';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
|
||||
export type RacingSuitColor =
|
||||
| 'red'
|
||||
| 'blue'
|
||||
| 'green'
|
||||
| 'yellow'
|
||||
| 'orange'
|
||||
| 'purple'
|
||||
| 'black'
|
||||
| 'white'
|
||||
| 'pink'
|
||||
| 'cyan';
|
||||
|
||||
export interface AvatarInfo {
|
||||
facePhoto: string | null;
|
||||
suitColor: RacingSuitColor;
|
||||
generatedAvatars: string[];
|
||||
selectedAvatarIndex: number | null;
|
||||
isGenerating: boolean;
|
||||
isValidating: boolean;
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
[key: string]: string | undefined;
|
||||
}
|
||||
|
||||
interface AvatarStepProps {
|
||||
avatarInfo: AvatarInfo;
|
||||
setAvatarInfo: (info: AvatarInfo) => void;
|
||||
errors: FormErrors;
|
||||
setErrors: (errors: FormErrors) => void;
|
||||
onGenerateAvatars: () => void;
|
||||
}
|
||||
|
||||
const SUIT_COLORS: { value: RacingSuitColor; label: string; hex: string }[] = [
|
||||
{ value: 'red', label: 'Racing Red', hex: '#EF4444' },
|
||||
{ value: 'blue', label: 'Motorsport Blue', hex: '#3B82F6' },
|
||||
{ value: 'green', label: 'Racing Green', hex: '#22C55E' },
|
||||
{ value: 'yellow', label: 'Championship Yellow', hex: '#EAB308' },
|
||||
{ value: 'orange', label: 'Papaya Orange', hex: '#F97316' },
|
||||
{ value: 'purple', label: 'Royal Purple', hex: '#A855F7' },
|
||||
{ value: 'black', label: 'Stealth Black', hex: '#1F2937' },
|
||||
{ value: 'white', label: 'Clean White', hex: '#F9FAFB' },
|
||||
{ value: 'pink', label: 'Hot Pink', hex: '#EC4899' },
|
||||
{ value: 'cyan', label: 'Electric Cyan', hex: '#06B6D4' },
|
||||
];
|
||||
|
||||
export function AvatarStep({ avatarInfo, setAvatarInfo, errors, setErrors, onGenerateAvatars }: AvatarStepProps) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleFileSelect = async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
// Validate file type
|
||||
if (!file.type.startsWith('image/')) {
|
||||
setErrors({ ...errors, facePhoto: 'Please upload an image file' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate file size (max 5MB)
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
setErrors({ ...errors, facePhoto: 'Image must be less than 5MB' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert to base64
|
||||
const reader = new FileReader();
|
||||
reader.onload = async (event) => {
|
||||
const base64 = event.target?.result as string;
|
||||
setAvatarInfo({
|
||||
...avatarInfo,
|
||||
facePhoto: base64,
|
||||
generatedAvatars: [],
|
||||
selectedAvatarIndex: null,
|
||||
});
|
||||
const newErrors = { ...errors };
|
||||
delete newErrors.facePhoto;
|
||||
setErrors(newErrors);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<Heading level={2} className="text-xl mb-1 flex items-center gap-2">
|
||||
<Camera className="w-5 h-5 text-primary-blue" />
|
||||
Create Your Racing Avatar
|
||||
</Heading>
|
||||
<p className="text-sm text-gray-400">
|
||||
Upload a photo and we will generate a unique racing avatar for you
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Photo Upload */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-3">
|
||||
Upload Your Photo *
|
||||
</label>
|
||||
<div className="flex gap-6">
|
||||
{/* Upload Area */}
|
||||
<div
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className={`relative flex-1 flex flex-col items-center justify-center p-6 rounded-xl border-2 border-dashed cursor-pointer transition-all ${
|
||||
avatarInfo.facePhoto
|
||||
? 'border-performance-green bg-performance-green/5'
|
||||
: errors.facePhoto
|
||||
? 'border-red-500 bg-red-500/5'
|
||||
: 'border-charcoal-outline hover:border-primary-blue hover:bg-primary-blue/5'
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleFileSelect}
|
||||
className="hidden"
|
||||
/>
|
||||
|
||||
{avatarInfo.isValidating ? (
|
||||
<>
|
||||
<Loader2 className="w-10 h-10 text-primary-blue animate-spin mb-3" />
|
||||
<p className="text-sm text-gray-400">Validating photo...</p>
|
||||
</>
|
||||
) : avatarInfo.facePhoto ? (
|
||||
<>
|
||||
<div className="w-24 h-24 rounded-xl overflow-hidden mb-3 ring-2 ring-performance-green">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={avatarInfo.facePhoto}
|
||||
alt="Your photo"
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-sm text-performance-green flex items-center gap-1">
|
||||
<Check className="w-4 h-4" />
|
||||
Photo uploaded
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">Click to change</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="w-10 h-10 text-gray-500 mb-3" />
|
||||
<p className="text-sm text-gray-300 font-medium mb-1">
|
||||
Drop your photo here or click to upload
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
JPEG or PNG, max 5MB
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Preview area */}
|
||||
<div className="w-32 flex flex-col items-center justify-center">
|
||||
<div className="w-24 h-24 rounded-xl bg-iron-gray border border-charcoal-outline flex items-center justify-center overflow-hidden">
|
||||
{(() => {
|
||||
const selectedAvatarUrl =
|
||||
avatarInfo.selectedAvatarIndex !== null
|
||||
? avatarInfo.generatedAvatars[avatarInfo.selectedAvatarIndex]
|
||||
: undefined;
|
||||
if (!selectedAvatarUrl) {
|
||||
return <User className="w-8 h-8 text-gray-600" />;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={selectedAvatarUrl} alt="Selected avatar" className="w-full h-full object-cover" />
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-2 text-center">Your avatar</p>
|
||||
</div>
|
||||
</div>
|
||||
{errors.facePhoto && (
|
||||
<p className="mt-2 text-sm text-red-400">{errors.facePhoto}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Suit Color Selection */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-3 flex items-center gap-2">
|
||||
<Palette className="w-4 h-4" />
|
||||
Racing Suit Color
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{SUIT_COLORS.map((color) => (
|
||||
<button
|
||||
key={color.value}
|
||||
type="button"
|
||||
onClick={() => setAvatarInfo({ ...avatarInfo, suitColor: color.value })}
|
||||
className={`relative w-10 h-10 rounded-lg transition-all ${
|
||||
avatarInfo.suitColor === color.value
|
||||
? 'ring-2 ring-primary-blue ring-offset-2 ring-offset-iron-gray scale-110'
|
||||
: 'hover:scale-105'
|
||||
}`}
|
||||
style={{ backgroundColor: color.hex }}
|
||||
title={color.label}
|
||||
>
|
||||
{avatarInfo.suitColor === color.value && (
|
||||
<Check className={`absolute inset-0 m-auto w-5 h-5 ${
|
||||
['white', 'yellow', 'cyan'].includes(color.value) ? 'text-gray-800' : 'text-white'
|
||||
}`} />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-gray-500">
|
||||
Selected: {SUIT_COLORS.find(c => c.value === avatarInfo.suitColor)?.label}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Generate Button */}
|
||||
{avatarInfo.facePhoto && !errors.facePhoto && (
|
||||
<div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
onClick={onGenerateAvatars}
|
||||
disabled={avatarInfo.isGenerating || avatarInfo.isValidating}
|
||||
className="w-full flex items-center justify-center gap-2"
|
||||
>
|
||||
{avatarInfo.isGenerating ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
Generating your avatars...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles className="w-5 h-5" />
|
||||
{avatarInfo.generatedAvatars.length > 0 ? 'Regenerate Avatars' : 'Generate Racing Avatars'}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Generated Avatars */}
|
||||
{avatarInfo.generatedAvatars.length > 0 && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-3">
|
||||
Choose Your Avatar *
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{avatarInfo.generatedAvatars.map((url, index) => (
|
||||
<button
|
||||
key={index}
|
||||
type="button"
|
||||
onClick={() => setAvatarInfo({ ...avatarInfo, selectedAvatarIndex: index })}
|
||||
className={`relative aspect-square rounded-xl overflow-hidden border-2 transition-all ${
|
||||
avatarInfo.selectedAvatarIndex === index
|
||||
? 'border-primary-blue ring-2 ring-primary-blue/30 scale-105'
|
||||
: 'border-charcoal-outline hover:border-gray-500'
|
||||
}`}
|
||||
>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={url} alt={`Avatar option ${index + 1}`} className="w-full h-full object-cover" />
|
||||
{avatarInfo.selectedAvatarIndex === index && (
|
||||
<div className="absolute top-2 right-2 w-6 h-6 rounded-full bg-primary-blue flex items-center justify-center">
|
||||
<Check className="w-4 h-4 text-white" />
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{errors.avatar && (
|
||||
<p className="mt-2 text-sm text-red-400">{errors.avatar}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,56 +1,14 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useRef, FormEvent, ChangeEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import Image from 'next/image';
|
||||
import {
|
||||
User,
|
||||
Flag,
|
||||
Camera,
|
||||
Clock,
|
||||
Check,
|
||||
ChevronRight,
|
||||
ChevronLeft,
|
||||
AlertCircle,
|
||||
Upload,
|
||||
Loader2,
|
||||
Sparkles,
|
||||
Palette,
|
||||
} from 'lucide-react';
|
||||
import { useState, FormEvent } from 'react';
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import CountrySelect from '@/components/ui/CountrySelect';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useCompleteOnboarding } from "@/lib/hooks/onboarding/useCompleteOnboarding";
|
||||
import { useGenerateAvatars } from "@/lib/hooks/onboarding/useGenerateAvatars";
|
||||
import { useValidateFacePhoto } from "@/lib/hooks/onboarding/useValidateFacePhoto";
|
||||
|
||||
// ============================================================================
|
||||
// TYPES
|
||||
// ============================================================================
|
||||
import { StepIndicator } from '@/ui/StepIndicator';
|
||||
import { PersonalInfoStep, PersonalInfo } from './PersonalInfoStep';
|
||||
import { AvatarStep, AvatarInfo } from './AvatarStep';
|
||||
|
||||
type OnboardingStep = 1 | 2;
|
||||
|
||||
interface PersonalInfo {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
displayName: string;
|
||||
country: string;
|
||||
timezone: string;
|
||||
}
|
||||
|
||||
interface AvatarInfo {
|
||||
facePhoto: string | null;
|
||||
suitColor: RacingSuitColor;
|
||||
generatedAvatars: string[];
|
||||
selectedAvatarIndex: number | null;
|
||||
isGenerating: boolean;
|
||||
isValidating: boolean;
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
[key: string]: string | undefined;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
displayName?: string;
|
||||
@@ -60,113 +18,22 @@ interface FormErrors {
|
||||
submit?: string;
|
||||
}
|
||||
|
||||
type RacingSuitColor =
|
||||
| 'red'
|
||||
| 'blue'
|
||||
| 'green'
|
||||
| 'yellow'
|
||||
| 'orange'
|
||||
| 'purple'
|
||||
| 'black'
|
||||
| 'white'
|
||||
| 'pink'
|
||||
| 'cyan';
|
||||
|
||||
// ============================================================================
|
||||
// CONSTANTS
|
||||
// ============================================================================
|
||||
|
||||
const TIMEZONES = [
|
||||
{ value: 'America/New_York', label: 'Eastern Time (ET)' },
|
||||
{ value: 'America/Chicago', label: 'Central Time (CT)' },
|
||||
{ value: 'America/Denver', label: 'Mountain Time (MT)' },
|
||||
{ value: 'America/Los_Angeles', label: 'Pacific Time (PT)' },
|
||||
{ value: 'Europe/London', label: 'Greenwich Mean Time (GMT)' },
|
||||
{ value: 'Europe/Berlin', label: 'Central European Time (CET)' },
|
||||
{ value: 'Europe/Paris', label: 'Central European Time (CET)' },
|
||||
{ value: 'Australia/Sydney', label: 'Australian Eastern Time (AET)' },
|
||||
{ value: 'Asia/Tokyo', label: 'Japan Standard Time (JST)' },
|
||||
{ value: 'America/Sao_Paulo', label: 'Brasília Time (BRT)' },
|
||||
];
|
||||
|
||||
const SUIT_COLORS: { value: RacingSuitColor; label: string; hex: string }[] = [
|
||||
{ value: 'red', label: 'Racing Red', hex: '#EF4444' },
|
||||
{ value: 'blue', label: 'Motorsport Blue', hex: '#3B82F6' },
|
||||
{ value: 'green', label: 'Racing Green', hex: '#22C55E' },
|
||||
{ value: 'yellow', label: 'Championship Yellow', hex: '#EAB308' },
|
||||
{ value: 'orange', label: 'Papaya Orange', hex: '#F97316' },
|
||||
{ value: 'purple', label: 'Royal Purple', hex: '#A855F7' },
|
||||
{ value: 'black', label: 'Stealth Black', hex: '#1F2937' },
|
||||
{ value: 'white', label: 'Clean White', hex: '#F9FAFB' },
|
||||
{ value: 'pink', label: 'Hot Pink', hex: '#EC4899' },
|
||||
{ value: 'cyan', label: 'Electric Cyan', hex: '#06B6D4' },
|
||||
];
|
||||
|
||||
// ============================================================================
|
||||
// HELPER COMPONENTS
|
||||
// ============================================================================
|
||||
|
||||
function StepIndicator({ currentStep }: { currentStep: number }) {
|
||||
const steps = [
|
||||
{ id: 1, label: 'Personal', icon: User },
|
||||
{ id: 2, label: 'Avatar', icon: Camera },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center gap-2 mb-8">
|
||||
{steps.map((step, index) => {
|
||||
const Icon = step.icon;
|
||||
const isCompleted = step.id < currentStep;
|
||||
const isCurrent = step.id === currentStep;
|
||||
|
||||
return (
|
||||
<div key={step.id} className="flex items-center">
|
||||
<div className="flex flex-col items-center">
|
||||
<div
|
||||
className={`flex h-12 w-12 items-center justify-center rounded-full transition-all duration-300 ${
|
||||
isCurrent
|
||||
? 'bg-primary-blue text-white shadow-lg shadow-primary-blue/30'
|
||||
: isCompleted
|
||||
? 'bg-performance-green text-white'
|
||||
: 'bg-iron-gray border border-charcoal-outline text-gray-500'
|
||||
}`}
|
||||
>
|
||||
{isCompleted ? (
|
||||
<Check className="w-5 h-5" />
|
||||
) : (
|
||||
<Icon className="w-5 h-5" />
|
||||
)}
|
||||
</div>
|
||||
<span
|
||||
className={`mt-2 text-xs font-medium ${
|
||||
isCurrent ? 'text-white' : isCompleted ? 'text-performance-green' : 'text-gray-500'
|
||||
}`}
|
||||
>
|
||||
{step.label}
|
||||
</span>
|
||||
</div>
|
||||
{index < steps.length - 1 && (
|
||||
<div
|
||||
className={`w-16 h-0.5 mx-4 mt-[-20px] ${
|
||||
isCompleted ? 'bg-performance-green' : 'bg-charcoal-outline'
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
interface OnboardingWizardProps {
|
||||
onCompleted: () => void;
|
||||
onCompleteOnboarding: (data: {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
displayName: string;
|
||||
country: string;
|
||||
timezone?: string;
|
||||
}) => Promise<{ success: boolean; error?: string }>;
|
||||
onGenerateAvatars: (params: {
|
||||
facePhotoData: string;
|
||||
suitColor: string;
|
||||
}) => Promise<{ success: boolean; data?: { success: boolean; avatarUrls?: string[]; errorMessage?: string }; error?: string }>;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// MAIN COMPONENT
|
||||
// ============================================================================
|
||||
|
||||
export default function OnboardingWizard() {
|
||||
const router = useRouter();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { session } = useAuth();
|
||||
export function OnboardingWizard({ onCompleted, onCompleteOnboarding, onGenerateAvatars }: OnboardingWizardProps) {
|
||||
const [step, setStep] = useState<OnboardingStep>(1);
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
|
||||
@@ -235,139 +102,39 @@ export default function OnboardingWizard() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileSelect = async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
// Validate file type
|
||||
if (!file.type.startsWith('image/')) {
|
||||
setErrors({ ...errors, facePhoto: 'Please upload an image file' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate file size (max 5MB)
|
||||
if (file.size > 5 * 1024 * 1024) {
|
||||
setErrors({ ...errors, facePhoto: 'Image must be less than 5MB' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert to base64
|
||||
const reader = new FileReader();
|
||||
reader.onload = async (event) => {
|
||||
const base64 = event.target?.result as string;
|
||||
setAvatarInfo({
|
||||
...avatarInfo,
|
||||
facePhoto: base64,
|
||||
generatedAvatars: [],
|
||||
selectedAvatarIndex: null,
|
||||
});
|
||||
setErrors((prev) => {
|
||||
const { facePhoto, ...rest } = prev;
|
||||
return rest;
|
||||
});
|
||||
|
||||
// Validate face
|
||||
await validateFacePhoto(base64);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
const validateFacePhotoMutation = useValidateFacePhoto({
|
||||
onSuccess: () => {
|
||||
setAvatarInfo(prev => ({ ...prev, isValidating: false }));
|
||||
},
|
||||
onError: (error) => {
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
facePhoto: error.message || 'Face validation failed'
|
||||
}));
|
||||
setAvatarInfo(prev => ({ ...prev, facePhoto: null, isValidating: false }));
|
||||
},
|
||||
});
|
||||
|
||||
const validateFacePhoto = async (photoData: string) => {
|
||||
setAvatarInfo(prev => ({ ...prev, isValidating: true }));
|
||||
setErrors(prev => {
|
||||
const { facePhoto, ...rest } = prev;
|
||||
return rest;
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await validateFacePhotoMutation.mutateAsync(photoData);
|
||||
|
||||
if (!result.isValid) {
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
facePhoto: result.errorMessage || 'Face validation failed'
|
||||
}));
|
||||
setAvatarInfo(prev => ({ ...prev, facePhoto: null, isValidating: false }));
|
||||
}
|
||||
} catch (error) {
|
||||
// For now, just accept the photo if validation fails
|
||||
setAvatarInfo(prev => ({ ...prev, isValidating: false }));
|
||||
}
|
||||
};
|
||||
|
||||
const generateAvatarsMutation = useGenerateAvatars({
|
||||
onSuccess: (result) => {
|
||||
if (result.success && result.avatarUrls) {
|
||||
setAvatarInfo(prev => ({
|
||||
...prev,
|
||||
generatedAvatars: result.avatarUrls,
|
||||
isGenerating: false,
|
||||
}));
|
||||
} else {
|
||||
setErrors(prev => ({ ...prev, avatar: result.errorMessage || 'Failed to generate avatars' }));
|
||||
setAvatarInfo(prev => ({ ...prev, isGenerating: false }));
|
||||
}
|
||||
},
|
||||
onError: () => {
|
||||
setErrors(prev => ({ ...prev, avatar: 'Failed to generate avatars. Please try again.' }));
|
||||
setAvatarInfo(prev => ({ ...prev, isGenerating: false }));
|
||||
},
|
||||
});
|
||||
|
||||
const generateAvatars = async () => {
|
||||
if (!avatarInfo.facePhoto) {
|
||||
setErrors({ ...errors, facePhoto: 'Please upload a photo first' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!session?.user?.userId) {
|
||||
setErrors({ ...errors, submit: 'User not authenticated' });
|
||||
return;
|
||||
}
|
||||
|
||||
setAvatarInfo(prev => ({ ...prev, isGenerating: true, generatedAvatars: [], selectedAvatarIndex: null }));
|
||||
setErrors(prev => {
|
||||
const { avatar, ...rest } = prev;
|
||||
return rest;
|
||||
});
|
||||
const newErrors = { ...errors };
|
||||
delete newErrors.avatar;
|
||||
setErrors(newErrors);
|
||||
|
||||
try {
|
||||
await generateAvatarsMutation.mutateAsync({
|
||||
userId: session.user.userId,
|
||||
const result = await onGenerateAvatars({
|
||||
facePhotoData: avatarInfo.facePhoto,
|
||||
suitColor: avatarInfo.suitColor,
|
||||
});
|
||||
|
||||
if (result.success && result.data?.success && result.data.avatarUrls) {
|
||||
setAvatarInfo(prev => ({
|
||||
...prev,
|
||||
generatedAvatars: result.data!.avatarUrls!,
|
||||
isGenerating: false,
|
||||
}));
|
||||
} else {
|
||||
setErrors(prev => ({ ...prev, avatar: result.data?.errorMessage || result.error || 'Failed to generate avatars' }));
|
||||
setAvatarInfo(prev => ({ ...prev, isGenerating: false }));
|
||||
}
|
||||
} catch (error) {
|
||||
// Error handling is done in the mutation's onError callback
|
||||
setErrors(prev => ({ ...prev, avatar: 'Failed to generate avatars. Please try again.' }));
|
||||
setAvatarInfo(prev => ({ ...prev, isGenerating: false }));
|
||||
}
|
||||
};
|
||||
|
||||
const completeOnboardingMutation = useCompleteOnboarding({
|
||||
onSuccess: () => {
|
||||
// TODO: Handle avatar assignment separately if needed
|
||||
router.push('/dashboard');
|
||||
router.refresh();
|
||||
},
|
||||
onError: (error) => {
|
||||
setErrors({
|
||||
submit: error.message || 'Failed to create profile',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -384,42 +151,37 @@ export default function OnboardingWizard() {
|
||||
setErrors({});
|
||||
|
||||
try {
|
||||
await completeOnboardingMutation.mutateAsync({
|
||||
const result = await onCompleteOnboarding({
|
||||
firstName: personalInfo.firstName.trim(),
|
||||
lastName: personalInfo.lastName.trim(),
|
||||
displayName: personalInfo.displayName.trim(),
|
||||
country: personalInfo.country,
|
||||
timezone: personalInfo.timezone || undefined,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
onCompleted();
|
||||
} else {
|
||||
setErrors({ submit: result.error || 'Failed to create profile' });
|
||||
}
|
||||
} catch (error) {
|
||||
// Error handling is done in the mutation's onError callback
|
||||
setErrors({ submit: 'Failed to create profile' });
|
||||
}
|
||||
};
|
||||
|
||||
// Loading state comes from the mutations
|
||||
const loading = completeOnboardingMutation.isPending ||
|
||||
generateAvatarsMutation.isPending ||
|
||||
validateFacePhotoMutation.isPending;
|
||||
|
||||
const getCountryFlag = (countryCode: string): string => {
|
||||
const code = countryCode.toUpperCase();
|
||||
if (code.length === 2) {
|
||||
const codePoints = [...code].map(char => 127397 + char.charCodeAt(0));
|
||||
return String.fromCodePoint(...codePoints);
|
||||
}
|
||||
return '🏁';
|
||||
};
|
||||
const loading = false; // This would be managed by the parent component
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto px-4 py-10">
|
||||
{/* Header */}
|
||||
<div className="text-center mb-8">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
|
||||
<Flag className="w-8 h-8 text-primary-blue" />
|
||||
<span className="text-2xl">🏁</span>
|
||||
</div>
|
||||
<Heading level={1} className="mb-2">Welcome to GridPilot</Heading>
|
||||
<h1 className="text-4xl font-bold mb-2">Welcome to GridPilot</h1>
|
||||
<p className="text-gray-400">
|
||||
Let's set up your racing profile
|
||||
Let us set up your racing profile
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -434,323 +196,29 @@ export default function OnboardingWizard() {
|
||||
<form onSubmit={handleSubmit} className="relative">
|
||||
{/* Step 1: Personal Information */}
|
||||
{step === 1 && (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<Heading level={2} className="text-xl mb-1 flex items-center gap-2">
|
||||
<User className="w-5 h-5 text-primary-blue" />
|
||||
Personal Information
|
||||
</Heading>
|
||||
<p className="text-sm text-gray-400">
|
||||
Tell us a bit about yourself
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label htmlFor="firstName" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
First Name *
|
||||
</label>
|
||||
<Input
|
||||
id="firstName"
|
||||
type="text"
|
||||
value={personalInfo.firstName}
|
||||
onChange={(e) =>
|
||||
setPersonalInfo({ ...personalInfo, firstName: e.target.value })
|
||||
}
|
||||
error={!!errors.firstName}
|
||||
errorMessage={errors.firstName}
|
||||
placeholder="John"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="lastName" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Last Name *
|
||||
</label>
|
||||
<Input
|
||||
id="lastName"
|
||||
type="text"
|
||||
value={personalInfo.lastName}
|
||||
onChange={(e) =>
|
||||
setPersonalInfo({ ...personalInfo, lastName: e.target.value })
|
||||
}
|
||||
error={!!errors.lastName}
|
||||
errorMessage={errors.lastName}
|
||||
placeholder="Racer"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="displayName" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Display Name * <span className="text-gray-500 font-normal">(shown publicly)</span>
|
||||
</label>
|
||||
<Input
|
||||
id="displayName"
|
||||
type="text"
|
||||
value={personalInfo.displayName}
|
||||
onChange={(e) =>
|
||||
setPersonalInfo({ ...personalInfo, displayName: e.target.value })
|
||||
}
|
||||
error={!!errors.displayName}
|
||||
errorMessage={errors.displayName}
|
||||
placeholder="SpeedyRacer42"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label htmlFor="country" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Country *
|
||||
</label>
|
||||
<CountrySelect
|
||||
value={personalInfo.country}
|
||||
onChange={(value) =>
|
||||
setPersonalInfo({ ...personalInfo, country: value })
|
||||
}
|
||||
error={!!errors.country}
|
||||
errorMessage={errors.country ?? ''}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="timezone" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Timezone
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Clock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 z-10" />
|
||||
<select
|
||||
id="timezone"
|
||||
value={personalInfo.timezone}
|
||||
onChange={(e) =>
|
||||
setPersonalInfo({ ...personalInfo, timezone: e.target.value })
|
||||
}
|
||||
className="block w-full rounded-md border-0 px-4 py-3 pl-10 bg-iron-gray text-white shadow-sm ring-1 ring-inset ring-charcoal-outline placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-primary-blue transition-all duration-150 sm:text-sm appearance-none cursor-pointer"
|
||||
disabled={loading}
|
||||
>
|
||||
<option value="">Select timezone</option>
|
||||
{TIMEZONES.map((tz) => (
|
||||
<option key={tz.value} value={tz.value}>
|
||||
{tz.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronRight className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 rotate-90" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<PersonalInfoStep
|
||||
personalInfo={personalInfo}
|
||||
setPersonalInfo={setPersonalInfo}
|
||||
errors={errors}
|
||||
loading={loading}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Step 2: Avatar Generation */}
|
||||
{step === 2 && (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<Heading level={2} className="text-xl mb-1 flex items-center gap-2">
|
||||
<Camera className="w-5 h-5 text-primary-blue" />
|
||||
Create Your Racing Avatar
|
||||
</Heading>
|
||||
<p className="text-sm text-gray-400">
|
||||
Upload a photo and we'll generate a unique racing avatar for you
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Photo Upload */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-3">
|
||||
Upload Your Photo *
|
||||
</label>
|
||||
<div className="flex gap-6">
|
||||
{/* Upload Area */}
|
||||
<div
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className={`relative flex-1 flex flex-col items-center justify-center p-6 rounded-xl border-2 border-dashed cursor-pointer transition-all ${
|
||||
avatarInfo.facePhoto
|
||||
? 'border-performance-green bg-performance-green/5'
|
||||
: errors.facePhoto
|
||||
? 'border-red-500 bg-red-500/5'
|
||||
: 'border-charcoal-outline hover:border-primary-blue hover:bg-primary-blue/5'
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleFileSelect}
|
||||
className="hidden"
|
||||
/>
|
||||
|
||||
{avatarInfo.isValidating ? (
|
||||
<>
|
||||
<Loader2 className="w-10 h-10 text-primary-blue animate-spin mb-3" />
|
||||
<p className="text-sm text-gray-400">Validating photo...</p>
|
||||
</>
|
||||
) : avatarInfo.facePhoto ? (
|
||||
<>
|
||||
<div className="w-24 h-24 rounded-xl overflow-hidden mb-3 ring-2 ring-performance-green">
|
||||
<Image
|
||||
src={avatarInfo.facePhoto}
|
||||
alt="Your photo"
|
||||
width={96}
|
||||
height={96}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-sm text-performance-green flex items-center gap-1">
|
||||
<Check className="w-4 h-4" />
|
||||
Photo uploaded
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">Click to change</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="w-10 h-10 text-gray-500 mb-3" />
|
||||
<p className="text-sm text-gray-300 font-medium mb-1">
|
||||
Drop your photo here or click to upload
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
JPEG or PNG, max 5MB
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Preview area */}
|
||||
<div className="w-32 flex flex-col items-center justify-center">
|
||||
<div className="w-24 h-24 rounded-xl bg-iron-gray border border-charcoal-outline flex items-center justify-center overflow-hidden">
|
||||
{(() => {
|
||||
const selectedAvatarUrl =
|
||||
avatarInfo.selectedAvatarIndex !== null
|
||||
? avatarInfo.generatedAvatars[avatarInfo.selectedAvatarIndex]
|
||||
: undefined;
|
||||
if (!selectedAvatarUrl) {
|
||||
return <User className="w-8 h-8 text-gray-600" />;
|
||||
}
|
||||
return (
|
||||
<Image
|
||||
src={selectedAvatarUrl}
|
||||
alt="Selected avatar"
|
||||
width={96}
|
||||
height={96}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-2 text-center">Your avatar</p>
|
||||
</div>
|
||||
</div>
|
||||
{errors.facePhoto && (
|
||||
<p className="mt-2 text-sm text-red-400">{errors.facePhoto}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Suit Color Selection */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-3 flex items-center gap-2">
|
||||
<Palette className="w-4 h-4" />
|
||||
Racing Suit Color
|
||||
</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{SUIT_COLORS.map((color) => (
|
||||
<button
|
||||
key={color.value}
|
||||
type="button"
|
||||
onClick={() => setAvatarInfo({ ...avatarInfo, suitColor: color.value })}
|
||||
className={`relative w-10 h-10 rounded-lg transition-all ${
|
||||
avatarInfo.suitColor === color.value
|
||||
? 'ring-2 ring-primary-blue ring-offset-2 ring-offset-iron-gray scale-110'
|
||||
: 'hover:scale-105'
|
||||
}`}
|
||||
style={{ backgroundColor: color.hex }}
|
||||
title={color.label}
|
||||
>
|
||||
{avatarInfo.suitColor === color.value && (
|
||||
<Check className={`absolute inset-0 m-auto w-5 h-5 ${
|
||||
['white', 'yellow', 'cyan'].includes(color.value) ? 'text-gray-800' : 'text-white'
|
||||
}`} />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-gray-500">
|
||||
Selected: {SUIT_COLORS.find(c => c.value === avatarInfo.suitColor)?.label}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Generate Button */}
|
||||
{avatarInfo.facePhoto && !errors.facePhoto && (
|
||||
<div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
onClick={generateAvatars}
|
||||
disabled={avatarInfo.isGenerating || avatarInfo.isValidating}
|
||||
className="w-full flex items-center justify-center gap-2"
|
||||
>
|
||||
{avatarInfo.isGenerating ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
Generating your avatars...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles className="w-5 h-5" />
|
||||
{avatarInfo.generatedAvatars.length > 0 ? 'Regenerate Avatars' : 'Generate Racing Avatars'}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Generated Avatars */}
|
||||
{avatarInfo.generatedAvatars.length > 0 && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-300 mb-3">
|
||||
Choose Your Avatar *
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
{avatarInfo.generatedAvatars.map((url, index) => (
|
||||
<button
|
||||
key={index}
|
||||
type="button"
|
||||
onClick={() => setAvatarInfo({ ...avatarInfo, selectedAvatarIndex: index })}
|
||||
className={`relative aspect-square rounded-xl overflow-hidden border-2 transition-all ${
|
||||
avatarInfo.selectedAvatarIndex === index
|
||||
? 'border-primary-blue ring-2 ring-primary-blue/30 scale-105'
|
||||
: 'border-charcoal-outline hover:border-gray-500'
|
||||
}`}
|
||||
>
|
||||
<Image
|
||||
src={url}
|
||||
alt={`Avatar option ${index + 1}`}
|
||||
fill
|
||||
className="object-cover"
|
||||
/>
|
||||
{avatarInfo.selectedAvatarIndex === index && (
|
||||
<div className="absolute top-2 right-2 w-6 h-6 rounded-full bg-primary-blue flex items-center justify-center">
|
||||
<Check className="w-4 h-4 text-white" />
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{errors.avatar && (
|
||||
<p className="mt-2 text-sm text-red-400">{errors.avatar}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<AvatarStep
|
||||
avatarInfo={avatarInfo}
|
||||
setAvatarInfo={setAvatarInfo}
|
||||
errors={errors}
|
||||
setErrors={setErrors}
|
||||
onGenerateAvatars={generateAvatars}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Error Message */}
|
||||
{errors.submit && (
|
||||
<div className="mt-6 flex items-start gap-3 p-4 rounded-xl bg-red-500/10 border border-red-500/30">
|
||||
<AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
|
||||
<span className="text-red-400 flex-shrink-0 mt-0.5">⚠</span>
|
||||
<p className="text-sm text-red-400">{errors.submit}</p>
|
||||
</div>
|
||||
)}
|
||||
@@ -764,7 +232,7 @@ export default function OnboardingWizard() {
|
||||
disabled={step === 1 || loading}
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
<span>←</span>
|
||||
Back
|
||||
</Button>
|
||||
|
||||
@@ -777,7 +245,7 @@ export default function OnboardingWizard() {
|
||||
className="flex items-center gap-2"
|
||||
>
|
||||
Continue
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
<span>→</span>
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
@@ -788,12 +256,12 @@ export default function OnboardingWizard() {
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
<span className="animate-spin">⟳</span>
|
||||
Creating Profile...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Check className="w-4 h-4" />
|
||||
<span>✓</span>
|
||||
Complete Setup
|
||||
</>
|
||||
)}
|
||||
|
||||
151
apps/website/components/onboarding/PersonalInfoStep.tsx
Normal file
151
apps/website/components/onboarding/PersonalInfoStep.tsx
Normal file
@@ -0,0 +1,151 @@
|
||||
import { User, Clock, ChevronRight } from 'lucide-react';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import CountrySelect from '@/components/ui/CountrySelect';
|
||||
|
||||
export interface PersonalInfo {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
displayName: string;
|
||||
country: string;
|
||||
timezone: string;
|
||||
}
|
||||
|
||||
interface FormErrors {
|
||||
[key: string]: string | undefined;
|
||||
}
|
||||
|
||||
interface PersonalInfoStepProps {
|
||||
personalInfo: PersonalInfo;
|
||||
setPersonalInfo: (info: PersonalInfo) => void;
|
||||
errors: FormErrors;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
const TIMEZONES = [
|
||||
{ value: 'America/New_York', label: 'Eastern Time (ET)' },
|
||||
{ value: 'America/Chicago', label: 'Central Time (CT)' },
|
||||
{ value: 'America/Denver', label: 'Mountain Time (MT)' },
|
||||
{ value: 'America/Los_Angeles', label: 'Pacific Time (PT)' },
|
||||
{ value: 'Europe/London', label: 'Greenwich Mean Time (GMT)' },
|
||||
{ value: 'Europe/Berlin', label: 'Central European Time (CET)' },
|
||||
{ value: 'Europe/Paris', label: 'Central European Time (CET)' },
|
||||
{ value: 'Australia/Sydney', label: 'Australian Eastern Time (AET)' },
|
||||
{ value: 'Asia/Tokyo', label: 'Japan Standard Time (JST)' },
|
||||
{ value: 'America/Sao_Paulo', label: 'Brasília Time (BRT)' },
|
||||
];
|
||||
|
||||
export function PersonalInfoStep({ personalInfo, setPersonalInfo, errors, loading }: PersonalInfoStepProps) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<Heading level={2} className="text-xl mb-1 flex items-center gap-2">
|
||||
<User className="w-5 h-5 text-primary-blue" />
|
||||
Personal Information
|
||||
</Heading>
|
||||
<p className="text-sm text-gray-400">
|
||||
Tell us a bit about yourself
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label htmlFor="firstName" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
First Name *
|
||||
</label>
|
||||
<Input
|
||||
id="firstName"
|
||||
type="text"
|
||||
value={personalInfo.firstName}
|
||||
onChange={(e) =>
|
||||
setPersonalInfo({ ...personalInfo, firstName: e.target.value })
|
||||
}
|
||||
error={!!errors.firstName}
|
||||
errorMessage={errors.firstName}
|
||||
placeholder="John"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="lastName" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Last Name *
|
||||
</label>
|
||||
<Input
|
||||
id="lastName"
|
||||
type="text"
|
||||
value={personalInfo.lastName}
|
||||
onChange={(e) =>
|
||||
setPersonalInfo({ ...personalInfo, lastName: e.target.value })
|
||||
}
|
||||
error={!!errors.lastName}
|
||||
errorMessage={errors.lastName}
|
||||
placeholder="Racer"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="displayName" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Display Name * <span className="text-gray-500 font-normal">(shown publicly)</span>
|
||||
</label>
|
||||
<Input
|
||||
id="displayName"
|
||||
type="text"
|
||||
value={personalInfo.displayName}
|
||||
onChange={(e) =>
|
||||
setPersonalInfo({ ...personalInfo, displayName: e.target.value })
|
||||
}
|
||||
error={!!errors.displayName}
|
||||
errorMessage={errors.displayName}
|
||||
placeholder="SpeedyRacer42"
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label htmlFor="country" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Country *
|
||||
</label>
|
||||
<CountrySelect
|
||||
value={personalInfo.country}
|
||||
onChange={(value) =>
|
||||
setPersonalInfo({ ...personalInfo, country: value })
|
||||
}
|
||||
error={!!errors.country}
|
||||
errorMessage={errors.country ?? ''}
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="timezone" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Timezone
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Clock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 z-10" />
|
||||
<select
|
||||
id="timezone"
|
||||
value={personalInfo.timezone}
|
||||
onChange={(e) =>
|
||||
setPersonalInfo({ ...personalInfo, timezone: e.target.value })
|
||||
}
|
||||
className="block w-full rounded-md border-0 px-4 py-3 pl-10 bg-iron-gray text-white shadow-sm ring-1 ring-inset ring-charcoal-outline placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-primary-blue transition-all duration-150 sm:text-sm appearance-none cursor-pointer"
|
||||
disabled={loading}
|
||||
>
|
||||
<option value="">Select timezone</option>
|
||||
{TIMEZONES.map((tz) => (
|
||||
<option key={tz.value} value={tz.value}>
|
||||
{tz.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<ChevronRight className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 rotate-90" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
9
apps/website/components/profile/ProfileLayoutShell.tsx
Normal file
9
apps/website/components/profile/ProfileLayoutShell.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
interface ProfileLayoutShellProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export default function ProfileLayoutShell({ children }: ProfileLayoutShellProps) {
|
||||
return <div className="min-h-screen bg-deep-graphite">{children}</div>;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import Card from '@/components/ui/Card';
|
||||
import DriverIdentity from '@/components/drivers/DriverIdentity';
|
||||
import { DriverIdentity } from '@/components/drivers/DriverIdentity';
|
||||
import { useTeamRoster } from "@/lib/hooks/team";
|
||||
import { useState } from 'react';
|
||||
import type { DriverViewModel } from '@/lib/view-models/DriverViewModel';
|
||||
|
||||
@@ -34,12 +34,17 @@ const viewModelBuilderContract = require('./view-model-builder-contract');
|
||||
const singleExportPerFile = require('./single-export-per-file');
|
||||
const filenameMatchesExport = require('./filename-matches-export');
|
||||
const pageQueryMustUseBuilders = require('./page-query-must-use-builders');
|
||||
const pageQueryMustMapErrors = require('./page-query-must-map-errors');
|
||||
const mutationMustUseBuilders = require('./mutation-must-use-builders');
|
||||
const mutationMustMapErrors = require('./mutation-must-map-errors');
|
||||
const serviceFunctionFormat = require('./service-function-format');
|
||||
const libNoNextImports = require('./lib-no-next-imports');
|
||||
const servicesNoInstantiation = require('./services-no-instantiation');
|
||||
const noPageDtosDirectory = require('./no-page-dtos-directory');
|
||||
const cleanErrorHandling = require('./clean-error-handling');
|
||||
const servicesImplementContract = require('./services-implement-contract');
|
||||
const serverActionsReturnResult = require('./server-actions-return-result');
|
||||
const serverActionsInterface = require('./server-actions-interface');
|
||||
|
||||
module.exports = {
|
||||
rules: {
|
||||
@@ -80,9 +85,9 @@ module.exports = {
|
||||
'page-query-contract': pageQueryRules['pagequery-must-implement-contract'],
|
||||
'page-query-execute': pageQueryRules['pagequery-must-have-execute'],
|
||||
'page-query-return-type': pageQueryRules['pagequery-execute-return-type'],
|
||||
'page-query-must-map-errors': pageQueryMustMapErrors,
|
||||
|
||||
// Services Rules
|
||||
'services-must-be-marked': servicesRules['services-must-be-marked'],
|
||||
'services-no-external-api': servicesRules['no-external-api-in-services'],
|
||||
'services-must-be-pure': servicesRules['services-must-be-pure'],
|
||||
'services-must-return-result': cleanErrorHandling,
|
||||
@@ -109,9 +114,13 @@ module.exports = {
|
||||
|
||||
// Mutation Rules
|
||||
'mutation-contract': mutationContract,
|
||||
'mutation-must-use-builders': mutationMustUseBuilders,
|
||||
'mutation-must-map-errors': mutationMustMapErrors,
|
||||
|
||||
// Server Actions Rules
|
||||
'server-actions-must-use-mutations': serverActionsMustUseMutations,
|
||||
'server-actions-return-result': serverActionsReturnResult,
|
||||
'server-actions-interface': serverActionsInterface,
|
||||
|
||||
// View Data Rules
|
||||
'view-data-location': viewDataLocation,
|
||||
@@ -148,6 +157,15 @@ module.exports = {
|
||||
// Route Configuration Rules
|
||||
'no-hardcoded-routes': require('./no-hardcoded-routes'),
|
||||
'no-hardcoded-search-params': require('./no-hardcoded-search-params'),
|
||||
|
||||
// Logging Rules
|
||||
'no-console': require('./no-console'),
|
||||
|
||||
// Cookies
|
||||
'no-next-cookies-in-pages': require('./no-next-cookies-in-pages'),
|
||||
|
||||
// Config
|
||||
'no-direct-process-env': require('./no-direct-process-env'),
|
||||
|
||||
// Architecture Rules
|
||||
'no-index-files': require('./no-index-files'),
|
||||
@@ -183,7 +201,7 @@ module.exports = {
|
||||
'gridpilot-rules/template-no-external-state': 'error',
|
||||
'gridpilot-rules/template-no-global-objects': 'error',
|
||||
'gridpilot-rules/template-no-mutation-props': 'error',
|
||||
'gridpilot-rules/template-no-unsafe-html': 'error',
|
||||
'gridpilot-rules/template-no-unsafe-html': 'warn',
|
||||
|
||||
// Display Objects
|
||||
'gridpilot-rules/display-no-domain-models': 'error',
|
||||
@@ -197,7 +215,6 @@ module.exports = {
|
||||
'gridpilot-rules/page-query-return-type': 'error',
|
||||
|
||||
// Services
|
||||
'gridpilot-rules/services-must-be-marked': 'error',
|
||||
'gridpilot-rules/services-no-external-api': 'error',
|
||||
'gridpilot-rules/services-must-be-pure': 'error',
|
||||
|
||||
@@ -220,9 +237,13 @@ module.exports = {
|
||||
|
||||
// Mutations
|
||||
'gridpilot-rules/mutation-contract': 'error',
|
||||
'gridpilot-rules/mutation-must-use-builders': 'error',
|
||||
'gridpilot-rules/mutation-must-map-errors': 'error',
|
||||
|
||||
// Server Actions
|
||||
'gridpilot-rules/server-actions-must-use-mutations': 'error',
|
||||
'gridpilot-rules/server-actions-return-result': 'error',
|
||||
'gridpilot-rules/server-actions-interface': 'error',
|
||||
|
||||
// View Data
|
||||
'gridpilot-rules/view-data-location': 'error',
|
||||
@@ -243,7 +264,7 @@ module.exports = {
|
||||
'gridpilot-rules/lib-no-next-imports': 'error',
|
||||
|
||||
// Component Architecture Rules
|
||||
'gridpilot-rules/no-raw-html-in-app': 'error',
|
||||
'gridpilot-rules/no-raw-html-in-app': 'warn',
|
||||
'gridpilot-rules/ui-element-purity': 'error',
|
||||
'gridpilot-rules/no-nextjs-imports-in-ui': 'error',
|
||||
'gridpilot-rules/component-classification': 'warn',
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
/**
|
||||
* ESLint Rule: Mutation Contract
|
||||
*
|
||||
* Ensures mutations return Result type
|
||||
* Enforces the basic Mutation contract:
|
||||
* - Mutation classes should `implement Mutation<...>` (type-level contract)
|
||||
* - `execute()` must return `Promise<Result<...>>`
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Ensure mutations return Result type',
|
||||
description: 'Ensure mutations implement the Mutation contract and return Result',
|
||||
category: 'Mutation Contract',
|
||||
recommended: true,
|
||||
},
|
||||
messages: {
|
||||
wrongReturnType: 'Mutations must return Promise<Result<void, string>> - see apps/website/lib/contracts/Result.ts',
|
||||
mustImplementMutationInterface:
|
||||
'Mutation classes must implement Mutation<TInput, TOutput, TError> - see apps/website/lib/contracts/mutations/Mutation.ts',
|
||||
wrongReturnType:
|
||||
'Mutation execute() must return Promise<Result<TOutput, TError>> - see apps/website/lib/contracts/Result.ts',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
@@ -21,50 +26,112 @@ module.exports = {
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
|
||||
// Only apply to mutation files
|
||||
if (!filename.includes('/lib/mutations/') || !filename.endsWith('.ts')) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const mutationInterfaceNames = new Set(['Mutation']);
|
||||
|
||||
function isIdentifier(node, nameSet) {
|
||||
return node && node.type === 'Identifier' && nameSet.has(node.name);
|
||||
}
|
||||
|
||||
function isPromiseType(typeAnnotation) {
|
||||
if (!typeAnnotation || typeAnnotation.type !== 'TSTypeReference') return false;
|
||||
const typeName = typeAnnotation.typeName;
|
||||
return typeName && typeName.type === 'Identifier' && typeName.name === 'Promise';
|
||||
}
|
||||
|
||||
function isResultType(typeNode) {
|
||||
if (!typeNode || typeNode.type !== 'TSTypeReference') return false;
|
||||
const typeName = typeNode.typeName;
|
||||
if (!typeName) return false;
|
||||
|
||||
// Common case: Result<...>
|
||||
if (typeName.type === 'Identifier') {
|
||||
return typeName.name === 'Result';
|
||||
}
|
||||
|
||||
// Fallback: handle qualified names (rare)
|
||||
if (typeName.type === 'TSQualifiedName') {
|
||||
return typeName.right && typeName.right.type === 'Identifier' && typeName.right.name === 'Result';
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
const importPath = node.source && node.source.value;
|
||||
if (typeof importPath !== 'string') return;
|
||||
|
||||
// Accept both alias and relative imports.
|
||||
const isMutationContractImport =
|
||||
importPath.includes('/lib/contracts/mutations/Mutation') ||
|
||||
importPath.endsWith('lib/contracts/mutations/Mutation') ||
|
||||
importPath.endsWith('contracts/mutations/Mutation') ||
|
||||
importPath.endsWith('contracts/mutations/Mutation.ts');
|
||||
|
||||
if (!isMutationContractImport) return;
|
||||
|
||||
for (const spec of node.specifiers || []) {
|
||||
// import { Mutation as X } from '...'
|
||||
if (spec.type === 'ImportSpecifier' && spec.imported && spec.imported.type === 'Identifier') {
|
||||
mutationInterfaceNames.add(spec.local.name);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
ClassDeclaration(node) {
|
||||
if (!node.id || node.id.type !== 'Identifier') return;
|
||||
if (!node.id.name.endsWith('Mutation')) return;
|
||||
|
||||
const implementsNodes = node.implements || [];
|
||||
const implementsMutation = implementsNodes.some((impl) => {
|
||||
// `implements Mutation<...>`
|
||||
return impl && isIdentifier(impl.expression, mutationInterfaceNames);
|
||||
});
|
||||
|
||||
if (!implementsMutation) {
|
||||
context.report({
|
||||
node: node.id,
|
||||
messageId: 'mustImplementMutationInterface',
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
MethodDefinition(node) {
|
||||
if (node.key.type === 'Identifier' &&
|
||||
node.key.name === 'execute' &&
|
||||
node.value.type === 'FunctionExpression') {
|
||||
|
||||
const returnType = node.value.returnType;
|
||||
|
||||
// Check if it returns Promise<Result<...>>
|
||||
if (!returnType ||
|
||||
!returnType.typeAnnotation ||
|
||||
!returnType.typeAnnotation.typeName ||
|
||||
returnType.typeAnnotation.typeName.name !== 'Promise') {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'wrongReturnType',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (node.key.type !== 'Identifier' || node.key.name !== 'execute') return;
|
||||
if (!node.value) return;
|
||||
|
||||
// Check for Result type
|
||||
const typeArgs = returnType.typeAnnotation.typeParameters;
|
||||
if (!typeArgs || !typeArgs.params || typeArgs.params.length === 0) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'wrongReturnType',
|
||||
});
|
||||
return;
|
||||
}
|
||||
const returnType = node.value.returnType;
|
||||
const typeAnnotation = returnType && returnType.typeAnnotation;
|
||||
|
||||
const resultType = typeArgs.params[0];
|
||||
if (resultType.type !== 'TSTypeReference' ||
|
||||
!resultType.typeName ||
|
||||
(resultType.typeName.type === 'Identifier' && resultType.typeName.name !== 'Result')) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'wrongReturnType',
|
||||
});
|
||||
}
|
||||
// Must be Promise<...>
|
||||
if (!isPromiseType(typeAnnotation)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'wrongReturnType',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const promiseTypeArgs = typeAnnotation.typeParameters;
|
||||
if (!promiseTypeArgs || !promiseTypeArgs.params || promiseTypeArgs.params.length === 0) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'wrongReturnType',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Must be Promise<Result<...>> (we don't constrain the generics here)
|
||||
const inner = promiseTypeArgs.params[0];
|
||||
if (!isResultType(inner)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'wrongReturnType',
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
227
apps/website/eslint-rules/mutation-must-map-errors.js
Normal file
227
apps/website/eslint-rules/mutation-must-map-errors.js
Normal file
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* ESLint Rule: Mutation Must Map Errors
|
||||
*
|
||||
* Enforces the architecture documented in `lib/contracts/mutations/Mutation.ts`:
|
||||
* - Mutations call Services.
|
||||
* - Service returns Result<..., DomainError>.
|
||||
* - Mutation maps DomainError -> MutationError via mapToMutationError.
|
||||
* - Mutation returns Result<..., MutationError>.
|
||||
*
|
||||
* Strict enforcement (scoped to service results):
|
||||
* - Disallow returning a Service Result directly.
|
||||
* - `return result;` where `result` came from `await service.*(...)`
|
||||
* - `return service.someMethod(...)`
|
||||
* - `return await service.someMethod(...)`
|
||||
* - If a mutation does `if (result.isErr()) return Result.err(...)`,
|
||||
* it must be `Result.err(mapToMutationError(result.getError()))`.
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Require mutations to map service errors via mapToMutationError',
|
||||
category: 'Architecture',
|
||||
recommended: true,
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
mustMapMutationError:
|
||||
'Mutations must map service errors via mapToMutationError(result.getError()) before returning Result.err(...) - see apps/website/lib/contracts/mutations/Mutation.ts',
|
||||
mustNotReturnServiceResult:
|
||||
'Mutations must not return a Service Result directly; map errors and return a Mutation-layer Result instead - see apps/website/lib/contracts/mutations/Mutation.ts',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
|
||||
if (!filename.includes('/lib/mutations/') || !filename.endsWith('.ts')) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const resultVarsFromServiceCall = new Set();
|
||||
const serviceVarNames = new Set();
|
||||
const mapToMutationErrorNames = new Set(['mapToMutationError']);
|
||||
|
||||
function isIdentifier(node, name) {
|
||||
return node && node.type === 'Identifier' && node.name === name;
|
||||
}
|
||||
|
||||
function isResultErrCall(node) {
|
||||
return (
|
||||
node &&
|
||||
node.type === 'CallExpression' &&
|
||||
node.callee &&
|
||||
node.callee.type === 'MemberExpression' &&
|
||||
!node.callee.computed &&
|
||||
node.callee.object &&
|
||||
node.callee.object.type === 'Identifier' &&
|
||||
node.callee.object.name === 'Result' &&
|
||||
node.callee.property &&
|
||||
node.callee.property.type === 'Identifier' &&
|
||||
node.callee.property.name === 'err'
|
||||
);
|
||||
}
|
||||
|
||||
function isMapToMutationErrorCall(node) {
|
||||
return (
|
||||
node &&
|
||||
node.type === 'CallExpression' &&
|
||||
node.callee &&
|
||||
node.callee.type === 'Identifier' &&
|
||||
mapToMutationErrorNames.has(node.callee.name)
|
||||
);
|
||||
}
|
||||
|
||||
function isGetErrorCall(node, resultVarName) {
|
||||
return (
|
||||
node &&
|
||||
node.type === 'CallExpression' &&
|
||||
node.callee &&
|
||||
node.callee.type === 'MemberExpression' &&
|
||||
!node.callee.computed &&
|
||||
node.callee.object &&
|
||||
isIdentifier(node.callee.object, resultVarName) &&
|
||||
node.callee.property &&
|
||||
node.callee.property.type === 'Identifier' &&
|
||||
node.callee.property.name === 'getError'
|
||||
);
|
||||
}
|
||||
|
||||
function isServiceObjectName(name) {
|
||||
return typeof name === 'string' && (name.endsWith('Service') || serviceVarNames.has(name));
|
||||
}
|
||||
|
||||
function isServiceMemberCallExpression(callExpression) {
|
||||
if (!callExpression || callExpression.type !== 'CallExpression') return false;
|
||||
const callee = callExpression.callee;
|
||||
if (!callee || callee.type !== 'MemberExpression' || callee.computed) return false;
|
||||
if (!callee.object || callee.object.type !== 'Identifier') return false;
|
||||
return isServiceObjectName(callee.object.name);
|
||||
}
|
||||
|
||||
function isAwaitedServiceCall(init) {
|
||||
if (!init || init.type !== 'AwaitExpression') return false;
|
||||
return isServiceMemberCallExpression(init.argument);
|
||||
}
|
||||
|
||||
function collectReturnStatements(statementNode, callback) {
|
||||
if (!statementNode) return;
|
||||
|
||||
if (statementNode.type !== 'BlockStatement') {
|
||||
if (statementNode.type === 'ReturnStatement') callback(statementNode);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const s of statementNode.body || []) {
|
||||
if (!s) continue;
|
||||
if (s.type === 'ReturnStatement') callback(s);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
const importPath = node.source && node.source.value;
|
||||
if (typeof importPath !== 'string') return;
|
||||
|
||||
const isMutationErrorImport =
|
||||
importPath.includes('/lib/contracts/mutations/MutationError') ||
|
||||
importPath.endsWith('lib/contracts/mutations/MutationError') ||
|
||||
importPath.endsWith('contracts/mutations/MutationError') ||
|
||||
importPath.endsWith('contracts/mutations/MutationError.ts');
|
||||
|
||||
if (!isMutationErrorImport) return;
|
||||
|
||||
for (const spec of node.specifiers || []) {
|
||||
// import { mapToMutationError as X } from '...'
|
||||
if (spec.type === 'ImportSpecifier' && spec.imported && spec.imported.type === 'Identifier') {
|
||||
if (spec.imported.name === 'mapToMutationError') {
|
||||
mapToMutationErrorNames.add(spec.local.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
VariableDeclarator(node) {
|
||||
if (!node.id || node.id.type !== 'Identifier') return;
|
||||
|
||||
// const service = new SomeService();
|
||||
if (node.init && node.init.type === 'NewExpression' && node.init.callee && node.init.callee.type === 'Identifier') {
|
||||
if (node.init.callee.name.endsWith('Service')) {
|
||||
serviceVarNames.add(node.id.name);
|
||||
}
|
||||
}
|
||||
|
||||
// const result = await service.method(...)
|
||||
if (!isAwaitedServiceCall(node.init)) return;
|
||||
resultVarsFromServiceCall.add(node.id.name);
|
||||
},
|
||||
|
||||
ReturnStatement(node) {
|
||||
if (!node.argument) return;
|
||||
|
||||
// return result;
|
||||
if (node.argument.type === 'Identifier') {
|
||||
if (resultVarsFromServiceCall.has(node.argument.name)) {
|
||||
context.report({ node, messageId: 'mustNotReturnServiceResult' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// return service.method(...)
|
||||
if (node.argument.type === 'CallExpression') {
|
||||
if (isServiceMemberCallExpression(node.argument)) {
|
||||
context.report({ node, messageId: 'mustNotReturnServiceResult' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// return await service.method(...)
|
||||
if (node.argument.type === 'AwaitExpression') {
|
||||
if (isServiceMemberCallExpression(node.argument.argument)) {
|
||||
context.report({ node, messageId: 'mustNotReturnServiceResult' });
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
IfStatement(node) {
|
||||
// if (result.isErr()) { return Result.err(...) }
|
||||
const test = node.test;
|
||||
if (!test || test.type !== 'CallExpression') return;
|
||||
const testCallee = test.callee;
|
||||
if (
|
||||
!testCallee ||
|
||||
testCallee.type !== 'MemberExpression' ||
|
||||
testCallee.computed ||
|
||||
!testCallee.object ||
|
||||
testCallee.object.type !== 'Identifier' ||
|
||||
!testCallee.property ||
|
||||
testCallee.property.type !== 'Identifier' ||
|
||||
testCallee.property.name !== 'isErr'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resultVarName = testCallee.object.name;
|
||||
if (!resultVarsFromServiceCall.has(resultVarName)) return;
|
||||
|
||||
collectReturnStatements(node.consequent, (returnNode) => {
|
||||
const arg = returnNode.argument;
|
||||
if (!isResultErrCall(arg)) return;
|
||||
|
||||
const errArg = arg.arguments && arg.arguments[0];
|
||||
if (!isMapToMutationErrorCall(errArg)) {
|
||||
context.report({ node: returnNode, messageId: 'mustMapMutationError' });
|
||||
return;
|
||||
}
|
||||
|
||||
const mappedFrom = errArg.arguments && errArg.arguments[0];
|
||||
if (!isGetErrorCall(mappedFrom, resultVarName)) {
|
||||
context.report({ node: returnNode, messageId: 'mustMapMutationError' });
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
211
apps/website/eslint-rules/mutation-must-use-builders.js
Normal file
211
apps/website/eslint-rules/mutation-must-use-builders.js
Normal file
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* ESLint Rule: Mutation Must Use Builders
|
||||
*
|
||||
* Ensures mutations use builders to transform DTOs into ViewData
|
||||
* or return appropriate simple types (void, string, etc.)
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Ensure mutations use builders or return appropriate types, not DTOs',
|
||||
category: 'Mutation',
|
||||
recommended: true,
|
||||
},
|
||||
messages: {
|
||||
mustUseBuilder: 'Mutations must use ViewDataBuilder to transform DTOs or return simple types - see apps/website/lib/contracts/builders/ViewDataBuilder.ts',
|
||||
noDirectDtoReturn: 'Mutations must not return DTOs directly, use builders to create ViewData or return simple types like void, string, or primitive values',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
const isMutation = filename.includes('/lib/mutations/') && filename.endsWith('.ts');
|
||||
|
||||
if (!isMutation) {
|
||||
return {};
|
||||
}
|
||||
|
||||
let hasBuilderImport = false;
|
||||
const returnStatements = [];
|
||||
const methodDefinitions = [];
|
||||
|
||||
return {
|
||||
// Check for builder imports
|
||||
ImportDeclaration(node) {
|
||||
const importPath = node.source.value;
|
||||
if (importPath.includes('/builders/view-data/')) {
|
||||
hasBuilderImport = true;
|
||||
}
|
||||
},
|
||||
|
||||
// Track method definitions
|
||||
MethodDefinition(node) {
|
||||
if (node.key.type === 'Identifier' && node.key.name === 'execute') {
|
||||
methodDefinitions.push(node);
|
||||
}
|
||||
},
|
||||
|
||||
// Track return statements in execute method
|
||||
ReturnStatement(node) {
|
||||
// Only track returns inside execute method
|
||||
let parent = node;
|
||||
while (parent) {
|
||||
if (parent.type === 'MethodDefinition' &&
|
||||
parent.key.type === 'Identifier' &&
|
||||
parent.key.name === 'execute') {
|
||||
if (node.argument) {
|
||||
returnStatements.push(node);
|
||||
}
|
||||
break;
|
||||
}
|
||||
parent = parent.parent;
|
||||
}
|
||||
},
|
||||
|
||||
'Program:exit'() {
|
||||
if (methodDefinitions.length === 0) {
|
||||
return; // No execute method found
|
||||
}
|
||||
|
||||
// Check each return statement in execute method
|
||||
returnStatements.forEach(returnNode => {
|
||||
const returnExpr = returnNode.argument;
|
||||
|
||||
if (!returnExpr) return;
|
||||
|
||||
// Check if it's a Result type
|
||||
if (returnExpr.type === 'CallExpression') {
|
||||
const callee = returnExpr.callee;
|
||||
|
||||
// Check for Result.ok() or Result.err()
|
||||
if (callee.type === 'MemberExpression' &&
|
||||
callee.object.type === 'Identifier' &&
|
||||
callee.object.name === 'Result' &&
|
||||
callee.property.type === 'Identifier' &&
|
||||
(callee.property.name === 'ok' || callee.property.name === 'err')) {
|
||||
|
||||
const resultArg = returnExpr.arguments[0];
|
||||
|
||||
if (callee.property.name === 'ok') {
|
||||
// Check what's being returned in Result.ok()
|
||||
|
||||
// If it's a builder call, that's good
|
||||
if (resultArg && resultArg.type === 'CallExpression') {
|
||||
const builderCallee = resultArg.callee;
|
||||
if (builderCallee.type === 'MemberExpression' &&
|
||||
builderCallee.property.type === 'Identifier' &&
|
||||
builderCallee.property.name === 'build') {
|
||||
return; // Good: using builder
|
||||
}
|
||||
}
|
||||
|
||||
// If it's a method call that might be unwrap() or similar
|
||||
if (resultArg && resultArg.type === 'CallExpression') {
|
||||
const methodCallee = resultArg.callee;
|
||||
if (methodCallee.type === 'MemberExpression' &&
|
||||
methodCallee.property.type === 'Identifier') {
|
||||
const methodName = methodCallee.property.name;
|
||||
// Common DTO extraction methods
|
||||
if (['unwrap', 'getValue', 'getData', 'getResult'].includes(methodName)) {
|
||||
context.report({
|
||||
node: returnNode,
|
||||
messageId: 'noDirectDtoReturn',
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If it's a simple type (string, number, boolean, void), that's OK
|
||||
if (resultArg && (
|
||||
resultArg.type === 'Literal' ||
|
||||
resultArg.type === 'Identifier' &&
|
||||
['void', 'undefined', 'null'].includes(resultArg.name) ||
|
||||
resultArg.type === 'UnaryExpression' // e.g., undefined
|
||||
)) {
|
||||
return; // Good: simple type
|
||||
}
|
||||
|
||||
// If it's an identifier that might be a DTO
|
||||
if (resultArg && resultArg.type === 'Identifier') {
|
||||
const varName = resultArg.name;
|
||||
// Check if it's likely a DTO (ends with DTO, or common patterns)
|
||||
if (varName.match(/(DTO|Result|Response|Data)$/i) &&
|
||||
!varName.includes('ViewData') &&
|
||||
!varName.includes('ViewModel')) {
|
||||
context.report({
|
||||
node: returnNode,
|
||||
messageId: 'noDirectDtoReturn',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// If it's an object literal with DTO-like properties
|
||||
if (resultArg && resultArg.type === 'ObjectExpression') {
|
||||
const hasDtoLikeProps = resultArg.properties.some(prop => {
|
||||
if (prop.type === 'Property' && prop.key.type === 'Identifier') {
|
||||
const keyName = prop.key.name;
|
||||
return keyName.match(/(id|Id|URL|Url|DTO)$/i);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
if (hasDtoLikeProps) {
|
||||
context.report({
|
||||
node: returnNode,
|
||||
messageId: 'noDirectDtoReturn',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// If no builder import and we have DTO returns, report
|
||||
if (!hasBuilderImport && returnStatements.length > 0) {
|
||||
const hasDtoReturn = returnStatements.some(returnNode => {
|
||||
const returnExpr = returnNode.argument;
|
||||
if (returnExpr && returnExpr.type === 'CallExpression') {
|
||||
const callee = returnExpr.callee;
|
||||
if (callee.type === 'MemberExpression' &&
|
||||
callee.object.type === 'Identifier' &&
|
||||
callee.object.name === 'Result' &&
|
||||
callee.property.name === 'ok') {
|
||||
const arg = returnExpr.arguments[0];
|
||||
|
||||
// Check for method calls like result.unwrap()
|
||||
if (arg && arg.type === 'CallExpression') {
|
||||
const methodCallee = arg.callee;
|
||||
if (methodCallee.type === 'MemberExpression' &&
|
||||
methodCallee.property.type === 'Identifier') {
|
||||
const methodName = methodCallee.property.name;
|
||||
if (['unwrap', 'getValue', 'getData', 'getResult'].includes(methodName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check for identifier
|
||||
if (arg && arg.type === 'Identifier') {
|
||||
return arg.name.match(/(DTO|Result|Response|Data)$/i);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
if (hasDtoReturn) {
|
||||
context.report({
|
||||
node: methodDefinitions[0],
|
||||
messageId: 'mustUseBuilder',
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
48
apps/website/eslint-rules/no-console.js
Normal file
48
apps/website/eslint-rules/no-console.js
Normal file
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* @file no-console.js
|
||||
* Forbid console usage in website code.
|
||||
*
|
||||
* Use ConsoleLogger instead:
|
||||
* import { logger } from '@/lib/infrastructure/logging/logger'
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Forbid console.* usage (use ConsoleLogger wrapper instead)',
|
||||
category: 'Logging',
|
||||
recommended: true,
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
noConsole:
|
||||
'Do not use console. Use the project logger instead (ConsoleLogger). Import: `logger` from `@/lib/infrastructure/logging/logger`.',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
|
||||
// Allow console within the logging infrastructure itself.
|
||||
// (ConsoleLogger implements the console adapter.)
|
||||
if (
|
||||
filename.includes('/lib/infrastructure/logging/') ||
|
||||
filename.includes('/lib/infrastructure/EnhancedErrorReporter') ||
|
||||
filename.includes('/lib/infrastructure/GlobalErrorHandler') ||
|
||||
filename.includes('/lib/infrastructure/ErrorReplay') ||
|
||||
filename.includes('/eslint-rules/')
|
||||
) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
MemberExpression(node) {
|
||||
// console.log / console.error / console.warn / console.info / console.debug / console.group* ...
|
||||
if (node.object && node.object.type === 'Identifier' && node.object.name === 'console') {
|
||||
context.report({ node, messageId: 'noConsole' });
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
56
apps/website/eslint-rules/no-direct-process-env.js
Normal file
56
apps/website/eslint-rules/no-direct-process-env.js
Normal file
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* @file no-direct-process-env.js
|
||||
* Enforce centralized env/config access.
|
||||
*
|
||||
* Prefer:
|
||||
* - getWebsiteServerEnv()/getWebsitePublicEnv() from '@/lib/config/env'
|
||||
* - getWebsiteApiBaseUrl() from '@/lib/config/apiBaseUrl'
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Forbid direct process.env reads outside of config modules',
|
||||
category: 'Configuration',
|
||||
recommended: true,
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
noProcessEnv:
|
||||
'Do not read process.env directly here. Use `getWebsiteServerEnv()` / `getWebsitePublicEnv()` (apps/website/lib/config/env.ts) or a dedicated config helper (e.g. getWebsiteApiBaseUrl()).',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
|
||||
// Allow env reads in config layer and low-level infrastructure that must branch by env.
|
||||
if (
|
||||
filename.includes('/lib/config/') ||
|
||||
filename.includes('/lib/infrastructure/logging/') ||
|
||||
filename.includes('/eslint-rules/')
|
||||
) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
MemberExpression(node) {
|
||||
// process.env.X
|
||||
if (
|
||||
node.object &&
|
||||
node.object.type === 'MemberExpression' &&
|
||||
node.object.object &&
|
||||
node.object.object.type === 'Identifier' &&
|
||||
node.object.object.name === 'process' &&
|
||||
node.object.property &&
|
||||
node.object.property.type === 'Identifier' &&
|
||||
node.object.property.name === 'env'
|
||||
) {
|
||||
context.report({ node, messageId: 'noProcessEnv' });
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -166,7 +166,7 @@ module.exports = {
|
||||
// Check router.push() and router.replace()
|
||||
CallExpression(node) {
|
||||
if (node.callee.type === 'MemberExpression' &&
|
||||
node.callee.property.name === 'push' || node.callee.property.name === 'replace') {
|
||||
(node.callee.property.name === 'push' || node.callee.property.name === 'replace')) {
|
||||
|
||||
// Check if it's router.push/replace
|
||||
const calleeObj = node.callee.object;
|
||||
|
||||
@@ -17,10 +17,61 @@ module.exports = {
|
||||
manualSearchParams: 'Manual URLSearchParams construction. Use SearchParamBuilder instead: import { SearchParamBuilder } from "@/lib/routing/search-params"',
|
||||
manualGetParam: 'Manual search param access with get(). Use SearchParamParser instead: import { SearchParamParser } from "@/lib/routing/search-params"',
|
||||
manualSetParam: 'Manual search param setting with set(). Use SearchParamBuilder instead',
|
||||
manualQueryString:
|
||||
'Manual query-string construction detected (e.g. "?returnTo=..."). Use SearchParamBuilder instead: import { SearchParamBuilder } from "@/lib/routing/search-params/SearchParamBuilder"',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const SEARCH_PARAM_KEYS = new Set([
|
||||
// Auth
|
||||
'returnTo',
|
||||
'token',
|
||||
'email',
|
||||
'error',
|
||||
'message',
|
||||
// Sponsor
|
||||
'type',
|
||||
'campaignId',
|
||||
// Pagination
|
||||
'page',
|
||||
'limit',
|
||||
'offset',
|
||||
// Sorting
|
||||
'sortBy',
|
||||
'order',
|
||||
// Filters
|
||||
'status',
|
||||
'role',
|
||||
'tier',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Detect patterns like:
|
||||
* - "?returnTo="
|
||||
* - "&returnTo="
|
||||
* - "?page="
|
||||
* - "returnTo=" (within a URL string)
|
||||
*/
|
||||
function containsManualQueryParamFragment(raw) {
|
||||
if (typeof raw !== 'string' || raw.length === 0) return false;
|
||||
|
||||
// Fast pre-check
|
||||
if (!raw.includes('?') && !raw.includes('&') && !raw.includes('=')) return false;
|
||||
|
||||
for (const key of SEARCH_PARAM_KEYS) {
|
||||
if (
|
||||
raw.includes(`?${key}=`) ||
|
||||
raw.includes(`&${key}=`) ||
|
||||
// catches "...returnTo=..." in some string-building scenarios
|
||||
raw.includes(`${key}=`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
// Detect: new URLSearchParams()
|
||||
NewExpression(node) {
|
||||
@@ -49,6 +100,42 @@ module.exports = {
|
||||
}
|
||||
},
|
||||
|
||||
// Detect manual query strings, e.g.
|
||||
// `${routes.auth.login}?returnTo=${routes.protected.onboarding}`
|
||||
// routes.auth.login + '?returnTo=' + routes.protected.onboarding
|
||||
TemplateLiteral(node) {
|
||||
// If any static chunk contains a query-param fragment, treat it as manual.
|
||||
for (const quasi of node.quasis) {
|
||||
const raw = quasi.value && (quasi.value.raw ?? quasi.value.cooked);
|
||||
if (containsManualQueryParamFragment(raw)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'manualQueryString',
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
BinaryExpression(node) {
|
||||
// String concatenation patterns, e.g. a + '?returnTo=' + b
|
||||
if (node.operator !== '+') return;
|
||||
|
||||
// If either side is a literal string containing query params, report.
|
||||
const left = node.left;
|
||||
const right = node.right;
|
||||
|
||||
if (left && left.type === 'Literal' && typeof left.value === 'string' && containsManualQueryParamFragment(left.value)) {
|
||||
context.report({ node, messageId: 'manualQueryString' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (right && right.type === 'Literal' && typeof right.value === 'string' && containsManualQueryParamFragment(right.value)) {
|
||||
context.report({ node, messageId: 'manualQueryString' });
|
||||
return;
|
||||
}
|
||||
},
|
||||
|
||||
// Detect: params.get() or params.set()
|
||||
CallExpression(node) {
|
||||
if (node.callee.type === 'MemberExpression') {
|
||||
|
||||
57
apps/website/eslint-rules/no-next-cookies-in-pages.js
Normal file
57
apps/website/eslint-rules/no-next-cookies-in-pages.js
Normal file
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* @file no-next-cookies-in-pages.js
|
||||
*
|
||||
* Forbid direct cookie access in Next.js App Router pages.
|
||||
*
|
||||
* Rationale:
|
||||
* - Pages should stay focused on orchestration/rendering.
|
||||
* - Cookie parsing/auth/session concerns belong in middleware/layout boundaries or gateways.
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Forbid using next/headers cookies() in app/**/page.* files',
|
||||
category: 'Architecture',
|
||||
recommended: true,
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
noCookiesInPages:
|
||||
'Do not use cookies() in App Router pages. Move cookie/session handling to a layout boundary or middleware (or a dedicated gateway).',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
const isPageFile = /\/app\/.*\/page\.(ts|tsx)$/.test(filename);
|
||||
if (!isPageFile) return {};
|
||||
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
if (node.source && node.source.value === 'next/headers') {
|
||||
for (const spec of node.specifiers || []) {
|
||||
if (spec.type === 'ImportSpecifier' && spec.imported && spec.imported.name === 'cookies') {
|
||||
context.report({ node: spec, messageId: 'noCookiesInPages' });
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
CallExpression(node) {
|
||||
if (node.callee && node.callee.type === 'Identifier' && node.callee.name === 'cookies') {
|
||||
context.report({ node, messageId: 'noCookiesInPages' });
|
||||
}
|
||||
},
|
||||
|
||||
ImportExpression(node) {
|
||||
// Also catch: await import('next/headers') in a page.
|
||||
if (node.source && node.source.type === 'Literal' && node.source.value === 'next/headers') {
|
||||
context.report({ node, messageId: 'noCookiesInPages' });
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,43 +1,66 @@
|
||||
/**
|
||||
* ESLint rule to forbid raw HTML in app/ directory
|
||||
* ESLint rule to forbid raw HTML in app/, components/, and templates/ directories
|
||||
*
|
||||
* All HTML must be encapsulated in React components from components/ or ui/
|
||||
* All HTML must be encapsulated in React components from ui/ directory
|
||||
*
|
||||
* Rationale:
|
||||
* - app/ should only contain page/layout components
|
||||
* - components/ should use ui/ elements for all rendering
|
||||
* - templates/ should use ui/ elements for all rendering
|
||||
* - Raw HTML with styling violates separation of concerns
|
||||
* - UI logic belongs in components/ui layers
|
||||
* - UI elements ensure consistency and reusability
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Forbid raw HTML with styling in app/ directory',
|
||||
description: 'Forbid raw HTML with styling in app/, components/, and templates/ directories',
|
||||
category: 'Architecture',
|
||||
recommended: true,
|
||||
},
|
||||
fixable: null,
|
||||
schema: [],
|
||||
messages: {
|
||||
noRawHtml: 'Raw HTML with styling is forbidden in app/. Use a component from components/ or ui/.',
|
||||
noRawHtml: 'Raw HTML with styling is forbidden. Use a UI element from ui/ directory.',
|
||||
noRawHtmlInApp: 'Raw HTML in app/ is forbidden. Use components/ or ui/ elements.',
|
||||
noRawHtmlInComponents: 'Raw HTML in components/ should use ui/ elements instead.',
|
||||
noRawHtmlInTemplates: 'Raw HTML in templates/ should use ui/ elements instead.',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
const isInApp = filename.includes('/app/');
|
||||
|
||||
if (!isInApp) return {};
|
||||
// Determine which layer we're in
|
||||
const isInApp = filename.includes('/app/');
|
||||
const isInComponents = filename.includes('/components/');
|
||||
const isInTemplates = filename.includes('/templates/');
|
||||
|
||||
// Only apply to these UI layers
|
||||
if (!isInApp && !isInComponents && !isInTemplates) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// HTML tags that should be wrapped in components
|
||||
// HTML tags that should be wrapped in UI elements
|
||||
const htmlTags = [
|
||||
'div', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
||||
'p', 'button', 'input', 'form', 'label', 'select', 'textarea',
|
||||
'ul', 'ol', 'li', 'table', 'tr', 'td', 'th', 'thead', 'tbody',
|
||||
'section', 'article', 'header', 'footer', 'nav', 'aside',
|
||||
'main', 'aside', 'figure', 'figcaption', 'blockquote', 'code',
|
||||
'pre', 'a', 'img', 'svg', 'path', 'g', 'rect', 'circle'
|
||||
'pre', 'a', 'img', 'svg', 'path', 'g', 'rect', 'circle',
|
||||
'hr', 'br', 'strong', 'em', 'b', 'i', 'u', 'small', 'mark'
|
||||
];
|
||||
|
||||
// UI elements that are allowed (from ui/ directory)
|
||||
const allowedUiElements = [
|
||||
'Button', 'Input', 'Form', 'Label', 'Select', 'Textarea',
|
||||
'Card', 'Container', 'Grid', 'Stack', 'Box', 'Text', 'Heading',
|
||||
'List', 'Table', 'Section', 'Article', 'Header', 'Footer', 'Nav', 'Aside',
|
||||
'Link', 'Image', 'Icon', 'Avatar', 'Badge', 'Chip', 'Pill',
|
||||
'Modal', 'Dialog', 'Toast', 'Notification', 'Alert',
|
||||
'StepIndicator', 'Loading', 'Spinner', 'Progress'
|
||||
];
|
||||
|
||||
return {
|
||||
@@ -48,6 +71,11 @@ module.exports = {
|
||||
|
||||
const tagName = openingElement.name.name;
|
||||
|
||||
// Skip allowed UI elements
|
||||
if (allowedUiElements.includes(tagName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it's a raw HTML element (lowercase)
|
||||
if (htmlTags.includes(tagName) && tagName[0] === tagName[0].toLowerCase()) {
|
||||
|
||||
@@ -59,21 +87,85 @@ module.exports = {
|
||||
attr => attr.type === 'JSXAttribute' && attr.name.name === 'style'
|
||||
);
|
||||
|
||||
// Check for inline event handlers (also a concern)
|
||||
// Check for inline event handlers
|
||||
const hasInlineHandlers = openingElement.attributes.some(
|
||||
attr => attr.type === 'JSXAttribute' &&
|
||||
attr.name.name &&
|
||||
attr.name.name.startsWith('on')
|
||||
);
|
||||
|
||||
if (hasClassName || hasStyle || hasInlineHandlers) {
|
||||
// Check for other common attributes that suggest styling/behavior
|
||||
const hasCommonAttrs = openingElement.attributes.some(
|
||||
attr => attr.type === 'JSXAttribute' &&
|
||||
['id', 'role', 'aria-label', 'aria-hidden'].includes(attr.name.name)
|
||||
);
|
||||
|
||||
if (hasClassName || hasStyle || hasInlineHandlers || hasCommonAttrs) {
|
||||
let messageId = 'noRawHtml';
|
||||
|
||||
if (isInApp) {
|
||||
messageId = 'noRawHtmlInApp';
|
||||
} else if (isInComponents) {
|
||||
messageId = 'noRawHtmlInComponents';
|
||||
} else if (isInTemplates) {
|
||||
messageId = 'noRawHtmlInTemplates';
|
||||
}
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'noRawHtml',
|
||||
messageId,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Also check for dangerouslySetInnerHTML
|
||||
JSXAttribute(node) {
|
||||
if (node.name.name === 'dangerouslySetInnerHTML') {
|
||||
let messageId = 'noRawHtml';
|
||||
|
||||
if (isInApp) {
|
||||
messageId = 'noRawHtmlInApp';
|
||||
} else if (isInComponents) {
|
||||
messageId = 'noRawHtmlInComponents';
|
||||
} else if (isInTemplates) {
|
||||
messageId = 'noRawHtmlInTemplates';
|
||||
}
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Check for HTML strings in JSX expressions
|
||||
JSXExpressionContainer(node) {
|
||||
if (node.expression.type === 'Literal' && typeof node.expression.value === 'string') {
|
||||
const value = node.expression.value.trim();
|
||||
|
||||
// Check if it contains HTML-like content
|
||||
if (value.includes('<') && value.includes('>') &&
|
||||
(value.includes('class=') || value.includes('style=') ||
|
||||
value.match(/<\w+[^>]*>/))) {
|
||||
|
||||
let messageId = 'noRawHtml';
|
||||
|
||||
if (isInApp) {
|
||||
messageId = 'noRawHtmlInApp';
|
||||
} else if (isInComponents) {
|
||||
messageId = 'noRawHtmlInComponents';
|
||||
} else if (isInTemplates) {
|
||||
messageId = 'noRawHtmlInTemplates';
|
||||
}
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
};
|
||||
172
apps/website/eslint-rules/no-raw-html.js
Normal file
172
apps/website/eslint-rules/no-raw-html.js
Normal file
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* ESLint rule to forbid raw HTML across all UI layers
|
||||
*
|
||||
* All HTML must be encapsulated in UI elements from ui/ directory
|
||||
*
|
||||
* Rationale:
|
||||
* - app/ should only contain page/layout components
|
||||
* - components/ should use ui/ elements for all rendering
|
||||
* - templates/ should use ui/ elements for all rendering
|
||||
* - Raw HTML with styling violates separation of concerns
|
||||
* - UI elements ensure consistency and reusability
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Forbid raw HTML with styling in app/, components/, and templates/ directories',
|
||||
category: 'Architecture',
|
||||
recommended: true,
|
||||
},
|
||||
fixable: null,
|
||||
schema: [],
|
||||
messages: {
|
||||
noRawHtml: 'Raw HTML with styling is forbidden. Use a UI element from ui/ directory.',
|
||||
noRawHtmlInApp: 'Raw HTML in app/ is forbidden. Use components/ or ui/ elements.',
|
||||
noRawHtmlInComponents: 'Raw HTML in components/ should use ui/ elements instead.',
|
||||
noRawHtmlInTemplates: 'Raw HTML in templates/ should use ui/ elements instead.',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
|
||||
// Determine which layer we're in
|
||||
const isInApp = filename.includes('/app/');
|
||||
const isInComponents = filename.includes('/components/');
|
||||
const isInTemplates = filename.includes('/templates/');
|
||||
const isInUi = filename.includes('/ui/');
|
||||
|
||||
// Only apply to UI layers (not ui/ itself)
|
||||
if (!isInApp && !isInComponents && !isInTemplates) {
|
||||
return {};
|
||||
}
|
||||
|
||||
// HTML tags that should be wrapped in UI elements
|
||||
const htmlTags = [
|
||||
'div', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
||||
'p', 'button', 'input', 'form', 'label', 'select', 'textarea',
|
||||
'ul', 'ol', 'li', 'table', 'tr', 'td', 'th', 'thead', 'tbody',
|
||||
'section', 'article', 'header', 'footer', 'nav', 'aside',
|
||||
'main', 'aside', 'figure', 'figcaption', 'blockquote', 'code',
|
||||
'pre', 'a', 'img', 'svg', 'path', 'g', 'rect', 'circle',
|
||||
'hr', 'br', 'strong', 'em', 'b', 'i', 'u', 'small', 'mark'
|
||||
];
|
||||
|
||||
// UI elements that are allowed (from ui/ directory)
|
||||
const allowedUiElements = [
|
||||
'Button', 'Input', 'Form', 'Label', 'Select', 'Textarea',
|
||||
'Card', 'Container', 'Grid', 'Stack', 'Box', 'Text', 'Heading',
|
||||
'List', 'Table', 'Section', 'Article', 'Header', 'Footer', 'Nav', 'Aside',
|
||||
'Link', 'Image', 'Icon', 'Avatar', 'Badge', 'Chip', 'Pill',
|
||||
'Modal', 'Dialog', 'Toast', 'Notification', 'Alert',
|
||||
'StepIndicator', 'Loading', 'Spinner', 'Progress'
|
||||
];
|
||||
|
||||
return {
|
||||
JSXElement(node) {
|
||||
const openingElement = node.openingElement;
|
||||
|
||||
if (openingElement.name.type !== 'JSXIdentifier') return;
|
||||
|
||||
const tagName = openingElement.name.name;
|
||||
|
||||
// Skip allowed UI elements
|
||||
if (allowedUiElements.includes(tagName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it's a raw HTML element (lowercase)
|
||||
if (htmlTags.includes(tagName) && tagName[0] === tagName[0].toLowerCase()) {
|
||||
|
||||
// Check for styling attributes
|
||||
const hasClassName = openingElement.attributes.some(
|
||||
attr => attr.type === 'JSXAttribute' && attr.name.name === 'className'
|
||||
);
|
||||
const hasStyle = openingElement.attributes.some(
|
||||
attr => attr.type === 'JSXAttribute' && attr.name.name === 'style'
|
||||
);
|
||||
|
||||
// Check for inline event handlers
|
||||
const hasInlineHandlers = openingElement.attributes.some(
|
||||
attr => attr.type === 'JSXAttribute' &&
|
||||
attr.name.name &&
|
||||
attr.name.name.startsWith('on')
|
||||
);
|
||||
|
||||
// Check for other common attributes that suggest styling/behavior
|
||||
const hasCommonAttrs = openingElement.attributes.some(
|
||||
attr => attr.type === 'JSXAttribute' &&
|
||||
['id', 'role', 'aria-label', 'aria-hidden'].includes(attr.name.name)
|
||||
);
|
||||
|
||||
if (hasClassName || hasStyle || hasInlineHandlers || hasCommonAttrs) {
|
||||
let messageId = 'noRawHtml';
|
||||
|
||||
if (isInApp) {
|
||||
messageId = 'noRawHtmlInApp';
|
||||
} else if (isInComponents) {
|
||||
messageId = 'noRawHtmlInComponents';
|
||||
} else if (isInTemplates) {
|
||||
messageId = 'noRawHtmlInTemplates';
|
||||
}
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Also check for dangerouslySetInnerHTML
|
||||
JSXAttribute(node) {
|
||||
if (node.name.name === 'dangerouslySetInnerHTML') {
|
||||
let messageId = 'noRawHtml';
|
||||
|
||||
if (isInApp) {
|
||||
messageId = 'noRawHtmlInApp';
|
||||
} else if (isInComponents) {
|
||||
messageId = 'noRawHtmlInComponents';
|
||||
} else if (isInTemplates) {
|
||||
messageId = 'noRawHtmlInTemplates';
|
||||
}
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Check for HTML strings in JSX expressions
|
||||
JSXExpressionContainer(node) {
|
||||
if (node.expression.type === 'Literal' && typeof node.expression.value === 'string') {
|
||||
const value = node.expression.value.trim();
|
||||
|
||||
// Check if it contains HTML-like content
|
||||
if (value.includes('<') && value.includes('>') &&
|
||||
(value.includes('class=') || value.includes('style=') ||
|
||||
value.match(/<\w+[^>]*>/))) {
|
||||
|
||||
let messageId = 'noRawHtml';
|
||||
|
||||
if (isInApp) {
|
||||
messageId = 'noRawHtmlInApp';
|
||||
} else if (isInComponents) {
|
||||
messageId = 'noRawHtmlInComponents';
|
||||
} else if (isInTemplates) {
|
||||
messageId = 'noRawHtmlInTemplates';
|
||||
}
|
||||
|
||||
context.report({
|
||||
node,
|
||||
messageId,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
192
apps/website/eslint-rules/page-query-must-map-errors.js
Normal file
192
apps/website/eslint-rules/page-query-must-map-errors.js
Normal file
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* ESLint Rule: PageQuery Must Map Errors
|
||||
*
|
||||
* Enforces the architecture documented in `lib/contracts/page-queries/PageQuery.ts`:
|
||||
* - PageQueries call Services.
|
||||
* - Service returns Result<..., DomainError>.
|
||||
* - PageQuery maps DomainError -> PresentationError via mapToPresentationError.
|
||||
* - PageQuery returns Result<..., PresentationError>.
|
||||
*
|
||||
* Strict enforcement (scoped to service-result error branches):
|
||||
* - If a page query does `const result = await someService.*(...)` and later does
|
||||
* `if (result.isErr()) return Result.err(...)`, then the `Result.err(...)`
|
||||
* must be `Result.err(mapToPresentationError(result.getError()))`.
|
||||
* - PageQueries must not `return result;` for a service result variable.
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Require PageQueries to map service errors via mapToPresentationError',
|
||||
category: 'Architecture',
|
||||
recommended: true,
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
mustMapPresentationError:
|
||||
'PageQueries must map service errors via mapToPresentationError(result.getError()) before returning Result.err(...) - see apps/website/lib/contracts/page-queries/PageQuery.ts',
|
||||
mustNotReturnServiceResult:
|
||||
'PageQueries must not return a Service Result directly; map errors and return a Presentation-layer Result instead - see apps/website/lib/contracts/page-queries/PageQuery.ts',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
|
||||
if (!filename.includes('/lib/page-queries/') || !filename.endsWith('.ts')) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const resultVarsFromServiceCall = new Set();
|
||||
const mapToPresentationErrorNames = new Set(['mapToPresentationError']);
|
||||
|
||||
function isIdentifier(node, name) {
|
||||
return node && node.type === 'Identifier' && node.name === name;
|
||||
}
|
||||
|
||||
function isResultErrCall(node) {
|
||||
return (
|
||||
node &&
|
||||
node.type === 'CallExpression' &&
|
||||
node.callee &&
|
||||
node.callee.type === 'MemberExpression' &&
|
||||
!node.callee.computed &&
|
||||
node.callee.object &&
|
||||
node.callee.object.type === 'Identifier' &&
|
||||
node.callee.object.name === 'Result' &&
|
||||
node.callee.property &&
|
||||
node.callee.property.type === 'Identifier' &&
|
||||
node.callee.property.name === 'err'
|
||||
);
|
||||
}
|
||||
|
||||
function isMapToPresentationErrorCall(node) {
|
||||
return (
|
||||
node &&
|
||||
node.type === 'CallExpression' &&
|
||||
node.callee &&
|
||||
node.callee.type === 'Identifier' &&
|
||||
mapToPresentationErrorNames.has(node.callee.name)
|
||||
);
|
||||
}
|
||||
|
||||
function isGetErrorCall(node, resultVarName) {
|
||||
return (
|
||||
node &&
|
||||
node.type === 'CallExpression' &&
|
||||
node.callee &&
|
||||
node.callee.type === 'MemberExpression' &&
|
||||
!node.callee.computed &&
|
||||
node.callee.object &&
|
||||
isIdentifier(node.callee.object, resultVarName) &&
|
||||
node.callee.property &&
|
||||
node.callee.property.type === 'Identifier' &&
|
||||
node.callee.property.name === 'getError'
|
||||
);
|
||||
}
|
||||
|
||||
function isAwaitedServiceCall(init) {
|
||||
if (!init || init.type !== 'AwaitExpression') return false;
|
||||
const call = init.argument;
|
||||
if (!call || call.type !== 'CallExpression') return false;
|
||||
const callee = call.callee;
|
||||
|
||||
// `await service.someMethod(...)`
|
||||
if (callee.type === 'MemberExpression' && callee.object && callee.object.type === 'Identifier') {
|
||||
return callee.object.name.endsWith('Service');
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function collectReturnStatements(statementNode, callback) {
|
||||
if (!statementNode) return;
|
||||
|
||||
if (statementNode.type !== 'BlockStatement') {
|
||||
if (statementNode.type === 'ReturnStatement') callback(statementNode);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const s of statementNode.body || []) {
|
||||
if (!s) continue;
|
||||
if (s.type === 'ReturnStatement') callback(s);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
ImportDeclaration(node) {
|
||||
const importPath = node.source && node.source.value;
|
||||
if (typeof importPath !== 'string') return;
|
||||
|
||||
const isPresentationErrorImport =
|
||||
importPath.includes('/lib/contracts/page-queries/PresentationError') ||
|
||||
importPath.endsWith('lib/contracts/page-queries/PresentationError') ||
|
||||
importPath.endsWith('contracts/page-queries/PresentationError') ||
|
||||
importPath.endsWith('contracts/page-queries/PresentationError.ts');
|
||||
|
||||
if (!isPresentationErrorImport) return;
|
||||
|
||||
for (const spec of node.specifiers || []) {
|
||||
// import { mapToPresentationError as X } from '...'
|
||||
if (spec.type === 'ImportSpecifier' && spec.imported && spec.imported.type === 'Identifier') {
|
||||
if (spec.imported.name === 'mapToPresentationError') {
|
||||
mapToPresentationErrorNames.add(spec.local.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
VariableDeclarator(node) {
|
||||
if (!node.id || node.id.type !== 'Identifier') return;
|
||||
if (!isAwaitedServiceCall(node.init)) return;
|
||||
resultVarsFromServiceCall.add(node.id.name);
|
||||
},
|
||||
|
||||
ReturnStatement(node) {
|
||||
if (node.argument && node.argument.type === 'Identifier') {
|
||||
if (resultVarsFromServiceCall.has(node.argument.name)) {
|
||||
context.report({ node, messageId: 'mustNotReturnServiceResult' });
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
IfStatement(node) {
|
||||
const test = node.test;
|
||||
if (!test || test.type !== 'CallExpression') return;
|
||||
const testCallee = test.callee;
|
||||
if (
|
||||
!testCallee ||
|
||||
testCallee.type !== 'MemberExpression' ||
|
||||
testCallee.computed ||
|
||||
!testCallee.object ||
|
||||
testCallee.object.type !== 'Identifier' ||
|
||||
!testCallee.property ||
|
||||
testCallee.property.type !== 'Identifier' ||
|
||||
testCallee.property.name !== 'isErr'
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resultVarName = testCallee.object.name;
|
||||
if (!resultVarsFromServiceCall.has(resultVarName)) return;
|
||||
|
||||
collectReturnStatements(node.consequent, (returnNode) => {
|
||||
const arg = returnNode.argument;
|
||||
if (!isResultErrCall(arg)) return;
|
||||
|
||||
const errArg = arg.arguments && arg.arguments[0];
|
||||
if (!isMapToPresentationErrorCall(errArg)) {
|
||||
context.report({ node: returnNode, messageId: 'mustMapPresentationError' });
|
||||
return;
|
||||
}
|
||||
|
||||
const mappedFrom = errArg.arguments && errArg.arguments[0];
|
||||
if (!isGetErrorCall(mappedFrom, resultVarName)) {
|
||||
context.report({ node: returnNode, messageId: 'mustMapPresentationError' });
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -1,166 +1,115 @@
|
||||
/**
|
||||
* ESLint rule to enforce PageQueries use Builders
|
||||
* ESLint Rule: Page Query Must Use Builders
|
||||
*
|
||||
* PageQueries should not manually transform API DTOs or return them directly.
|
||||
* They must use Builder classes to transform API DTOs to View Data.
|
||||
* Ensures page queries use builders to transform DTOs into ViewData
|
||||
* This prevents DTOs from leaking to the client
|
||||
*/
|
||||
|
||||
module.exports = {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Enforce PageQueries use Builders for data transformation',
|
||||
description: 'Ensure page queries use builders to transform DTOs into ViewData',
|
||||
category: 'Page Query',
|
||||
recommended: true,
|
||||
},
|
||||
fixable: null,
|
||||
schema: [],
|
||||
messages: {
|
||||
mustUseBuilder: 'PageQueries must use Builder classes to transform API DTOs to View Data. Found manual transformation or direct API DTO return.',
|
||||
multipleExports: 'PageQuery files should only export the PageQuery class, not DTOs.',
|
||||
mustUseBuilder: 'PageQueries must use ViewDataBuilder to transform DTOs - see apps/website/lib/contracts/builders/ViewDataBuilder.ts',
|
||||
noDirectDtoReturn: 'PageQueries must not return DTOs directly, use builders to create ViewData',
|
||||
},
|
||||
schema: [],
|
||||
},
|
||||
|
||||
create(context) {
|
||||
let inPageQueryExecute = false;
|
||||
let hasManualTransformation = false;
|
||||
let hasMultipleExports = false;
|
||||
let hasBuilderCall = false;
|
||||
let pageQueryClassName = null;
|
||||
const filename = context.getFilename();
|
||||
const isPageQuery = filename.includes('/page-queries/') && filename.endsWith('.ts');
|
||||
|
||||
if (!isPageQuery) {
|
||||
return {};
|
||||
}
|
||||
|
||||
let hasBuilderImport = false;
|
||||
const builderUsages = [];
|
||||
const returnStatements = [];
|
||||
|
||||
return {
|
||||
// Track PageQuery class name
|
||||
ClassDeclaration(node) {
|
||||
if (node.id && node.id.name && node.id.name.endsWith('PageQuery')) {
|
||||
pageQueryClassName = node.id.name;
|
||||
}
|
||||
},
|
||||
|
||||
// Track PageQuery class execute method
|
||||
MethodDefinition(node) {
|
||||
if (node.key.type === 'Identifier' &&
|
||||
node.key.name === 'execute' &&
|
||||
node.parent.type === 'ClassBody') {
|
||||
// Check for builder imports
|
||||
ImportDeclaration(node) {
|
||||
const importPath = node.source.value;
|
||||
if (importPath.includes('/builders/view-data/')) {
|
||||
hasBuilderImport = true;
|
||||
|
||||
const classNode = node.parent.parent;
|
||||
if (classNode && classNode.id && classNode.id.name &&
|
||||
classNode.id.name.endsWith('PageQuery')) {
|
||||
inPageQueryExecute = true;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Detect Builder calls
|
||||
CallExpression(node) {
|
||||
if (inPageQueryExecute) {
|
||||
// Check for Builder.build() or Builder.createViewData()
|
||||
if (node.callee.type === 'MemberExpression' &&
|
||||
node.callee.property.type === 'Identifier' &&
|
||||
(node.callee.property.name === 'build' || node.callee.property.name === 'createViewData')) {
|
||||
|
||||
// Check if the object is a Builder
|
||||
if (node.callee.object.type === 'Identifier' &&
|
||||
(node.callee.object.name.includes('Builder') ||
|
||||
node.callee.object.name.includes('builder'))) {
|
||||
hasBuilderCall = true;
|
||||
// Track which builder is imported
|
||||
node.specifiers.forEach(spec => {
|
||||
if (spec.type === 'ImportSpecifier') {
|
||||
builderUsages.push({
|
||||
name: spec.imported.name,
|
||||
localName: spec.local.name,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Detect object literal assignments (manual transformation)
|
||||
VariableDeclarator(node) {
|
||||
if (inPageQueryExecute && node.init && node.init.type === 'ObjectExpression') {
|
||||
hasManualTransformation = true;
|
||||
}
|
||||
},
|
||||
|
||||
// Detect object literal in return statements
|
||||
// Track return statements
|
||||
ReturnStatement(node) {
|
||||
if (inPageQueryExecute && node.argument) {
|
||||
// Direct object literal return
|
||||
if (node.argument.type === 'ObjectExpression') {
|
||||
hasManualTransformation = true;
|
||||
}
|
||||
// Direct identifier return (likely API DTO)
|
||||
else if (node.argument.type === 'Identifier' &&
|
||||
!node.argument.name.includes('ViewData') &&
|
||||
!node.argument.name.includes('viewData')) {
|
||||
// This might be returning an API DTO directly
|
||||
// We'll flag it as manual transformation since no builder was used
|
||||
if (!hasBuilderCall) {
|
||||
hasManualTransformation = true;
|
||||
}
|
||||
}
|
||||
// CallExpression like Result.ok(apiDto) or Result.err()
|
||||
else if (node.argument.type === 'CallExpression') {
|
||||
// Check if it's a Result call with an identifier argument
|
||||
const callExpr = node.argument;
|
||||
if (callExpr.callee.type === 'MemberExpression' &&
|
||||
callExpr.callee.object.type === 'Identifier' &&
|
||||
callExpr.callee.object.name === 'Result' &&
|
||||
callExpr.callee.property.type === 'Identifier' &&
|
||||
(callExpr.callee.property.name === 'ok' || callExpr.callee.property.name === 'err')) {
|
||||
|
||||
// If it's Result.ok(someIdentifier), check if the identifier is likely an API DTO
|
||||
if (callExpr.callee.property.name === 'ok' &&
|
||||
callExpr.arguments.length > 0 &&
|
||||
callExpr.arguments[0].type === 'Identifier') {
|
||||
const argName = callExpr.arguments[0].name;
|
||||
// Common API DTO naming patterns
|
||||
const isApiDto = argName.includes('Dto') ||
|
||||
argName.includes('api') ||
|
||||
argName === 'result' ||
|
||||
argName === 'data';
|
||||
|
||||
if (isApiDto && !hasBuilderCall) {
|
||||
hasManualTransformation = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Track exports
|
||||
ExportNamedDeclaration(node) {
|
||||
if (node.declaration) {
|
||||
if (node.declaration.type === 'ClassDeclaration') {
|
||||
const className = node.declaration.id?.name;
|
||||
if (className && !className.endsWith('PageQuery')) {
|
||||
hasMultipleExports = true;
|
||||
}
|
||||
} else if (node.declaration.type === 'InterfaceDeclaration' ||
|
||||
node.declaration.type === 'TypeAlias') {
|
||||
hasMultipleExports = true;
|
||||
}
|
||||
} else if (node.specifiers && node.specifiers.length > 0) {
|
||||
hasMultipleExports = true;
|
||||
}
|
||||
},
|
||||
|
||||
'MethodDefinition:exit'(node) {
|
||||
if (node.key.type === 'Identifier' && node.key.name === 'execute') {
|
||||
inPageQueryExecute = false;
|
||||
if (node.argument) {
|
||||
returnStatements.push(node);
|
||||
}
|
||||
},
|
||||
|
||||
'Program:exit'() {
|
||||
// Only report if no builder was used
|
||||
if (hasManualTransformation && !hasBuilderCall) {
|
||||
if (!hasBuilderImport) {
|
||||
context.report({
|
||||
node: context.getSourceCode().ast,
|
||||
messageId: 'mustUseBuilder',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasMultipleExports) {
|
||||
context.report({
|
||||
node: context.getSourceCode().ast,
|
||||
messageId: 'multipleExports',
|
||||
});
|
||||
}
|
||||
// Check if return statements use builders
|
||||
returnStatements.forEach(returnNode => {
|
||||
const returnExpr = returnNode.argument;
|
||||
|
||||
// Check if it's a builder call
|
||||
if (returnExpr && returnExpr.type === 'CallExpression') {
|
||||
const callee = returnExpr.callee;
|
||||
|
||||
// Check if it's a builder method call (e.g., ViewDataBuilder.build())
|
||||
if (callee.type === 'MemberExpression' &&
|
||||
callee.property.type === 'Identifier' &&
|
||||
callee.property.name === 'build') {
|
||||
// This is good - using a builder
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if it's a direct Result.ok() with DTO
|
||||
if (callee.type === 'MemberExpression' &&
|
||||
callee.object.type === 'Identifier' &&
|
||||
callee.object.name === 'Result' &&
|
||||
callee.property.type === 'Identifier' &&
|
||||
callee.property.name === 'ok') {
|
||||
|
||||
// Check if the argument is a variable that might be a DTO
|
||||
if (returnExpr.arguments && returnExpr.arguments[0]) {
|
||||
const arg = returnExpr.arguments[0];
|
||||
|
||||
// If it's an identifier, check if it's likely a DTO
|
||||
if (arg.type === 'Identifier') {
|
||||
const varName = arg.name;
|
||||
// Common DTO patterns: result, data, dto, apiResult, etc.
|
||||
if (varName.match(/(result|data|dto|apiResult|response)/i)) {
|
||||
context.report({
|
||||
node: returnNode,
|
||||
messageId: 'noDirectDtoReturn',
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user