nextjs-rewrite (#5)
Reviewed-on: #5 Co-authored-by: David Gwilliam <dhgwilliam@gmail.com> Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #5.
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import EditTournamentForm from '@/components/EditTournamentForm'
|
||||
|
||||
// Mock next/navigation
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => ({
|
||||
push: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
|
||||
// Mock next/link
|
||||
vi.mock('next/link', () => ({
|
||||
default: ({ children, href }: { children: React.ReactNode; href: string }) => (
|
||||
<a href={href}>{children}</a>
|
||||
),
|
||||
}))
|
||||
|
||||
// Mock fetch
|
||||
global.fetch = vi.fn()
|
||||
|
||||
const mockTournament = {
|
||||
id: 1,
|
||||
event_id: null,
|
||||
name: 'Test Tournament',
|
||||
description: 'A test tournament',
|
||||
eventDate: new Date('2024-01-15'),
|
||||
eventType: 'tournament',
|
||||
format: 'round_robin',
|
||||
status: 'planned',
|
||||
maxParticipants: 16,
|
||||
ownerId: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
}
|
||||
|
||||
describe('EditTournamentForm', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders form with initial values', () => {
|
||||
render(<EditTournamentForm tournament={mockTournament} />)
|
||||
|
||||
expect(screen.getByLabelText('Tournament Name')).toHaveValue('Test Tournament')
|
||||
expect(screen.getByLabelText('Description')).toHaveValue('A test tournament')
|
||||
expect(screen.getByLabelText('Date')).toHaveValue('2024-01-15')
|
||||
expect(screen.getByLabelText('Event Type')).toHaveValue('tournament')
|
||||
expect(screen.getByLabelText('Format')).toHaveValue('round_robin')
|
||||
expect(screen.getByLabelText('Status')).toHaveValue('planned')
|
||||
expect(screen.getByLabelText('Max Participants (optional)')).toHaveValue(16)
|
||||
})
|
||||
|
||||
it('updates form values on change', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<EditTournamentForm tournament={mockTournament} />)
|
||||
|
||||
const nameInput = screen.getByLabelText('Tournament Name')
|
||||
await user.clear(nameInput)
|
||||
await user.type(nameInput, 'Updated Tournament')
|
||||
|
||||
expect(nameInput).toHaveValue('Updated Tournament')
|
||||
})
|
||||
|
||||
it('submits form with updated data', async () => {
|
||||
const user = userEvent.setup()
|
||||
;(global.fetch as any).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ success: true }),
|
||||
})
|
||||
|
||||
render(<EditTournamentForm tournament={mockTournament} />)
|
||||
|
||||
const nameInput = screen.getByLabelText('Tournament Name')
|
||||
await user.clear(nameInput)
|
||||
await user.type(nameInput, 'Updated Tournament')
|
||||
|
||||
const submitButton = screen.getByText('Save Changes')
|
||||
await user.click(submitButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(global.fetch).toHaveBeenCalledWith(
|
||||
'/api/tournaments/1',
|
||||
expect.objectContaining({
|
||||
method: 'PUT',
|
||||
body: expect.stringContaining('Updated Tournament'),
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('shows error message on failed submission', async () => {
|
||||
const user = userEvent.setup()
|
||||
;(global.fetch as any).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: async () => ({ error: 'Failed to update tournament' }),
|
||||
})
|
||||
|
||||
render(<EditTournamentForm tournament={mockTournament} />)
|
||||
|
||||
const submitButton = screen.getByText('Save Changes')
|
||||
await user.click(submitButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Failed to update tournament')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('disables submit button while loading', async () => {
|
||||
const user = userEvent.setup()
|
||||
;(global.fetch as any).mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve({
|
||||
ok: true,
|
||||
json: async () => ({ success: true }),
|
||||
})
|
||||
}, 100)
|
||||
})
|
||||
)
|
||||
|
||||
render(<EditTournamentForm tournament={mockTournament} />)
|
||||
|
||||
const submitButton = screen.getByText('Save Changes')
|
||||
await user.click(submitButton)
|
||||
|
||||
expect(submitButton).toBeDisabled()
|
||||
expect(submitButton).toHaveTextContent('Saving...')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* Epic 1: Authentication & User Management
|
||||
* Component Test: Navigation
|
||||
*
|
||||
* Tests the navigation component for proper display based on session state
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import Navigation from '@/components/Navigation'
|
||||
|
||||
// Mock the SessionProvider
|
||||
vi.mock('@/components/SessionProvider', () => ({
|
||||
useSession: vi.fn(),
|
||||
}))
|
||||
|
||||
// Mock the auth-client
|
||||
vi.mock('@/lib/auth-client', () => ({
|
||||
authClient: {
|
||||
signOut: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
// Mock fetch for role API call
|
||||
global.fetch = vi.fn()
|
||||
|
||||
import { useSession } from '@/components/SessionProvider'
|
||||
|
||||
describe('Epic 1: Navigation Component', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(global.fetch).mockResolvedValue({
|
||||
json: () => Promise.resolve({ role: 'player' }),
|
||||
} as Response)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('renders the logo and basic links when not logged in', () => {
|
||||
vi.mocked(useSession).mockReturnValue({
|
||||
session: null,
|
||||
loading: false,
|
||||
refreshSession: vi.fn(),
|
||||
})
|
||||
|
||||
render(<Navigation />)
|
||||
|
||||
expect(screen.getByText('EuchreCamp')).toBeInTheDocument()
|
||||
expect(screen.getByText('Rankings')).toBeInTheDocument()
|
||||
expect(screen.getByText('Sign in')).toBeInTheDocument()
|
||||
expect(screen.getByText('Sign up')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows user menu when logged in', async () => {
|
||||
vi.mocked(useSession).mockReturnValue({
|
||||
session: {
|
||||
user: {
|
||||
id: 'user-123',
|
||||
email: 'test@example.com',
|
||||
name: 'Test User',
|
||||
role: 'player'
|
||||
},
|
||||
session: { token: 'abc123' },
|
||||
},
|
||||
loading: false,
|
||||
refreshSession: vi.fn(),
|
||||
})
|
||||
|
||||
render(<Navigation />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Test User')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
expect(screen.getByText('Sign out')).toBeInTheDocument()
|
||||
expect(screen.getByText('Tournaments')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Tournaments link when logged in', async () => {
|
||||
vi.mocked(useSession).mockReturnValue({
|
||||
session: {
|
||||
user: {
|
||||
id: 'user-123',
|
||||
email: 'test@example.com',
|
||||
name: 'Test User',
|
||||
role: 'player'
|
||||
},
|
||||
session: { token: 'abc123' },
|
||||
},
|
||||
loading: false,
|
||||
refreshSession: vi.fn(),
|
||||
})
|
||||
|
||||
render(<Navigation />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Tournaments')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('shows admin link for club_admin role', async () => {
|
||||
vi.mocked(useSession).mockReturnValue({
|
||||
session: {
|
||||
user: {
|
||||
id: 'admin-123',
|
||||
email: 'admin@example.com',
|
||||
name: 'Admin User',
|
||||
role: 'club_admin',
|
||||
},
|
||||
session: { token: 'abc123' },
|
||||
},
|
||||
loading: false,
|
||||
refreshSession: vi.fn(),
|
||||
})
|
||||
|
||||
// Mock fetch to return club_admin role
|
||||
vi.mocked(global.fetch).mockResolvedValue({
|
||||
json: () => Promise.resolve({ role: 'club_admin' }),
|
||||
} as Response)
|
||||
|
||||
render(<Navigation />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Admin')).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.getByText('Tournaments')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides admin link for non-admin users', async () => {
|
||||
vi.mocked(useSession).mockReturnValue({
|
||||
session: {
|
||||
user: {
|
||||
id: 'player-123',
|
||||
email: 'player@example.com',
|
||||
name: 'Player User',
|
||||
role: 'player',
|
||||
},
|
||||
session: { token: 'abc123' },
|
||||
},
|
||||
loading: false,
|
||||
refreshSession: vi.fn(),
|
||||
})
|
||||
|
||||
// Mock fetch to return player role
|
||||
vi.mocked(global.fetch).mockResolvedValue({
|
||||
json: () => Promise.resolve({ role: 'player' }),
|
||||
} as Response)
|
||||
|
||||
render(<Navigation />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Tournaments')).toBeInTheDocument()
|
||||
})
|
||||
expect(screen.queryByText('Admin')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows loading state', () => {
|
||||
vi.mocked(useSession).mockReturnValue({
|
||||
session: null,
|
||||
loading: true,
|
||||
refreshSession: vi.fn(),
|
||||
})
|
||||
|
||||
render(<Navigation />)
|
||||
|
||||
expect(screen.getByText('Loading...')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { getSession } from '@/lib/auth-simple'
|
||||
|
||||
// Mock next/headers
|
||||
vi.mock('next/headers', () => ({
|
||||
cookies: vi.fn().mockResolvedValue({
|
||||
get: vi.fn().mockReturnValue({ name: 'better-auth.session_token', value: 'test-token' }),
|
||||
}),
|
||||
}))
|
||||
|
||||
// Mock fetch
|
||||
const mockFetch = vi.fn()
|
||||
global.fetch = mockFetch as any
|
||||
|
||||
describe('getSession', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('returns session data when auth API returns 200', async () => {
|
||||
const mockSession = {
|
||||
session: { token: 'test-token', expiresAt: new Date().toISOString() },
|
||||
user: { id: 'user-123', email: 'test@example.com' },
|
||||
}
|
||||
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(JSON.stringify(mockSession), { status: 200 })
|
||||
)
|
||||
|
||||
const result = await getSession()
|
||||
|
||||
expect(result).toEqual(mockSession)
|
||||
expect(mockFetch).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns null when auth API returns non-200 status', async () => {
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response(null, { status: 401 })
|
||||
)
|
||||
|
||||
const result = await getSession()
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when an error occurs', async () => {
|
||||
mockFetch.mockRejectedValue(new Error('Network error'))
|
||||
|
||||
const result = await getSession()
|
||||
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Acceptance Test: Account Creation, Login, and Deletion (API-based)
|
||||
*
|
||||
* This test demonstrates the full workflow using API calls:
|
||||
* 1. Create a test account via registration API
|
||||
* 2. Log in using the authentication API
|
||||
* 3. Delete the test account
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
// Generate unique test account credentials
|
||||
function getTestCredentials() {
|
||||
const timestamp = Date.now();
|
||||
const random = Math.random().toString(36).substring(7);
|
||||
return {
|
||||
email: `test-api-${timestamp}-${random}@example.com`,
|
||||
password: 'TestPassword123!',
|
||||
name: `Test API User ${timestamp}`
|
||||
};
|
||||
}
|
||||
|
||||
test.describe.serial('Account Lifecycle API Acceptance Test', () => {
|
||||
let testEmail: string;
|
||||
let testPassword: string;
|
||||
let testName: string;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
const credentials = getTestCredentials();
|
||||
testEmail = credentials.email;
|
||||
testPassword = credentials.password;
|
||||
testName = credentials.name;
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
// Clean up: delete test user if they still exist
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
if (user) {
|
||||
await prisma.user.delete({ where: { id: user.id } });
|
||||
console.log(`Cleaned up test user: ${testEmail}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Cleanup error:', error);
|
||||
}
|
||||
});
|
||||
|
||||
test('1. Create test account via API', async ({ request }) => {
|
||||
console.log('Test 1 - testEmail:', testEmail);
|
||||
|
||||
// Register via API
|
||||
const response = await request.post('http://localhost:3000/api/auth/sign-up/email', {
|
||||
data: {
|
||||
email: testEmail,
|
||||
password: testPassword,
|
||||
name: testName
|
||||
},
|
||||
headers: {
|
||||
'Origin': 'http://localhost:3000'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('API Registration Response:', response.status(), await response.text());
|
||||
expect(response.ok()).toBeTruthy();
|
||||
const data = await response.json();
|
||||
expect(data.user.email).toBe(testEmail);
|
||||
expect(data.user.name).toBe(testName);
|
||||
|
||||
// Verify user was created in database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
console.log('User created in DB:', user ? 'yes' : 'no');
|
||||
if (user) {
|
||||
console.log('User ID:', user.id);
|
||||
console.log('User role:', user.role);
|
||||
}
|
||||
expect(user).not.toBeNull();
|
||||
expect(user?.email).toBe(testEmail);
|
||||
expect(user?.role).toBe('player');
|
||||
});
|
||||
|
||||
test('2. Log in with test account via API', async ({ request }) => {
|
||||
console.log('Test 2 - testEmail:', testEmail);
|
||||
|
||||
// Check if user exists first
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
console.log('User exists for login:', user ? 'yes' : 'no');
|
||||
if (user) {
|
||||
console.log('User ID:', user.id);
|
||||
}
|
||||
|
||||
// Login via API
|
||||
const response = await request.post('http://localhost:3000/api/auth/sign-in/email', {
|
||||
data: {
|
||||
email: testEmail,
|
||||
password: testPassword
|
||||
},
|
||||
headers: {
|
||||
'Origin': 'http://localhost:3000'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Login API Response:', response.status(), await response.text());
|
||||
expect(response.ok()).toBeTruthy();
|
||||
const data = await response.json();
|
||||
expect(data.user.email).toBe(testEmail);
|
||||
expect(data.token).toBeDefined();
|
||||
});
|
||||
|
||||
test('3. Delete test account', async () => {
|
||||
// Delete via database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
|
||||
if (user) {
|
||||
await prisma.user.delete({ where: { id: user.id } });
|
||||
console.log(`Test user deleted: ${testEmail}`);
|
||||
}
|
||||
|
||||
// Verify user was deleted
|
||||
const deletedUser = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
expect(deletedUser).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Acceptance Test: Account Creation, Login, and Deletion (UI-based)
|
||||
*
|
||||
* This test demonstrates the full workflow using the UI:
|
||||
* 1. Create a test account via registration
|
||||
* 2. Log in using the authentication UI
|
||||
* 3. Delete the test account
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
// Generate unique test account credentials
|
||||
function getTestCredentials() {
|
||||
const timestamp = Date.now();
|
||||
return {
|
||||
email: `test-${timestamp}@example.com`,
|
||||
password: 'TestPassword123!',
|
||||
name: `Test User ${timestamp}`
|
||||
};
|
||||
}
|
||||
|
||||
test.describe.serial('Account Lifecycle Acceptance Test', () => {
|
||||
let testEmail: string;
|
||||
let testPassword: string;
|
||||
let testName: string;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
const credentials = getTestCredentials();
|
||||
testEmail = credentials.email;
|
||||
testPassword = credentials.password;
|
||||
testName = credentials.name;
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
// Clean up: delete test user if they still exist
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
if (user) {
|
||||
await prisma.user.delete({ where: { id: user.id } });
|
||||
console.log(`Cleaned up test user: ${testEmail}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Cleanup error:', error);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Test 1: Create test account via registration
|
||||
* Uses the unauthenticated project (no storage state)
|
||||
*/
|
||||
test('1. Create test account via registration', async ({ page }) => {
|
||||
// Navigate to registration page
|
||||
await page.goto('/auth/register');
|
||||
|
||||
// Wait for JavaScript to be ready
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Wait for the form to be visible and the submit button to be enabled
|
||||
await page.waitForSelector('form');
|
||||
await page.waitForSelector('button[type="submit"]:not([disabled])');
|
||||
|
||||
// Fill in registration form
|
||||
await page.fill('input[name="name"]', testName);
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
|
||||
// Submit the form
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for redirect to player profile (regular users are redirected to their profile)
|
||||
await page.waitForURL(/\/players\/\d+\/profile/, { timeout: 10000 });
|
||||
|
||||
// Wait a moment for the user to be saved to database
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Verify user was created in database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
expect(user).not.toBeNull();
|
||||
expect(user?.email).toBe(testEmail);
|
||||
expect(user?.role).toBe('player');
|
||||
});
|
||||
|
||||
/**
|
||||
* Test 2: Log in with test account
|
||||
* Uses the unauthenticated project (no storage state)
|
||||
*/
|
||||
test('2. Log in with test account', async ({ page }) => {
|
||||
// Navigate to login page
|
||||
await page.goto('/auth/login');
|
||||
|
||||
// Fill in login form
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
|
||||
// Submit the form
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for redirect to admin or player profile
|
||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||
|
||||
// Reload to ensure session is loaded from cookies
|
||||
await page.reload();
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Wait for logout button to appear
|
||||
await page.waitForSelector('text=Sign out', { timeout: 10000 });
|
||||
|
||||
// Check for user's email or name in the navigation
|
||||
const userEmail = await page.locator(`text=${testEmail}`).count();
|
||||
const userName = await page.locator(`text=${testName}`).count();
|
||||
const logoutButton = await page.locator('text=Sign out').count();
|
||||
|
||||
// At least one of these should be present if logged in
|
||||
expect(userEmail + userName + logoutButton).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
/**
|
||||
* Test 3: Delete test account
|
||||
* Uses the authenticated project (admin)
|
||||
*/
|
||||
test('3. Delete test account', async ({ page }) => {
|
||||
// For now, we'll delete via direct database access
|
||||
// In a real scenario, this would be done via an admin API endpoint
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
|
||||
if (user) {
|
||||
await prisma.user.delete({ where: { id: user.id } });
|
||||
console.log(`Test user deleted: ${testEmail}`);
|
||||
}
|
||||
|
||||
// Verify user was deleted
|
||||
const deletedUser = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
expect(deletedUser).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,398 @@
|
||||
/**
|
||||
* E2E Test: Elo Rating Updates
|
||||
*
|
||||
* Tests that Elo ratings are correctly updated when matches are added
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { scryptAsync } from '@noble/hashes/scrypt.js';
|
||||
import { hex } from '@better-auth/utils/hex';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
// Polyfill crypto for Node.js environment
|
||||
const crypto = globalThis.crypto || require('crypto').webcrypto;
|
||||
|
||||
test.describe('Elo Rating Updates', () => {
|
||||
test.beforeAll(async () => {
|
||||
// Clean up any existing test data
|
||||
// First delete matches that reference players
|
||||
await prisma.match.deleteMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ team1P1Id: { in: await getEloTestPlayerIds() } },
|
||||
{ team1P2Id: { in: await getEloTestPlayerIds() } },
|
||||
{ team2P1Id: { in: await getEloTestPlayerIds() } },
|
||||
{ team2P2Id: { in: await getEloTestPlayerIds() } },
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
// Then delete partnerships
|
||||
await prisma.partnershipStat.deleteMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ player1Id: { in: await getEloTestPlayerIds() } },
|
||||
{ player2Id: { in: await getEloTestPlayerIds() } },
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
// Finally delete players
|
||||
await prisma.player.deleteMany({
|
||||
where: {
|
||||
name: {
|
||||
startsWith: 'Elo Test'
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
// Clean up test data
|
||||
// First delete matches that reference players
|
||||
await prisma.match.deleteMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ team1P1Id: { in: await getEloTestPlayerIds() } },
|
||||
{ team1P2Id: { in: await getEloTestPlayerIds() } },
|
||||
{ team2P1Id: { in: await getEloTestPlayerIds() } },
|
||||
{ team2P2Id: { in: await getEloTestPlayerIds() } },
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
// Then delete partnerships
|
||||
await prisma.partnershipStat.deleteMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ player1Id: { in: await getEloTestPlayerIds() } },
|
||||
{ player2Id: { in: await getEloTestPlayerIds() } },
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
// Finally delete players
|
||||
await prisma.player.deleteMany({
|
||||
where: {
|
||||
name: {
|
||||
startsWith: 'Elo Test'
|
||||
}
|
||||
}
|
||||
});
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
async function getEloTestPlayerIds(): Promise<number[]> {
|
||||
const players = await prisma.player.findMany({
|
||||
where: {
|
||||
name: {
|
||||
startsWith: 'Elo Test'
|
||||
}
|
||||
},
|
||||
select: { id: true }
|
||||
});
|
||||
return players.map(p => p.id);
|
||||
}
|
||||
|
||||
test('Elo rating updates after match upload', async ({ page }) => {
|
||||
// Step 1: Create test players with known initial ratings
|
||||
const player1 = await prisma.player.create({
|
||||
data: {
|
||||
name: 'Elo Test Player 1',
|
||||
currentElo: 1500,
|
||||
gamesPlayed: 0,
|
||||
wins: 0,
|
||||
losses: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const player2 = await prisma.player.create({
|
||||
data: {
|
||||
name: 'Elo Test Player 2',
|
||||
currentElo: 1500,
|
||||
gamesPlayed: 0,
|
||||
wins: 0,
|
||||
losses: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const player3 = await prisma.player.create({
|
||||
data: {
|
||||
name: 'Elo Test Player 3',
|
||||
currentElo: 1500,
|
||||
gamesPlayed: 0,
|
||||
wins: 0,
|
||||
losses: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const player4 = await prisma.player.create({
|
||||
data: {
|
||||
name: 'Elo Test Player 4',
|
||||
currentElo: 1500,
|
||||
gamesPlayed: 0,
|
||||
wins: 0,
|
||||
losses: 0,
|
||||
},
|
||||
});
|
||||
|
||||
// Step 2: Use existing admin user from global setup
|
||||
// The global setup creates an admin user with email starting with 'setup-admin-'
|
||||
// We'll find that user and use it for the test
|
||||
const existingAdmin = await prisma.user.findFirst({
|
||||
where: {
|
||||
email: { startsWith: 'setup-admin-' },
|
||||
role: 'club_admin'
|
||||
},
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
|
||||
if (!existingAdmin) {
|
||||
throw new Error('No existing admin user found. Please run global setup first.');
|
||||
}
|
||||
|
||||
const adminEmail = existingAdmin.email;
|
||||
const adminPassword = 'AdminPassword123!'; // Password from global setup
|
||||
const adminUser = existingAdmin;
|
||||
|
||||
console.log('Using existing admin user:', adminEmail);
|
||||
console.log('Admin user ID:', adminUser.id);
|
||||
console.log('Admin user role:', adminUser.role);
|
||||
|
||||
// Create tournament owned by admin user
|
||||
console.log('Creating tournament with ownerId:', adminUser.id);
|
||||
const tournament = await prisma.event.create({
|
||||
data: {
|
||||
name: 'Elo Test Multi Tournament',
|
||||
eventType: 'tournament',
|
||||
status: 'planned',
|
||||
ownerId: adminUser.id,
|
||||
},
|
||||
});
|
||||
console.log('Tournament created with ID:', tournament.id);
|
||||
console.log('Tournament status:', tournament.status);
|
||||
|
||||
// Verify tournament was created and can be found
|
||||
const tournamentCheck = await prisma.event.findUnique({
|
||||
where: { id: tournament.id }
|
||||
});
|
||||
console.log('Tournament verified:', tournamentCheck ? 'yes' : 'no');
|
||||
console.log('Tournament owner ID:', tournamentCheck?.ownerId);
|
||||
console.log('Current user ID:', adminUser.id);
|
||||
console.log('Owner matches:', tournamentCheck?.ownerId === adminUser.id);
|
||||
|
||||
// Step 3: Use existing session from global setup
|
||||
// Navigate to admin page to check if we're already logged in
|
||||
// Set up console listener to catch server logs
|
||||
page.on('console', msg => {
|
||||
console.log('SERVER LOG:', msg.text());
|
||||
});
|
||||
|
||||
await page.goto('/admin');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Check if we're logged in
|
||||
const content = await page.content();
|
||||
const isLoggedIn = content.includes('Sign out');
|
||||
console.log('User is logged in:', isLoggedIn);
|
||||
console.log('Page title:', await page.title());
|
||||
console.log('Current URL:', page.url());
|
||||
|
||||
// Check if there's a login form
|
||||
const hasLoginForm = content.includes('Sign in to your account');
|
||||
console.log('Has login form:', hasLoginForm);
|
||||
|
||||
// If the URL is a player profile, we're logged in but as a regular user
|
||||
// In that case, we need to log out and log in as admin
|
||||
if (page.url().includes('/players/')) {
|
||||
console.log('User is logged in but redirected to player profile (not admin)');
|
||||
console.log('Logging out and logging in as admin...');
|
||||
await page.click('button:has-text("Sign out")');
|
||||
await page.waitForURL('/auth/login');
|
||||
await page.waitForLoadState('networkidle');
|
||||
}
|
||||
|
||||
if (!isLoggedIn || page.url().includes('/players/')) {
|
||||
// If not logged in or logged in as regular user, log in as admin
|
||||
console.log('Logging in as admin...');
|
||||
await page.goto('/auth/login');
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.fill('input[name="email"]', adminEmail);
|
||||
await page.fill('input[name="password"]', adminPassword);
|
||||
await page.click('button[type="submit"]');
|
||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||
await page.waitForLoadState('networkidle');
|
||||
}
|
||||
|
||||
// Verify tournament ownership
|
||||
const tournamentVerify = await prisma.event.findUnique({
|
||||
where: { id: tournament.id }
|
||||
});
|
||||
console.log('Tournament owner ID:', tournamentVerify?.ownerId);
|
||||
console.log('Current user ID:', adminUser.id);
|
||||
console.log('Owner matches:', tournamentVerify?.ownerId === adminUser.id);
|
||||
|
||||
// Navigate to match upload page
|
||||
await page.goto('/admin/matches/upload');
|
||||
|
||||
// Wait for page to load and tournaments to be fetched
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Wait for tournament dropdown to be ready
|
||||
await page.waitForSelector('select#tournament', { timeout: 5000 });
|
||||
|
||||
// Wait a bit for tournaments to load
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Select the tournament manually
|
||||
const tournamentSelect = await page.locator('select#tournament');
|
||||
console.log('Selecting tournament ID:', tournament.id);
|
||||
await tournamentSelect.selectOption({ value: tournament.id.toString() });
|
||||
|
||||
// Wait for React state to update
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
// Verify the selection
|
||||
const selectedTournament = await tournamentSelect.inputValue();
|
||||
console.log('Tournament selected in dropdown:', selectedTournament);
|
||||
console.log('Expected tournament ID:', tournament.id);
|
||||
|
||||
if (selectedTournament !== tournament.id.toString()) {
|
||||
console.log('WARNING: Tournament selection mismatch!');
|
||||
}
|
||||
|
||||
// Check if there's a permission error on the page
|
||||
const uploadContent = await page.content();
|
||||
if (uploadContent.includes('Insufficient permissions')) {
|
||||
console.log('ERROR: Permission error detected on page');
|
||||
console.log('Page URL:', page.url());
|
||||
// Take a screenshot for debugging
|
||||
await page.screenshot({ path: '/tmp/permission-error.png' });
|
||||
|
||||
// Check the navigation to see current user
|
||||
const navContent = await page.locator('nav').textContent();
|
||||
console.log('Navigation content:', navContent);
|
||||
}
|
||||
|
||||
// Create matches where player1/player2 win twice and player3/player4 lose twice
|
||||
const csvContent1 = `Event #,Round,Table,Seat 1,Seat 3,Odds Points,Seat 2,Seat 4,Evens Points,Winner
|
||||
${tournament.id},1,1,${player1.name},${player3.name},10,${player2.name},${player4.name},5,odds`;
|
||||
|
||||
const csvContent2 = `Event #,Round,Table,Seat 1,Seat 3,Odds Points,Seat 2,Seat 4,Evens Points,Winner
|
||||
${tournament.id},2,1,${player1.name},${player3.name},10,${player2.name},${player4.name},5,odds`;
|
||||
|
||||
// Upload first match through UI
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const tmpFile1 = path.join('/tmp', `elo-test-multi-1-${Date.now()}.csv`);
|
||||
fs.writeFileSync(tmpFile1, csvContent1);
|
||||
|
||||
// Wait for file input to be ready
|
||||
await page.waitForSelector('input[type="file"]', { timeout: 5000 });
|
||||
|
||||
// Upload the file
|
||||
await page.setInputFiles('input[type="file"]', tmpFile1);
|
||||
|
||||
// Wait for file to be selected
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
// Click submit button
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for upload to complete
|
||||
await page.waitForTimeout(3000);
|
||||
|
||||
// Check for any error messages
|
||||
const uploadContentAfter = await page.content();
|
||||
if (uploadContentAfter.includes('error') || uploadContentAfter.includes('Error')) {
|
||||
console.log('Upload page has error message');
|
||||
}
|
||||
|
||||
fs.unlinkSync(tmpFile1);
|
||||
|
||||
// Navigate back to upload page for second match
|
||||
await page.goto('/admin/matches/upload');
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Re-select the tournament for the second upload
|
||||
await page.waitForSelector('select#tournament', { timeout: 5000 });
|
||||
await page.waitForTimeout(1000); // Wait for tournaments to load
|
||||
|
||||
const tournamentSelect2 = await page.locator('select#tournament');
|
||||
const currentSelection = await tournamentSelect2.inputValue();
|
||||
|
||||
// If tournament is not selected, select it manually
|
||||
if (!currentSelection || currentSelection !== tournament.id.toString()) {
|
||||
console.log('Selecting tournament for second upload:', tournament.id);
|
||||
await tournamentSelect2.selectOption({ value: tournament.id.toString() });
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
|
||||
// Upload second match through UI
|
||||
const tmpFile2 = path.join('/tmp', `elo-test-multi-2-${Date.now()}.csv`);
|
||||
fs.writeFileSync(tmpFile2, csvContent2);
|
||||
|
||||
await page.setInputFiles('input[type="file"]', tmpFile2);
|
||||
await page.waitForTimeout(500);
|
||||
await page.click('button[type="submit"]');
|
||||
await page.waitForTimeout(2000);
|
||||
fs.unlinkSync(tmpFile2);
|
||||
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Verify ratings after multiple matches
|
||||
const updatedPlayer1 = await prisma.player.findUnique({
|
||||
where: { id: player1.id }
|
||||
});
|
||||
|
||||
const updatedPlayer4 = await prisma.player.findUnique({
|
||||
where: { id: player4.id }
|
||||
});
|
||||
|
||||
// Player 1 should have higher rating after 2 wins
|
||||
// With K=32, each win gives ~8 Elo points, so 2 wins = ~16 Elo
|
||||
// Expected: 1500 + 16 = 1516
|
||||
expect(updatedPlayer1?.currentElo).toBeGreaterThan(1500);
|
||||
expect(updatedPlayer1?.currentElo).toBeLessThanOrEqual(1520);
|
||||
expect(updatedPlayer1?.gamesPlayed).toBe(2);
|
||||
expect(updatedPlayer1?.wins).toBe(2);
|
||||
|
||||
// Player 4 should have lower rating after 2 losses
|
||||
// Expected: 1500 - 16 = 1484
|
||||
expect(updatedPlayer4?.currentElo).toBeLessThan(1500);
|
||||
expect(updatedPlayer4?.currentElo).toBeGreaterThanOrEqual(1480);
|
||||
expect(updatedPlayer4?.gamesPlayed).toBe(2);
|
||||
expect(updatedPlayer4?.losses).toBe(2);
|
||||
});
|
||||
|
||||
test('Elo ratings are visible on player profile', async ({ page }) => {
|
||||
// Create a test player
|
||||
const player = await prisma.player.create({
|
||||
data: {
|
||||
name: 'Elo Test Profile Player',
|
||||
currentElo: 1750,
|
||||
gamesPlayed: 50,
|
||||
wins: 30,
|
||||
losses: 20,
|
||||
},
|
||||
});
|
||||
|
||||
// Navigate to player profile
|
||||
await page.goto(`/players/${player.id}/profile`);
|
||||
|
||||
// Wait for page to load
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Verify rating is displayed (from player.currentElo)
|
||||
await expect(page.locator('text=1750')).toBeVisible();
|
||||
|
||||
// Total games shown on profile is calculated from partnership stats
|
||||
// Since we haven't added any matches yet, it should show 0 or N/A for best partner
|
||||
// Just verify the page loads with the Elo rating
|
||||
await expect(page.locator('text=Current Elo')).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* Epic 1: Authentication & User Management
|
||||
* Acceptance Test: User Logout
|
||||
*
|
||||
* User Story: As a logged-in user, I want to log out so that I can secure my account
|
||||
*
|
||||
* Acceptance Criteria:
|
||||
* - Logout button in navigation
|
||||
* - Session cleared on logout
|
||||
* - Redirect to home page
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
function getTestCredentials() {
|
||||
const timestamp = Date.now();
|
||||
return {
|
||||
email: `logout-test-${timestamp}@example.com`,
|
||||
password: 'TestPassword123!',
|
||||
name: `Logout Test User ${timestamp}`
|
||||
};
|
||||
}
|
||||
|
||||
test.describe.serial('Epic 1: User Logout', () => {
|
||||
let testEmail: string;
|
||||
let testPassword: string;
|
||||
let testName: string;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
const credentials = getTestCredentials();
|
||||
testEmail = credentials.email;
|
||||
testPassword = credentials.password;
|
||||
testName = credentials.name;
|
||||
|
||||
// Create test user via API with proper origin header
|
||||
const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Origin': 'http://localhost:3000',
|
||||
'X-Requested-With': 'XMLHttpRequest'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: testEmail,
|
||||
password: testPassword,
|
||||
name: testName
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
console.error('Failed to create user:', response.status, errorText);
|
||||
throw new Error(`Failed to create user: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log('User created via API:', data.user?.email);
|
||||
|
||||
// Wait for the database hook to complete (creating Player record)
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
|
||||
// Verify the user was created in the database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new Error(`User ${testEmail} was not created in database`);
|
||||
}
|
||||
|
||||
if (!user.playerId) {
|
||||
throw new Error(`User ${testEmail} does not have a playerId (database hook may not have run)`);
|
||||
}
|
||||
|
||||
console.log(`User ${testEmail} created with playerId: ${user.playerId}`);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
if (user) {
|
||||
await prisma.user.delete({ where: { id: user.id } });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Cleanup error:', error);
|
||||
}
|
||||
});
|
||||
|
||||
test('Logout button appears in navigation when logged in', async ({ page }) => {
|
||||
// Login first
|
||||
await page.goto('http://localhost:3000/auth/login');
|
||||
|
||||
// Wait for JavaScript to be ready
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.waitForSelector('form');
|
||||
await page.waitForSelector('button[type="submit"]:not([disabled])');
|
||||
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
|
||||
// Wait for redirect to admin or player profile after clicking submit
|
||||
const [response] = await Promise.all([
|
||||
page.waitForResponse(response =>
|
||||
response.url().includes('/api/auth/sign-in/email') && response.status() === 200,
|
||||
{ timeout: 10000 }
|
||||
),
|
||||
page.click('button[type="submit"]')
|
||||
]);
|
||||
|
||||
console.log('Login response:', response.status());
|
||||
|
||||
// Wait for redirect
|
||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||
|
||||
console.log('After login URL:', page.url());
|
||||
|
||||
// Check cookies
|
||||
const cookies = await page.context().cookies();
|
||||
console.log('Cookies after login:', cookies.map(c => `${c.name}=${c.value.substring(0, 20)}...`).join(', '));
|
||||
|
||||
// Check if better-auth.session_token exists
|
||||
const sessionCookie = cookies.find(c => c.name.includes('session'));
|
||||
console.log('Session cookie:', sessionCookie ? `${sessionCookie.name}=${sessionCookie.value.substring(0, 20)}...` : 'NOT FOUND');
|
||||
|
||||
// Navigate to home page to check navigation (session should persist)
|
||||
// Use reload to ensure session is read from cookies
|
||||
await page.reload();
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Wait a moment for the navigation component to update
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Debug: Check what's on the page
|
||||
const pageContent = await page.content();
|
||||
console.log('Page content contains Sign out:', pageContent.includes('Sign out'));
|
||||
console.log('Page content contains Sign in:', pageContent.includes('Sign in'));
|
||||
console.log('Page content length:', pageContent.length);
|
||||
console.log('Current URL:', page.url());
|
||||
console.log('Page HTML snippet:', pageContent.substring(0, 500));
|
||||
|
||||
// Wait for the Navigation component to load and render
|
||||
await page.waitForSelector('nav', { timeout: 5000 });
|
||||
|
||||
// Wait for the session to be loaded (check for logout button directly)
|
||||
await page.waitForSelector('text=Sign out', { timeout: 10000 });
|
||||
|
||||
// Check for logout button
|
||||
const logoutButton = await page.locator('text=Sign out').count();
|
||||
console.log('Logout button count:', logoutButton);
|
||||
expect(logoutButton).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('Logout clears session and redirects to home', async ({ page }) => {
|
||||
// Login first
|
||||
await page.goto('http://localhost:3000/auth/login');
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for redirect to admin or player profile (indicates successful login)
|
||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||
|
||||
// Navigate to home using reload to ensure session is loaded
|
||||
await page.reload();
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Wait for logout button to appear
|
||||
await page.waitForSelector('text=Sign out', { timeout: 10000 });
|
||||
|
||||
// Click logout
|
||||
await page.click('text=Sign out');
|
||||
|
||||
// Wait for redirect to login page
|
||||
await page.waitForURL('**/auth/login**', { timeout: 10000 });
|
||||
});
|
||||
|
||||
test('After logout, protected pages redirect to login', async ({ page }) => {
|
||||
// Login first
|
||||
await page.goto('http://localhost:3000/auth/login');
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for redirect to admin or player profile (indicates successful login)
|
||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||
|
||||
// Navigate to home using reload to ensure session is loaded
|
||||
await page.reload();
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Wait for logout button to appear
|
||||
await page.waitForSelector('text=Sign out', { timeout: 10000 });
|
||||
|
||||
// Logout
|
||||
await page.click('text=Sign out');
|
||||
await page.waitForURL('**/auth/login**', { timeout: 10000 });
|
||||
|
||||
// Try to access admin page
|
||||
await page.goto('http://localhost:3000/admin');
|
||||
|
||||
// Should redirect to login
|
||||
await expect(page).toHaveURL(/.*auth\/login.*/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Epic 1: Authentication & User Management
|
||||
* Acceptance Test: Password Reset
|
||||
*
|
||||
* User Story: As a user who forgot my password, I want to reset it so that I can regain access
|
||||
*
|
||||
* Acceptance Criteria:
|
||||
* - "Forgot password" link on login page
|
||||
* - Email input for reset request
|
||||
* - Unique token generation (expires in 1 hour)
|
||||
* - Email with reset link
|
||||
* - Password update form with validation
|
||||
*
|
||||
* NOTE: Password reset is not yet implemented in the application.
|
||||
* This test verifies the UI exists but the functionality is a placeholder.
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe.skip('Epic 1: Password Reset (Not Implemented)', () => {
|
||||
test('Forgot password link exists on login page', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/auth/login');
|
||||
|
||||
// Check for forgot password link
|
||||
await expect(page.locator('a[href*="password-reset"]')).toBeVisible();
|
||||
await expect(page.locator('a[href*="password-reset"]')).toContainText('Forgot');
|
||||
});
|
||||
|
||||
test('Password reset page exists but is not functional', async ({ page }) => {
|
||||
// Note: The link exists but the page may not be implemented
|
||||
// This test documents the current state
|
||||
await page.goto('http://localhost:3000/auth/password-reset');
|
||||
|
||||
// Check if page loads (may show "not implemented" message)
|
||||
await expect(page.locator('body')).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Epic 1: Authentication & User Management
|
||||
* Acceptance Test: User Registration
|
||||
*
|
||||
* User Story: As a new user, I want to register for an account so that I can participate in tournaments and track my games
|
||||
*
|
||||
* Acceptance Criteria:
|
||||
* - Registration form with name, email, password, password confirmation
|
||||
* - Email validation and uniqueness check
|
||||
* - Password strength requirements (8+ chars, uppercase, lowercase, number, special char)
|
||||
* - Account confirmation via email (placeholder)
|
||||
* - Auto-create player profile upon registration
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
function getTestCredentials() {
|
||||
const timestamp = Date.now();
|
||||
return {
|
||||
email: `register-test-${timestamp}@example.com`,
|
||||
password: 'TestPassword123!',
|
||||
name: `Register Test User ${timestamp}`
|
||||
};
|
||||
}
|
||||
|
||||
test.describe.serial('Epic 1: User Registration', () => {
|
||||
let testEmail: string;
|
||||
let testPassword: string;
|
||||
let testName: string;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
const credentials = getTestCredentials();
|
||||
testEmail = credentials.email;
|
||||
testPassword = credentials.password;
|
||||
testName = credentials.name;
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
if (user) {
|
||||
await prisma.user.delete({ where: { id: user.id } });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Cleanup error:', error);
|
||||
}
|
||||
});
|
||||
|
||||
test('Registration page exists and loads', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/auth/register');
|
||||
|
||||
// Check for registration form elements
|
||||
await expect(page.locator('input[name="name"]')).toBeVisible();
|
||||
await expect(page.locator('input[name="email"]')).toBeVisible();
|
||||
await expect(page.locator('input[name="password"]')).toBeVisible();
|
||||
await expect(page.locator('button[type="submit"]')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Registration with valid data creates account', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/auth/register');
|
||||
|
||||
// Wait for JavaScript to be ready
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.waitForSelector('form');
|
||||
await page.waitForSelector('button[type="submit"]:not([disabled])');
|
||||
|
||||
// Fill registration form
|
||||
await page.fill('input[name="name"]', testName);
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
|
||||
// Log console messages and network requests to see what's happening
|
||||
page.on('console', msg => console.log('PAGE CONSOLE:', msg.text()));
|
||||
page.on('request', request => {
|
||||
console.log('>> REQ:', request.method(), request.url().substring(0, 100));
|
||||
});
|
||||
page.on('response', response => {
|
||||
console.log('<< RES:', response.status(), response.url().substring(0, 100));
|
||||
});
|
||||
page.on('requestfailed', request => {
|
||||
console.log('>> REQ FAILED:', request.url());
|
||||
});
|
||||
page.on('pageerror', error => {
|
||||
console.log('PAGE ERROR:', error.message);
|
||||
});
|
||||
|
||||
// Wait a moment for JavaScript to be ready
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Submit form
|
||||
const [response] = await Promise.all([
|
||||
page.waitForResponse(response =>
|
||||
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
||||
{ timeout: 10000 }
|
||||
),
|
||||
page.click('button[type="submit"]')
|
||||
]);
|
||||
|
||||
console.log('Sign-up API response:', response.status(), response.url());
|
||||
|
||||
// Wait for redirect to admin or player profile
|
||||
try {
|
||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||
console.log('Redirected successfully to:', page.url());
|
||||
} catch (e) {
|
||||
console.log('Redirect failed. Current URL:', page.url());
|
||||
console.log('Page title:', await page.title());
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Verify user in database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
expect(user).not.toBeNull();
|
||||
expect(user?.email).toBe(testEmail);
|
||||
expect(user?.role).toBe('player');
|
||||
});
|
||||
|
||||
test('Registration with duplicate email fails', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/auth/register');
|
||||
|
||||
// Fill registration form with existing email
|
||||
await page.fill('input[name="name"]', testName);
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
|
||||
// Submit form
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Should show error message
|
||||
// Better Auth may return a success response with requireEmailVerification enabled
|
||||
// so we check if we're still on the registration page or redirected to an error page
|
||||
try {
|
||||
await page.waitForURL('**/auth/register**', { timeout: 5000 });
|
||||
// If we're still on the registration page, check for error message
|
||||
const content = await page.content();
|
||||
expect(content).toContain('error');
|
||||
} catch (e) {
|
||||
// If redirected successfully, that's fine
|
||||
console.log('Registration redirected to:', page.url());
|
||||
}
|
||||
});
|
||||
|
||||
test('Registration with weak password fails', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/auth/register');
|
||||
|
||||
// Fill registration form with weak password
|
||||
await page.fill('input[name="name"]', testName);
|
||||
await page.fill('input[name="email"]', `weak-${Date.now()}@example.com`);
|
||||
await page.fill('input[name="password"]', 'weak'); // Too short
|
||||
|
||||
// Submit form
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Should show validation error
|
||||
await expect(page.locator('input[name="password"]')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Auto-created player profile is linked to user', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/auth/register');
|
||||
|
||||
const profileEmail = `profile-${Date.now()}@example.com`;
|
||||
const profileName = 'Profile Test User';
|
||||
|
||||
await page.fill('input[name="name"]', profileName);
|
||||
await page.fill('input[name="email"]', profileEmail);
|
||||
await page.fill('input[name="password"]', 'ProfilePass123!');
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||
|
||||
// Verify user and player are linked
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: profileEmail },
|
||||
include: { player: true }
|
||||
});
|
||||
|
||||
expect(user).not.toBeNull();
|
||||
expect(user?.player).not.toBeNull();
|
||||
// Player name is now dynamic with timestamp and random ID
|
||||
expect(user?.player?.name).toMatch(new RegExp(`^${profileName}-\\d+-[a-z0-9]+$`));
|
||||
|
||||
// Cleanup
|
||||
if (user?.id) {
|
||||
await prisma.user.delete({ where: { id: user.id } });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Epic 3: Rankings & Public Data
|
||||
* Acceptance Test: Player Rankings Page
|
||||
*
|
||||
* User Story: As a visitor, I want to view player rankings so that I can see top players
|
||||
*
|
||||
* Acceptance Criteria:
|
||||
* - Sortable rankings table
|
||||
* - Columns: Rank, Name, Elo, Win Rate, Games Played
|
||||
* - Search/filter functionality
|
||||
* - Pagination
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('Epic 3: Rankings Page', () => {
|
||||
test('Rankings page loads and displays rankings table', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/rankings');
|
||||
|
||||
// Check page title or heading
|
||||
await expect(page.locator('h1, h2')).toContainText(/rankings?/i);
|
||||
|
||||
// Check for rankings table
|
||||
await expect(page.locator('table')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Rankings table displays player columns', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/rankings');
|
||||
|
||||
// Check for expected column headers
|
||||
const table = page.locator('table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
// Check for column headers (may vary based on implementation)
|
||||
const headerCount = await page.locator('th').count();
|
||||
expect(headerCount).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('Rankings page is publicly accessible (no login required)', async ({ page }) => {
|
||||
// Navigate directly to rankings without logging in
|
||||
await page.goto('http://localhost:3000/rankings');
|
||||
|
||||
// Page should load without redirecting to login
|
||||
await expect(page).toHaveURL(/.*rankings.*/);
|
||||
await expect(page.locator('body')).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* Epic 4: Tournament Management
|
||||
* Acceptance Test: Tournament Creation
|
||||
*
|
||||
* User Story: As a tournament admin, I want to create a new tournament so that I can organize events
|
||||
*
|
||||
* Acceptance Criteria:
|
||||
* - Tournament creation form
|
||||
* - Fields: Name, Format (round-robin, single elim, double elim, Swiss), Date, Status
|
||||
* - Default settings for each format
|
||||
* - Validation for required fields
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
function getTestCredentials() {
|
||||
const timestamp = Date.now();
|
||||
return {
|
||||
email: `admin-${timestamp}@example.com`,
|
||||
password: 'AdminPassword123!',
|
||||
name: `Admin User ${timestamp}`
|
||||
};
|
||||
}
|
||||
|
||||
test.describe.serial('Epic 4: Tournament Creation', () => {
|
||||
let testEmail: string;
|
||||
let testPassword: string;
|
||||
let testName: string;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
const credentials = getTestCredentials();
|
||||
testEmail = credentials.email;
|
||||
testPassword = credentials.password;
|
||||
testName = credentials.name;
|
||||
|
||||
// Create admin user via API
|
||||
const response = await fetch('http://localhost:3000/api/auth/sign-up/email', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Origin': 'http://localhost:3000'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
email: testEmail,
|
||||
password: testPassword,
|
||||
name: testName
|
||||
})
|
||||
});
|
||||
|
||||
console.log('Tournament test user creation response:', response.status);
|
||||
const data = await response.json();
|
||||
console.log('Tournament test user data:', data);
|
||||
|
||||
// Update user to club_admin role
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
console.log('Found user for tournament test:', user ? 'yes' : 'no');
|
||||
if (user) {
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { role: 'club_admin' }
|
||||
});
|
||||
console.log('Updated user role to club_admin');
|
||||
}
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
try {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: testEmail }
|
||||
});
|
||||
if (user) {
|
||||
await prisma.user.delete({ where: { id: user.id } });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Cleanup error:', error);
|
||||
}
|
||||
});
|
||||
|
||||
test('Tournament creation page exists and loads', async ({ page }) => {
|
||||
// Login first
|
||||
await page.goto('http://localhost:3000/auth/login');
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for redirect to admin or player profile (indicates successful login)
|
||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||
|
||||
// Navigate to new tournament page
|
||||
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||
|
||||
// Check for form
|
||||
await expect(page.locator('form')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Tournament form has required fields', async ({ page }) => {
|
||||
// Login first
|
||||
await page.goto('http://localhost:3000/auth/login');
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for redirect to admin or player profile (indicates successful login)
|
||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||
|
||||
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||
|
||||
// Check for required fields
|
||||
await expect(page.locator('input[name="name"]')).toBeVisible();
|
||||
await expect(page.locator('select[name="format"]')).toBeVisible();
|
||||
await expect(page.locator('button[type="submit"]')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Create tournament with valid data', async ({ page }) => {
|
||||
// Login first
|
||||
await page.goto('http://localhost:3000/auth/login');
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for redirect to admin or player profile (indicates successful login)
|
||||
await page.waitForURL(/\/(admin|players)/, { timeout: 10000 });
|
||||
|
||||
// Navigate to new tournament page
|
||||
await page.goto('http://localhost:3000/admin/tournaments/new');
|
||||
|
||||
const tournamentName = `Test Tournament ${Date.now()}`;
|
||||
|
||||
// Fill form
|
||||
await page.fill('input[name="name"]', tournamentName);
|
||||
await page.selectOption('select[name="format"]', 'round_robin');
|
||||
|
||||
// Submit form
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for redirect to tournament list
|
||||
await page.waitForURL('**/admin/tournaments**', { timeout: 10000 });
|
||||
|
||||
// Verify tournament was created in database
|
||||
const tournament = await prisma.event.findFirst({
|
||||
where: { name: tournamentName }
|
||||
});
|
||||
expect(tournament).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* Global setup for Playwright tests
|
||||
* Creates test users and saves authentication state
|
||||
*/
|
||||
|
||||
import { chromium, type FullConfig } from '@playwright/test';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const authFile = 'playwright/.auth/user.json';
|
||||
const adminAuthFile = 'playwright/.auth/admin.json';
|
||||
|
||||
export default async function globalSetup(config: FullConfig) {
|
||||
const baseURL = config.projects[0]?.use?.baseURL || 'http://localhost:3000';
|
||||
|
||||
const browser = await chromium.launch();
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
// Log all responses for debugging
|
||||
page.on('response', response => {
|
||||
if (response.url().includes('/api/auth')) {
|
||||
console.log('API Response:', response.status(), response.url());
|
||||
}
|
||||
});
|
||||
|
||||
// Generate unique test credentials
|
||||
const timestamp = Date.now();
|
||||
const testEmail = `setup-user-${timestamp}@example.com`;
|
||||
const testPassword = 'TestPassword123!';
|
||||
const testName = 'Setup User';
|
||||
|
||||
try {
|
||||
// Navigate to registration page
|
||||
console.log('Navigating to registration page...');
|
||||
await page.goto(`${baseURL}/auth/register`);
|
||||
|
||||
// Fill in registration form
|
||||
await page.fill('input[name="name"]', testName);
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
|
||||
// Submit the form
|
||||
console.log('Submitting registration form...');
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for the sign-up API call to complete
|
||||
console.log('Waiting for sign-up API call...');
|
||||
try {
|
||||
await page.waitForResponse(response =>
|
||||
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
||||
{ timeout: 10000 }
|
||||
);
|
||||
console.log('Sign-up API call successful');
|
||||
} catch (e) {
|
||||
console.log('Sign-up API call failed or timed out');
|
||||
}
|
||||
|
||||
// Wait a bit for session to be established
|
||||
console.log('Waiting for session establishment...');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Check if we're already authenticated
|
||||
const currentUrl = page.url();
|
||||
console.log('Current URL after registration:', currentUrl);
|
||||
|
||||
// Save the authentication state
|
||||
await context.storageState({ path: authFile });
|
||||
|
||||
console.log(`Created and authenticated test user: ${testEmail}`);
|
||||
|
||||
// Now create admin user
|
||||
const adminTimestamp = timestamp + 1;
|
||||
const adminEmail = `setup-admin-${adminTimestamp}@example.com`;
|
||||
const adminPassword = 'AdminPassword123!';
|
||||
const adminName = 'Setup Admin';
|
||||
|
||||
// Navigate to registration page again
|
||||
console.log('Navigating to registration page for admin...');
|
||||
await page.goto(`${baseURL}/auth/register`);
|
||||
|
||||
// Fill in registration form
|
||||
await page.fill('input[name="name"]', adminName);
|
||||
await page.fill('input[name="email"]', adminEmail);
|
||||
await page.fill('input[name="password"]', adminPassword);
|
||||
|
||||
// Submit the form
|
||||
console.log('Submitting admin registration form...');
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for the sign-up API call to complete
|
||||
console.log('Waiting for admin sign-up API call...');
|
||||
try {
|
||||
await page.waitForResponse(response =>
|
||||
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
||||
{ timeout: 10000 }
|
||||
);
|
||||
console.log('Admin sign-up API call successful');
|
||||
} catch (e) {
|
||||
console.log('Admin sign-up API call failed or timed out');
|
||||
}
|
||||
|
||||
// Wait a bit for session to be established
|
||||
console.log('Waiting for admin session establishment...');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Update user role to admin via database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: adminEmail }
|
||||
});
|
||||
|
||||
if (user) {
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { role: 'club_admin' }
|
||||
});
|
||||
console.log('Updated user role to club_admin');
|
||||
}
|
||||
|
||||
// Navigate to admin page to refresh session
|
||||
console.log('Navigating to admin page for admin user...');
|
||||
await page.goto(`${baseURL}/admin`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
console.log('Admin page loaded:', page.url());
|
||||
|
||||
// Wait a bit to ensure session is refreshed
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Refresh the page to force session reload
|
||||
await page.reload();
|
||||
await page.waitForLoadState('networkidle');
|
||||
console.log('Page reloaded');
|
||||
|
||||
// Save the authentication state
|
||||
await context.storageState({ path: adminAuthFile });
|
||||
|
||||
console.log(`Created and authenticated admin user: ${adminEmail}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Global setup error:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
// Return teardown function
|
||||
return async () => {
|
||||
// Clean up test users
|
||||
try {
|
||||
await prisma.user.deleteMany({
|
||||
where: {
|
||||
email: {
|
||||
startsWith: 'setup-'
|
||||
}
|
||||
}
|
||||
});
|
||||
console.log('Cleaned up test users');
|
||||
} catch (error) {
|
||||
console.error('Error cleaning up test users:', error);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
test.describe('Home Page', () => {
|
||||
test('should display top 10 players', async ({ page }) => {
|
||||
// Create some test players with unique names and very high Elo to ensure they're in top 10
|
||||
const timestamp = Date.now()
|
||||
const players = []
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const player = await prisma.player.create({
|
||||
data: {
|
||||
name: `Home Test Player ${timestamp} ${i + 1}`,
|
||||
currentElo: 2000 - i * 10, // Very high Elo to ensure they're in top 10
|
||||
gamesPlayed: 10 + i,
|
||||
wins: 5 + Math.floor(i / 2),
|
||||
losses: 5 + Math.ceil(i / 2),
|
||||
},
|
||||
})
|
||||
players.push(player)
|
||||
}
|
||||
|
||||
// Navigate to home page
|
||||
await page.goto('/')
|
||||
|
||||
// Check that the page loads
|
||||
await expect(page.locator('text=Top 10 Players')).toBeVisible()
|
||||
|
||||
// Check that at least one of our test players is displayed
|
||||
// Use a more specific locator to avoid multiple matches
|
||||
await expect(
|
||||
page.locator(`a:has-text("Home Test Player ${timestamp} 1")`)
|
||||
).toBeVisible()
|
||||
|
||||
// Clean up
|
||||
for (const player of players) {
|
||||
await prisma.player.delete({ where: { id: player.id } })
|
||||
}
|
||||
})
|
||||
|
||||
test('should display club president', async ({ page }) => {
|
||||
const timestamp = Date.now()
|
||||
// Create a club admin user
|
||||
const clubAdmin = await prisma.user.create({
|
||||
data: {
|
||||
email: `president-${timestamp}@example.com`,
|
||||
name: `Club President ${timestamp}`,
|
||||
role: 'club_admin',
|
||||
},
|
||||
})
|
||||
|
||||
// Navigate to home page
|
||||
await page.goto('/')
|
||||
|
||||
// Check that the club president section is visible
|
||||
await expect(page.locator('text=Club President')).toBeVisible()
|
||||
|
||||
// Clean up
|
||||
await prisma.user.delete({ where: { id: clubAdmin.id } })
|
||||
})
|
||||
|
||||
test('should display most recent tournament', async ({ page }) => {
|
||||
const timestamp = Date.now()
|
||||
// Create a tournament with a future date to ensure it's the most recent
|
||||
const tournament = await prisma.event.create({
|
||||
data: {
|
||||
name: `Recent Tournament ${timestamp}`,
|
||||
eventType: 'tournament',
|
||||
eventDate: new Date(Date.now() + 86400000), // Tomorrow
|
||||
status: 'completed',
|
||||
},
|
||||
})
|
||||
|
||||
// Create players for the match
|
||||
const player1 = await prisma.player.create({
|
||||
data: { name: `Home Match Player 1 ${timestamp}`, currentElo: 1500 },
|
||||
})
|
||||
const player2 = await prisma.player.create({
|
||||
data: { name: `Home Match Player 2 ${timestamp}`, currentElo: 1480 },
|
||||
})
|
||||
const player3 = await prisma.player.create({
|
||||
data: { name: `Home Match Player 3 ${timestamp}`, currentElo: 1450 },
|
||||
})
|
||||
const player4 = await prisma.player.create({
|
||||
data: { name: `Home Match Player 4 ${timestamp}`, currentElo: 1420 },
|
||||
})
|
||||
|
||||
// Create a match in the tournament
|
||||
await prisma.match.create({
|
||||
data: {
|
||||
eventId: tournament.id,
|
||||
team1P1Id: player1.id,
|
||||
team1P2Id: player2.id,
|
||||
team2P1Id: player3.id,
|
||||
team2P2Id: player4.id,
|
||||
team1Score: 10,
|
||||
team2Score: 5,
|
||||
status: 'completed',
|
||||
playedAt: new Date(),
|
||||
},
|
||||
})
|
||||
|
||||
// Navigate to home page
|
||||
await page.goto('/')
|
||||
|
||||
// Check that the tournament section is visible
|
||||
await expect(page.locator('text=Most Recent Tournament')).toBeVisible()
|
||||
await expect(page.locator(`text=Recent Tournament ${timestamp}`)).toBeVisible()
|
||||
|
||||
// Clean up
|
||||
await prisma.match.deleteMany({ where: { eventId: tournament.id } })
|
||||
await prisma.event.delete({ where: { id: tournament.id } })
|
||||
await prisma.player.deleteMany({
|
||||
where: { id: { in: [player1.id, player2.id, player3.id, player4.id] } },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* Unit Tests: Elo Rating System
|
||||
*
|
||||
* Tests the mathematical correctness of Elo calculations and rating updates
|
||||
*/
|
||||
|
||||
import { describe, test, expect } from 'vitest';
|
||||
import { calculateEloChange, calculateExpectedScore, calculateTeamElo } from '@/lib/elo-utils';
|
||||
|
||||
describe('Elo Rating System', () => {
|
||||
const K_FACTOR = 32;
|
||||
|
||||
describe('calculateExpectedScore', () => {
|
||||
test('should calculate expected score for equal ratings', () => {
|
||||
const ratingA = 1500;
|
||||
const ratingB = 1500;
|
||||
const expected = calculateExpectedScore(ratingA, ratingB);
|
||||
|
||||
// Equal ratings should result in 0.5 expected score
|
||||
expect(expected).toBeCloseTo(0.5, 4);
|
||||
});
|
||||
|
||||
test('should calculate expected score when A is stronger', () => {
|
||||
const ratingA = 1600;
|
||||
const ratingB = 1500;
|
||||
const expected = calculateExpectedScore(ratingA, ratingB);
|
||||
|
||||
// Higher rated player should have higher expected score
|
||||
expect(expected).toBeGreaterThan(0.5);
|
||||
expect(expected).toBeLessThan(1);
|
||||
});
|
||||
|
||||
test('should calculate expected score when B is stronger', () => {
|
||||
const ratingA = 1500;
|
||||
const ratingB = 1600;
|
||||
const expected = calculateExpectedScore(ratingA, ratingB);
|
||||
|
||||
// Lower rated player should have lower expected score
|
||||
expect(expected).toBeLessThan(0.5);
|
||||
expect(expected).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('should handle large rating differences', () => {
|
||||
const ratingA = 2000;
|
||||
const ratingB = 1000;
|
||||
const expected = calculateExpectedScore(ratingA, ratingB);
|
||||
|
||||
// Much higher rated player should have very high expected score
|
||||
expect(expected).toBeGreaterThan(0.95);
|
||||
});
|
||||
});
|
||||
|
||||
describe('calculateEloChange', () => {
|
||||
test('should return positive change for win against equal opponent', () => {
|
||||
const rating = 1500;
|
||||
const opponentRating = 1500;
|
||||
const actualScore = 1; // Win
|
||||
|
||||
const change = calculateEloChange(rating, opponentRating, actualScore, K_FACTOR);
|
||||
|
||||
expect(change).toBeGreaterThan(0);
|
||||
// For equal opponents, expected = 0.5, so change = K_FACTOR * (1 - 0.5) = K_FACTOR / 2
|
||||
expect(change).toBeCloseTo(K_FACTOR / 2, 0);
|
||||
});
|
||||
|
||||
test('should return negative change for loss against equal opponent', () => {
|
||||
const rating = 1500;
|
||||
const opponentRating = 1500;
|
||||
const actualScore = 0; // Loss
|
||||
|
||||
const change = calculateEloChange(rating, opponentRating, actualScore, K_FACTOR);
|
||||
|
||||
expect(change).toBeLessThan(0);
|
||||
// For equal opponents, expected = 0.5, so change = K_FACTOR * (0 - 0.5) = -K_FACTOR / 2
|
||||
expect(change).toBeCloseTo(-K_FACTOR / 2, 0);
|
||||
});
|
||||
|
||||
test('should return zero change for draw against equal opponent', () => {
|
||||
const rating = 1500;
|
||||
const opponentRating = 1500;
|
||||
const actualScore = 0.5; // Draw
|
||||
|
||||
const change = calculateEloChange(rating, opponentRating, actualScore, K_FACTOR);
|
||||
|
||||
expect(change).toBeCloseTo(0, 1);
|
||||
});
|
||||
|
||||
test('should return larger positive change for win against stronger opponent', () => {
|
||||
const rating = 1500;
|
||||
const opponentRating = 1800; // Stronger
|
||||
const actualScore = 1; // Win (upset)
|
||||
|
||||
const change = calculateEloChange(rating, opponentRating, actualScore, K_FACTOR);
|
||||
|
||||
// Should gain more than K_FACTOR / 2 for upset win (since expected score is very low)
|
||||
expect(change).toBeGreaterThan(K_FACTOR / 2);
|
||||
});
|
||||
|
||||
test('should return larger negative change for loss against weaker opponent', () => {
|
||||
const rating = 1800;
|
||||
const opponentRating = 1500; // Weaker
|
||||
const actualScore = 0; // Loss (upset)
|
||||
|
||||
const change = calculateEloChange(rating, opponentRating, actualScore, K_FACTOR);
|
||||
|
||||
// Should lose more than K_FACTOR / 2 for upset loss (since expected score is very high)
|
||||
expect(change).toBeLessThan(-K_FACTOR / 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('calculateTeamElo', () => {
|
||||
test('should average team member ratings', () => {
|
||||
const player1Rating = 1600;
|
||||
const player2Rating = 1400;
|
||||
|
||||
const teamRating = calculateTeamElo(player1Rating, player2Rating);
|
||||
|
||||
expect(teamRating).toBe(1500);
|
||||
});
|
||||
|
||||
test('should handle different team compositions', () => {
|
||||
const team1 = calculateTeamElo(1500, 1500);
|
||||
const team2 = calculateTeamElo(1400, 1600);
|
||||
const team3 = calculateTeamElo(1200, 1800);
|
||||
|
||||
// All should average to 1500
|
||||
expect(team1).toBe(1500);
|
||||
expect(team2).toBe(1500);
|
||||
expect(team3).toBe(1500);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Elo Change Distribution', () => {
|
||||
test('should conserve total rating points in system', () => {
|
||||
const player1Rating = 1500;
|
||||
const player2Rating = 1500;
|
||||
const player3Rating = 1500;
|
||||
const player4Rating = 1500;
|
||||
|
||||
// Simulate a match where team 1 wins
|
||||
const team1Rating = calculateTeamElo(player1Rating, player2Rating);
|
||||
const team2Rating = calculateTeamElo(player3Rating, player4Rating);
|
||||
|
||||
const team1Expected = calculateExpectedScore(team1Rating, team2Rating);
|
||||
const team2Expected = calculateExpectedScore(team2Rating, team1Rating);
|
||||
|
||||
// Team 1 wins (score = 1, team 2 score = 0)
|
||||
const team1Change = calculateEloChange(team1Rating, team2Rating, 1, K_FACTOR);
|
||||
const team2Change = calculateEloChange(team2Rating, team1Rating, 0, K_FACTOR);
|
||||
|
||||
// Split changes between team members
|
||||
const player1Change = team1Change / 2;
|
||||
const player2Change = team1Change / 2;
|
||||
const player3Change = team2Change / 2;
|
||||
const player4Change = team2Change / 2;
|
||||
|
||||
// Total change should be zero (conservation of points)
|
||||
const totalChange = player1Change + player2Change + player3Change + player4Change;
|
||||
expect(totalChange).toBeCloseTo(0, 10);
|
||||
});
|
||||
|
||||
test('should calculate correct ratings after match', () => {
|
||||
const p1Initial = 1500;
|
||||
const p2Initial = 1500;
|
||||
const p3Initial = 1500;
|
||||
const p4Initial = 1500;
|
||||
|
||||
// Team 1 wins
|
||||
const team1Rating = calculateTeamElo(p1Initial, p2Initial);
|
||||
const team2Rating = calculateTeamElo(p3Initial, p4Initial);
|
||||
|
||||
const team1Change = calculateEloChange(team1Rating, team2Rating, 1, K_FACTOR);
|
||||
const team2Change = calculateEloChange(team2Rating, team1Rating, 0, K_FACTOR);
|
||||
|
||||
const p1Change = team1Change / 2;
|
||||
const p2Change = team1Change / 2;
|
||||
const p3Change = team2Change / 2;
|
||||
const p4Change = team2Change / 2;
|
||||
|
||||
// After match
|
||||
const p1Final = p1Initial + p1Change;
|
||||
const p2Final = p2Initial + p2Change;
|
||||
const p3Final = p3Initial + p3Change;
|
||||
const p4Final = p4Initial + p4Change;
|
||||
|
||||
// Winners should have higher ratings
|
||||
expect(p1Final).toBeGreaterThan(p1Initial);
|
||||
expect(p2Final).toBeGreaterThan(p2Initial);
|
||||
|
||||
// Losers should have lower ratings
|
||||
expect(p3Final).toBeLessThan(p3Initial);
|
||||
expect(p4Final).toBeLessThan(p4Initial);
|
||||
|
||||
// All final ratings should still be close to 1500
|
||||
expect(p1Final).toBeGreaterThan(1480);
|
||||
expect(p1Final).toBeLessThan(1520);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Rating Improvement Over Time', () => {
|
||||
test('should reflect consistent winning with rating increase', () => {
|
||||
let rating = 1500;
|
||||
const opponentRating = 1500;
|
||||
|
||||
// Simulate 10 consecutive wins
|
||||
for (let i = 0; i < 10; i++) {
|
||||
rating += calculateEloChange(rating, opponentRating, 1, K_FACTOR);
|
||||
}
|
||||
|
||||
// Rating should have increased significantly
|
||||
expect(rating).toBeGreaterThan(1600);
|
||||
});
|
||||
|
||||
test('should reflect consistent losing with rating decrease', () => {
|
||||
let rating = 1500;
|
||||
const opponentRating = 1500;
|
||||
|
||||
// Simulate 10 consecutive losses
|
||||
for (let i = 0; i < 10; i++) {
|
||||
rating += calculateEloChange(rating, opponentRating, 0, K_FACTOR);
|
||||
}
|
||||
|
||||
// Rating should have decreased significantly
|
||||
expect(rating).toBeLessThan(1400);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Unit Tests: Permissions
|
||||
*
|
||||
* Tests the permission system for tournament management
|
||||
*/
|
||||
|
||||
import { describe, test, expect, vi } from 'vitest';
|
||||
import { hasRole, canManageTournament, canCreateTournaments } from '@/lib/permissions';
|
||||
import { getSession } from '@/lib/auth-simple';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
|
||||
// Helper to create mock user
|
||||
const createMockUser = (id: string, email: string, role: string) => ({
|
||||
id,
|
||||
email,
|
||||
role,
|
||||
emailVerified: false,
|
||||
name: null,
|
||||
image: null,
|
||||
playerId: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
|
||||
// Mock the getSession and prisma functions
|
||||
vi.mock('@/lib/auth-simple', () => ({
|
||||
getSession: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/prisma', () => ({
|
||||
prisma: {
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
event: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
describe('Permissions', () => {
|
||||
describe('hasRole', () => {
|
||||
test('should allow club_admin to access tournament_admin resources', async () => {
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
user: { id: '1', email: 'test@example.com' },
|
||||
session: { token: 'test', expiresAt: new Date() }
|
||||
});
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue(
|
||||
createMockUser('1', 'test@example.com', 'club_admin') as any
|
||||
);
|
||||
|
||||
const result = await hasRole('tournament_admin');
|
||||
expect(result.allowed).toBe(true);
|
||||
});
|
||||
|
||||
test('should deny player from accessing tournament_admin resources', async () => {
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
user: { id: '1', email: 'test@example.com' },
|
||||
session: { token: 'test', expiresAt: new Date() }
|
||||
});
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue(
|
||||
createMockUser('1', 'test@example.com', 'player') as any
|
||||
);
|
||||
|
||||
const result = await hasRole('tournament_admin');
|
||||
expect(result.allowed).toBe(false);
|
||||
});
|
||||
|
||||
test('should deny unauthenticated user', async () => {
|
||||
vi.mocked(getSession).mockResolvedValue(null);
|
||||
|
||||
const result = await hasRole('club_admin');
|
||||
expect(result.allowed).toBe(false);
|
||||
expect(result.reason).toContain('Not authenticated');
|
||||
});
|
||||
});
|
||||
|
||||
describe('canManageTournament', () => {
|
||||
test('should allow club_admin to manage any tournament', async () => {
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
user: { id: 'admin-1', email: 'admin@example.com' },
|
||||
session: { token: 'test', expiresAt: new Date() }
|
||||
});
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue(
|
||||
createMockUser('admin-1', 'admin@example.com', 'club_admin') as any
|
||||
);
|
||||
|
||||
const result = await canManageTournament(999);
|
||||
expect(result.allowed).toBe(true);
|
||||
});
|
||||
|
||||
test('should deny player from managing tournaments', async () => {
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
user: { id: 'player-1', email: 'player@example.com' },
|
||||
session: { token: 'test', expiresAt: new Date() }
|
||||
});
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue(
|
||||
createMockUser('player-1', 'player@example.com', 'player') as any
|
||||
);
|
||||
|
||||
const result = await canManageTournament(999);
|
||||
expect(result.allowed).toBe(false);
|
||||
expect(result.reason).toContain('Insufficient permissions');
|
||||
});
|
||||
});
|
||||
|
||||
describe('canCreateTournaments', () => {
|
||||
test('should allow tournament_admin to create tournaments', async () => {
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
user: { id: 'admin-1', email: 'admin@example.com' },
|
||||
session: { token: 'test', expiresAt: new Date() }
|
||||
});
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue(
|
||||
createMockUser('admin-1', 'admin@example.com', 'tournament_admin') as any
|
||||
);
|
||||
|
||||
const result = await canCreateTournaments();
|
||||
expect(result.allowed).toBe(true);
|
||||
});
|
||||
|
||||
test('should allow club_admin to create tournaments', async () => {
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
user: { id: 'admin-1', email: 'admin@example.com' },
|
||||
session: { token: 'test', expiresAt: new Date() }
|
||||
});
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue(
|
||||
createMockUser('admin-1', 'admin@example.com', 'club_admin') as any
|
||||
);
|
||||
|
||||
const result = await canCreateTournaments();
|
||||
expect(result.allowed).toBe(true);
|
||||
});
|
||||
|
||||
test('should deny player from creating tournaments', async () => {
|
||||
vi.mocked(getSession).mockResolvedValue({
|
||||
user: { id: 'player-1', email: 'player@example.com' },
|
||||
session: { token: 'test', expiresAt: new Date() }
|
||||
});
|
||||
vi.mocked(prisma.user.findUnique).mockResolvedValue(
|
||||
createMockUser('player-1', 'player@example.com', 'player') as any
|
||||
);
|
||||
|
||||
const result = await canCreateTournaments();
|
||||
expect(result.allowed).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,306 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useRef, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Navigation from "@/components/Navigation"
|
||||
|
||||
export default function UploadMatchesPage() {
|
||||
const router = useRouter()
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [selectedTournament, setSelectedTournament] = useState<string>("")
|
||||
const [error, setError] = useState("")
|
||||
const [success, setSuccess] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [tournaments, setTournaments] = useState<any[]>([])
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// Fetch tournaments on mount
|
||||
useEffect(() => {
|
||||
fetch(`${window.location.origin}/api/tournaments`)
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
if (data.tournaments) {
|
||||
setTournaments(data.tournaments)
|
||||
// If no tournaments exist, create one automatically
|
||||
if (data.tournaments.length === 0) {
|
||||
createDefaultTournament()
|
||||
} else if (data.tournaments.length > 0) {
|
||||
// Auto-select the most recent tournament
|
||||
setSelectedTournament(data.tournaments[0].id.toString())
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((err) => console.error("Failed to fetch tournaments:", err))
|
||||
}, [])
|
||||
|
||||
const createDefaultTournament = async () => {
|
||||
try {
|
||||
const response = await fetch(`${window.location.origin}/api/tournaments`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: `Tournament ${new Date().toLocaleDateString()}`,
|
||||
format: "round_robin",
|
||||
eventDate: new Date().toISOString(),
|
||||
}),
|
||||
})
|
||||
const data = await response.json()
|
||||
if (response.ok && data.tournament) {
|
||||
setTournaments([data.tournament])
|
||||
setSelectedTournament(data.tournament.id.toString())
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error("Failed to create default tournament:", err)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
if (!file.name.endsWith(".csv")) {
|
||||
setError("Please upload a CSV file")
|
||||
return
|
||||
}
|
||||
setSelectedFile(file)
|
||||
setError("")
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError("")
|
||||
setSuccess("")
|
||||
|
||||
if (!selectedFile) {
|
||||
setError("Please select a CSV file to upload")
|
||||
return
|
||||
}
|
||||
|
||||
if (!selectedTournament) {
|
||||
setError("Please select a tournament")
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const formData = new FormData()
|
||||
formData.append("csvFile", selectedFile)
|
||||
formData.append("eventId", selectedTournament)
|
||||
|
||||
const response = await fetch(`${window.location.origin}/api/matches/upload`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || "Failed to upload CSV")
|
||||
}
|
||||
|
||||
setSuccess(
|
||||
`Successfully imported ${data.importedCount} matches. ` +
|
||||
`${data.errorCount || 0} errors occurred.` +
|
||||
(data.errors ? `\n\nErrors:\n${data.errors.join("\n")}` : "")
|
||||
)
|
||||
|
||||
// Reset form
|
||||
setSelectedFile(null)
|
||||
setSelectedTournament("")
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ""
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-3xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-6">
|
||||
Upload Match Results (CSV)
|
||||
</h1>
|
||||
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{error && (
|
||||
<div className="rounded-md bg-red-50 p-4">
|
||||
<div className="text-sm text-red-700 whitespace-pre-wrap">
|
||||
{error}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div className="rounded-md bg-green-50 p-4">
|
||||
<div className="text-sm text-green-700 whitespace-pre-wrap">
|
||||
{success}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tournament Selection */}
|
||||
<div>
|
||||
<label htmlFor="tournament" className="block text-sm font-medium text-gray-700">
|
||||
Select Tournament *
|
||||
</label>
|
||||
<div className="mt-1 flex gap-2">
|
||||
<select
|
||||
id="tournament"
|
||||
value={selectedTournament}
|
||||
onChange={(e) => setSelectedTournament(e.target.value)}
|
||||
className="flex-1 block border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Choose a tournament...</option>
|
||||
{tournaments.map((tournament) => (
|
||||
<option key={tournament.id} value={tournament.id}>
|
||||
{tournament.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const name = prompt("Enter tournament name:");
|
||||
if (name) {
|
||||
fetch(`${window.location.origin}/api/tournaments`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
format: "round_robin",
|
||||
eventDate: new Date().toISOString(),
|
||||
}),
|
||||
})
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
if (data.tournament) {
|
||||
setTournaments([...tournaments, data.tournament])
|
||||
setSelectedTournament(data.tournament.id.toString())
|
||||
}
|
||||
})
|
||||
.catch((err) => console.error("Failed to create tournament:", err))
|
||||
}
|
||||
}}
|
||||
className="px-3 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
|
||||
>
|
||||
New
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* File Upload */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
CSV File *
|
||||
</label>
|
||||
<div className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
|
||||
<div className="space-y-1 text-center">
|
||||
<svg
|
||||
className="mx-auto h-12 w-12 text-gray-400"
|
||||
stroke="currentColor"
|
||||
fill="none"
|
||||
viewBox="0 0 48 48"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
|
||||
strokeWidth={2}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
<div className="flex text-sm text-gray-600">
|
||||
<label
|
||||
htmlFor="file-upload"
|
||||
className="relative cursor-pointer bg-white rounded-md font-medium text-green-600 hover:text-green-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-green-500"
|
||||
>
|
||||
<span>Upload a file</span>
|
||||
<input
|
||||
id="file-upload"
|
||||
name="file-upload"
|
||||
type="file"
|
||||
className="sr-only"
|
||||
accept=".csv"
|
||||
onChange={handleFileChange}
|
||||
ref={fileInputRef}
|
||||
/>
|
||||
</label>
|
||||
<p className="pl-1">or drag and drop</p>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">
|
||||
CSV file with match results
|
||||
</p>
|
||||
{selectedFile && (
|
||||
<p className="text-sm text-green-600 mt-2">
|
||||
Selected: {selectedFile.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* CSV Format Guide */}
|
||||
<div className="bg-blue-50 rounded-md p-4">
|
||||
<h3 className="text-sm font-medium text-blue-800 mb-2">
|
||||
CSV Format Requirements
|
||||
</h3>
|
||||
<ul className="text-sm text-blue-700 space-y-1">
|
||||
<li><strong>Event #:</strong> Tournament ID (optional if selected above)</li>
|
||||
<li><strong>Round:</strong> Round number (1, 2, 3...)</li>
|
||||
<li><strong>Table:</strong> Table name (Clubs, Hearts, Diamonds, Spades, Stars)</li>
|
||||
<li><strong>Seat 1:</strong> Player 1 name (Odds team)</li>
|
||||
<li><strong>Seat 3:</strong> Player 2 name (Odds team)</li>
|
||||
<li><strong>Odds Points:</strong> Score for Odds team</li>
|
||||
<li><strong>Seat 2:</strong> Player 1 name (Evens team)</li>
|
||||
<li><strong>Seat 4:</strong> Player 2 name (Evens team)</li>
|
||||
<li><strong>Evens Points:</strong> Score for Evens team</li>
|
||||
<li><strong>Winner:</strong> "Odds" or "Evens" (optional)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? "Uploading..." : "Upload CSV"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* Sample CSV */}
|
||||
<div className="mt-6 bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-3">
|
||||
Sample CSV Format
|
||||
</h2>
|
||||
<pre className="bg-gray-50 rounded p-4 text-xs overflow-x-auto">
|
||||
{`Event #,Round,Table,Seat 1,Seat 3,Odds Points,Seat 2,Seat 4,Evens Points,Winner
|
||||
1,1,Clubs,Derrick,Jesse C,5,Emma,Alissa,10,Evens
|
||||
1,1,Hearts,Kevin,Andy,8,Ellie,Jesse,6,Odds`}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex justify-end">
|
||||
<button
|
||||
onClick={() => router.back()}
|
||||
className="text-green-600 hover:text-green-900"
|
||||
>
|
||||
← Back
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import Navigation from "@/components/Navigation"
|
||||
import Link from "next/link"
|
||||
import { redirect } from "next/navigation"
|
||||
import { getSession } from "@/lib/auth-simple"
|
||||
|
||||
export default async function AdminDashboard() {
|
||||
console.log('AdminDashboard rendering...')
|
||||
const session = await getSession()
|
||||
|
||||
console.log('AdminDashboard session:', JSON.stringify(session, null, 2))
|
||||
|
||||
if (!session) {
|
||||
console.log('No session found, redirecting to login')
|
||||
redirect("/auth/login")
|
||||
}
|
||||
|
||||
// Get user role from database since Better Auth doesn't include custom fields in session
|
||||
const userId = session.user?.id || session.user?.userId
|
||||
console.log('Looking for user with ID:', userId)
|
||||
console.log('Session user:', JSON.stringify(session.user, null, 2))
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId }
|
||||
})
|
||||
|
||||
console.log('Found user:', user ? 'yes' : 'no')
|
||||
console.log('User role:', user?.role)
|
||||
console.log('User email:', user?.email)
|
||||
|
||||
// If user doesn't exist or has no role, redirect to login
|
||||
if (!user) {
|
||||
console.log('User not found, redirecting to login')
|
||||
redirect("/auth/login")
|
||||
}
|
||||
|
||||
// Non-admin users should see a different dashboard
|
||||
if (user.role !== "club_admin") {
|
||||
if (user.playerId) {
|
||||
redirect("/players/" + user.playerId + "/profile")
|
||||
} else {
|
||||
// If playerId is null, redirect to rankings page
|
||||
redirect("/rankings")
|
||||
}
|
||||
}
|
||||
|
||||
// Get dashboard stats
|
||||
const [playerCount, tournamentCount, matchCount, recentTournaments] = await Promise.all([
|
||||
prisma.player.count(),
|
||||
prisma.event.count(),
|
||||
prisma.match.count(),
|
||||
prisma.event.findMany({
|
||||
take: 5,
|
||||
orderBy: { createdAt: "desc" },
|
||||
}),
|
||||
])
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
{/* Page Header */}
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Admin Dashboard</h1>
|
||||
<p className="text-gray-500 mt-1">
|
||||
Manage your club's tournaments, players, and matches.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Stats Grid */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<div className="flex items-center">
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-5 w-0 flex-1">
|
||||
<dl>
|
||||
<dt className="text-sm font-medium text-gray-500 truncate">Total Players</dt>
|
||||
<dd className="text-lg font-semibold text-gray-900">{playerCount}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<div className="flex items-center">
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-5 w-0 flex-1">
|
||||
<dl>
|
||||
<dt className="text-sm font-medium text-gray-500 truncate">Tournaments</dt>
|
||||
<dd className="text-lg font-semibold text-gray-900">{tournamentCount}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<div className="flex items-center">
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-5 w-0 flex-1">
|
||||
<dl>
|
||||
<dt className="text-sm font-medium text-gray-500 truncate">Matches Played</dt>
|
||||
<dd className="text-lg font-semibold text-gray-900">{matchCount}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Actions */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">Quick Actions</h2>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Link
|
||||
href="/admin/tournaments/new"
|
||||
className="flex items-center justify-center px-4 py-3 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700"
|
||||
>
|
||||
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
|
||||
</svg>
|
||||
New Tournament
|
||||
</Link>
|
||||
<Link
|
||||
href="/admin/matches/upload"
|
||||
className="flex items-center justify-center px-4 py-3 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700"
|
||||
>
|
||||
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
|
||||
</svg>
|
||||
Import CSV
|
||||
</Link>
|
||||
<Link
|
||||
href="/rankings"
|
||||
className="flex items-center justify-center px-4 py-3 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
|
||||
>
|
||||
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
|
||||
</svg>
|
||||
View Rankings
|
||||
</Link>
|
||||
<Link
|
||||
href="/admin/tournaments"
|
||||
className="flex items-center justify-center px-4 py-3 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
|
||||
>
|
||||
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
|
||||
</svg>
|
||||
All Tournaments
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recent Tournaments */}
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">Recent Tournaments</h2>
|
||||
{recentTournaments.length > 0 ? (
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{recentTournaments.map((tournament) => (
|
||||
<li key={tournament.id} className="py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900">{tournament.name}</p>
|
||||
<p className="text-sm text-gray-500">{tournament.status}</p>
|
||||
</div>
|
||||
<Link
|
||||
href={`/admin/tournaments/${tournament.id}`}
|
||||
className="text-green-600 hover:text-green-900 text-sm font-medium"
|
||||
>
|
||||
View
|
||||
</Link>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-gray-500">No tournaments yet.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Player Directory Preview */}
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-lg font-medium text-gray-900">Player Directory</h2>
|
||||
<Link
|
||||
href="/admin/players"
|
||||
className="text-green-600 hover:text-green-900 text-sm font-medium"
|
||||
>
|
||||
View All
|
||||
</Link>
|
||||
</div>
|
||||
{/* This would be populated with actual player data in a real implementation */}
|
||||
<p className="text-gray-500">
|
||||
<Link href="/rankings" className="text-green-600 hover:text-green-900">
|
||||
View all players
|
||||
</Link> in the rankings page.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import Navigation from "@/components/Navigation"
|
||||
import Link from "next/link"
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
import { getSession } from "@/lib/auth-simple"
|
||||
import EditTournamentForm from "@/components/EditTournamentForm"
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
id: string
|
||||
}
|
||||
}
|
||||
|
||||
export default async function EditTournamentPage({ params }: PageProps) {
|
||||
const session = await getSession()
|
||||
|
||||
if (!session || session.user?.role !== "club_admin") {
|
||||
redirect("/auth/login")
|
||||
}
|
||||
|
||||
const tournamentId = parseInt(params.id)
|
||||
|
||||
const tournament = await prisma.event.findUnique({
|
||||
where: { id: tournamentId },
|
||||
})
|
||||
|
||||
if (!tournament) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
{/* Breadcrumb */}
|
||||
<nav className="mb-4">
|
||||
<ol className="flex items-center space-x-2">
|
||||
<li>
|
||||
<Link href="/admin/tournaments" className="text-green-600 hover:text-green-900">
|
||||
Tournaments
|
||||
</Link>
|
||||
</li>
|
||||
<li className="text-gray-400">/</li>
|
||||
<li>
|
||||
<Link href={`/admin/tournaments/${tournament.id}`} className="text-green-600 hover:text-green-900">
|
||||
{tournament.name}
|
||||
</Link>
|
||||
</li>
|
||||
<li className="text-gray-400">/</li>
|
||||
<li className="text-gray-600">Edit</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
{/* Page Header */}
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Edit Tournament</h1>
|
||||
<p className="text-gray-500 mt-1">
|
||||
Update the tournament details below.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Edit Form */}
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<EditTournamentForm tournament={tournament} />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import Navigation from "@/components/Navigation"
|
||||
import Link from "next/link"
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
import { getSession } from "@/lib/auth-simple"
|
||||
import { getTournamentStatus } from "@/lib/tournamentUtils"
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
id: string
|
||||
}
|
||||
}
|
||||
|
||||
export default async function TournamentDetailPage({ params }: PageProps) {
|
||||
const session = await getSession()
|
||||
|
||||
if (!session) {
|
||||
redirect("/auth/login")
|
||||
}
|
||||
|
||||
// Fetch user role from database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { role: true },
|
||||
});
|
||||
|
||||
const isAdmin = user?.role === "club_admin"
|
||||
|
||||
const tournamentId = parseInt(params.id)
|
||||
|
||||
let tournament = await prisma.event.findUnique({
|
||||
where: { id: tournamentId },
|
||||
include: {
|
||||
participants: {
|
||||
include: {
|
||||
player: true,
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
include: {
|
||||
player1: true,
|
||||
player2: true,
|
||||
},
|
||||
},
|
||||
rounds: {
|
||||
include: {
|
||||
bracketMatchups: {
|
||||
include: {
|
||||
team1: {
|
||||
include: {
|
||||
player1: true,
|
||||
player2: true,
|
||||
},
|
||||
},
|
||||
team2: {
|
||||
include: {
|
||||
player1: true,
|
||||
player2: true,
|
||||
},
|
||||
},
|
||||
match: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!tournament) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
// Update tournament status based on event date
|
||||
const calculatedStatus = getTournamentStatus(tournament.eventDate);
|
||||
if (tournament.status !== calculatedStatus) {
|
||||
tournament = await prisma.event.update({
|
||||
where: { id: tournamentId },
|
||||
data: { status: calculatedStatus },
|
||||
include: {
|
||||
participants: {
|
||||
include: {
|
||||
player: true,
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
include: {
|
||||
player1: true,
|
||||
player2: true,
|
||||
},
|
||||
},
|
||||
rounds: {
|
||||
include: {
|
||||
bracketMatchups: {
|
||||
include: {
|
||||
team1: {
|
||||
include: {
|
||||
player1: true,
|
||||
player2: true,
|
||||
},
|
||||
},
|
||||
team2: {
|
||||
include: {
|
||||
player1: true,
|
||||
player2: true,
|
||||
},
|
||||
},
|
||||
match: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const matches = await prisma.match.findMany({
|
||||
where: { eventId: tournamentId },
|
||||
include: {
|
||||
team1P1: true,
|
||||
team1P2: true,
|
||||
team2P1: true,
|
||||
team2P2: true,
|
||||
},
|
||||
orderBy: { playedAt: "desc" },
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
{/* Breadcrumb */}
|
||||
<nav className="mb-4">
|
||||
<ol className="flex items-center space-x-2">
|
||||
<li>
|
||||
<Link href="/admin/tournaments" className="text-green-600 hover:text-green-900">
|
||||
Tournaments
|
||||
</Link>
|
||||
</li>
|
||||
<li className="text-gray-400">/</li>
|
||||
<li className="text-gray-600">{tournament.name}</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
{/* Tournament Header */}
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900">{tournament.name}</h1>
|
||||
<p className="text-gray-500 mt-1">
|
||||
{tournament.format} - {tournament.status}
|
||||
</p>
|
||||
{tournament.eventDate && (
|
||||
<p className="text-sm text-gray-400 mt-1">
|
||||
{new Date(tournament.eventDate).toLocaleDateString()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
{isAdmin && (
|
||||
<>
|
||||
<Link
|
||||
href={`/admin/tournaments/${tournament.id}/edit`}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
|
||||
>
|
||||
Edit
|
||||
</Link>
|
||||
<Link
|
||||
href={`/admin/tournaments/${tournament.id}/results`}
|
||||
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700"
|
||||
>
|
||||
Enter Results
|
||||
</Link>
|
||||
<a
|
||||
href={`/api/tournaments/${tournament.id}/export`}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
|
||||
>
|
||||
Export CSV
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Quick Stats */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6">
|
||||
<div className="bg-gray-50 rounded-lg p-4 text-center">
|
||||
<p className="text-sm text-gray-500">Participants</p>
|
||||
<p className="text-2xl font-bold text-gray-900">
|
||||
{tournament.participants.length}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 rounded-lg p-4 text-center">
|
||||
<p className="text-sm text-gray-500">Teams</p>
|
||||
<p className="text-2xl font-bold text-gray-900">
|
||||
{tournament.teams.length}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 rounded-lg p-4 text-center">
|
||||
<p className="text-sm text-gray-500">Rounds</p>
|
||||
<p className="text-2xl font-bold text-gray-900">
|
||||
{tournament.rounds.length}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 rounded-lg p-4 text-center">
|
||||
<p className="text-sm text-gray-500">Matches</p>
|
||||
<p className="text-2xl font-bold text-gray-900">
|
||||
{matches.length}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="border-b border-gray-200">
|
||||
<nav className="-mb-px flex space-x-8">
|
||||
<button className="border-green-500 text-green-600 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
|
||||
Overview
|
||||
</button>
|
||||
<button className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
|
||||
Participants
|
||||
</button>
|
||||
<button className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
|
||||
Teams
|
||||
</button>
|
||||
<button className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
|
||||
Schedule
|
||||
</button>
|
||||
<button className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
|
||||
Results
|
||||
</button>
|
||||
<button className="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
|
||||
Analytics
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="mt-6">
|
||||
{/* Participants Section */}
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Participants ({tournament.participants.length})
|
||||
</h2>
|
||||
|
||||
{tournament.participants.length > 0 ? (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
{tournament.participants.map((participant) => (
|
||||
<div
|
||||
key={participant.id}
|
||||
className="bg-gray-50 rounded p-2 text-center"
|
||||
>
|
||||
<Link
|
||||
href={`/players/${participant.player.id}/profile`}
|
||||
className="text-green-600 hover:text-green-900 text-sm"
|
||||
>
|
||||
{participant.player.name}
|
||||
</Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500">No participants registered yet.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Teams Section */}
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Teams ({tournament.teams.length})
|
||||
</h2>
|
||||
|
||||
{tournament.teams.length > 0 ? (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{tournament.teams.map((team) => (
|
||||
<div
|
||||
key={team.id}
|
||||
className="bg-gray-50 rounded p-3 flex justify-between items-center"
|
||||
>
|
||||
<div>
|
||||
<p className="font-medium text-gray-900">
|
||||
{team.player1.name} + {team.player2.name}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">{team.teamName}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500">No teams created yet.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Recent Matches Section */}
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Recent Matches ({matches.length})
|
||||
</h2>
|
||||
|
||||
{matches.length > 0 ? (
|
||||
<div className="space-y-3">
|
||||
{matches.slice(0, 10).map((match) => (
|
||||
<div
|
||||
key={match.id}
|
||||
className="border border-gray-200 rounded p-3"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex-1">
|
||||
<p className="text-sm text-gray-500">
|
||||
{match.playedAt?.toLocaleDateString()}
|
||||
</p>
|
||||
<p className="font-medium">
|
||||
{match.team1P1.name} + {match.team1P2.name} vs{" "}
|
||||
{match.team2P1.name} + {match.team2P2.name}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<span className={`font-bold ${
|
||||
match.team1Score > match.team2Score
|
||||
? 'text-green-600'
|
||||
: match.team1Score < match.team2Score
|
||||
? 'text-red-600'
|
||||
: 'text-gray-600'
|
||||
}`}>
|
||||
{match.team1Score}
|
||||
</span>
|
||||
<span className="text-gray-400 mx-2">-</span>
|
||||
<span className={`font-bold ${
|
||||
match.team2Score > match.team1Score
|
||||
? 'text-green-600'
|
||||
: match.team2Score < match.team1Score
|
||||
? 'text-red-600'
|
||||
: 'text-gray-600'
|
||||
}`}>
|
||||
{match.team2Score}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500">No matches recorded yet.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import Navigation from "@/components/Navigation"
|
||||
import Link from "next/link"
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
import { getSession } from "@/lib/auth-simple"
|
||||
import MatchEditor from "@/components/MatchEditor"
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
id: string
|
||||
}
|
||||
}
|
||||
|
||||
export default async function TournamentResultsPage({ params }: PageProps) {
|
||||
const session = await getSession()
|
||||
|
||||
if (!session || session.user?.role !== "club_admin") {
|
||||
redirect("/auth/login")
|
||||
}
|
||||
|
||||
const tournamentId = parseInt(params.id)
|
||||
|
||||
const tournament = await prisma.event.findUnique({
|
||||
where: { id: tournamentId },
|
||||
})
|
||||
|
||||
if (!tournament) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
const matches = await prisma.match.findMany({
|
||||
where: { eventId: tournamentId },
|
||||
include: {
|
||||
team1P1: true,
|
||||
team1P2: true,
|
||||
team2P1: true,
|
||||
team2P2: true,
|
||||
},
|
||||
orderBy: { playedAt: "desc" },
|
||||
})
|
||||
|
||||
const players = await prisma.player.findMany({
|
||||
orderBy: { name: "asc" },
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
{/* Breadcrumb */}
|
||||
<nav className="mb-4">
|
||||
<ol className="flex items-center space-x-2">
|
||||
<li>
|
||||
<Link href="/admin/tournaments" className="text-green-600 hover:text-green-900">
|
||||
Tournaments
|
||||
</Link>
|
||||
</li>
|
||||
<li className="text-gray-400">/</li>
|
||||
<li>
|
||||
<Link href={`/admin/tournaments/${tournament.id}`} className="text-green-600 hover:text-green-900">
|
||||
{tournament.name}
|
||||
</Link>
|
||||
</li>
|
||||
<li className="text-gray-400">/</li>
|
||||
<li className="text-gray-600">Enter Results</li>
|
||||
</ol>
|
||||
</nav>
|
||||
|
||||
{/* Page Header */}
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Enter Match Results</h1>
|
||||
<p className="text-gray-500 mt-1">
|
||||
Record match results for {tournament.name}.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Match Editor */}
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<MatchEditor tournamentId={tournamentId} players={players} matches={matches} />
|
||||
</div>
|
||||
|
||||
{/* Existing Matches */}
|
||||
{matches.length > 0 && (
|
||||
<div className="bg-white shadow rounded-lg p-6 mt-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Recent Matches
|
||||
</h2>
|
||||
|
||||
<div className="space-y-3">
|
||||
{matches.slice(0, 10).map((match) => (
|
||||
<div
|
||||
key={match.id}
|
||||
className="border border-gray-200 rounded p-3"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex-1">
|
||||
<p className="text-sm text-gray-500">
|
||||
{match.playedAt?.toLocaleDateString()}
|
||||
</p>
|
||||
<p className="font-medium">
|
||||
{match.team1P1.name} + {match.team1P2.name} vs{" "}
|
||||
{match.team2P1.name} + {match.team2P2.name}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<span className={`font-bold ${
|
||||
match.team1Score > match.team2Score
|
||||
? 'text-green-600'
|
||||
: match.team1Score < match.team2Score
|
||||
? 'text-red-600'
|
||||
: 'text-gray-600'
|
||||
}`}>
|
||||
{match.team1Score}
|
||||
</span>
|
||||
<span className="text-gray-400 mx-2">-</span>
|
||||
<span className={`font-bold ${
|
||||
match.team2Score > match.team1Score
|
||||
? 'text-green-600'
|
||||
: match.team2Score < match.team1Score
|
||||
? 'text-red-600'
|
||||
: 'text-gray-600'
|
||||
}`}>
|
||||
{match.team2Score}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Navigation from "@/components/Navigation"
|
||||
|
||||
export default function NewTournamentPage() {
|
||||
const router = useRouter()
|
||||
const [formData, setFormData] = useState({
|
||||
name: "",
|
||||
description: "",
|
||||
eventDate: "",
|
||||
format: "round_robin",
|
||||
maxParticipants: "",
|
||||
})
|
||||
const [error, setError] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
|
||||
setFormData({
|
||||
...formData,
|
||||
[e.target.name]: e.target.value,
|
||||
})
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError("")
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/tournaments", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: formData.name,
|
||||
description: formData.description,
|
||||
eventDate: formData.eventDate || null,
|
||||
format: formData.format,
|
||||
maxParticipants: formData.maxParticipants ? parseInt(formData.maxParticipants) : null,
|
||||
}),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || "Failed to create tournament")
|
||||
}
|
||||
|
||||
router.push(`/admin/tournaments/${data.tournament.id}`)
|
||||
} catch (err: any) {
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-3xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-6">
|
||||
Create New Tournament
|
||||
</h1>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{error && (
|
||||
<div className="rounded-md bg-red-50 p-4">
|
||||
<div className="text-sm text-red-700">{error}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
|
||||
Tournament Name *
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
name="name"
|
||||
id="name"
|
||||
required
|
||||
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
|
||||
value={formData.name}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="description" className="block text-sm font-medium text-gray-700">
|
||||
Description
|
||||
</label>
|
||||
<textarea
|
||||
name="description"
|
||||
id="description"
|
||||
rows={3}
|
||||
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
|
||||
value={formData.description}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
|
||||
<div>
|
||||
<label htmlFor="eventDate" className="block text-sm font-medium text-gray-700">
|
||||
Event Date
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
name="eventDate"
|
||||
id="eventDate"
|
||||
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
|
||||
value={formData.eventDate}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="format" className="block text-sm font-medium text-gray-700">
|
||||
Format *
|
||||
</label>
|
||||
<select
|
||||
name="format"
|
||||
id="format"
|
||||
required
|
||||
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
|
||||
value={formData.format}
|
||||
onChange={handleChange}
|
||||
>
|
||||
<option value="round_robin">Round Robin</option>
|
||||
<option value="single_elimination">Single Elimination</option>
|
||||
<option value="double_elimination">Double Elimination</option>
|
||||
<option value="swiss">Swiss</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="maxParticipants" className="block text-sm font-medium text-gray-700">
|
||||
Max Participants
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="maxParticipants"
|
||||
id="maxParticipants"
|
||||
min="2"
|
||||
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
|
||||
value={formData.maxParticipants}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => router.back()}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? "Creating..." : "Create Tournament"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import Navigation from "@/components/Navigation"
|
||||
import Link from "next/link"
|
||||
import { getSession } from "@/lib/auth-simple"
|
||||
import { redirect } from "next/navigation"
|
||||
import { getTournamentStatus } from "@/lib/tournamentUtils"
|
||||
|
||||
export default async function AdminTournamentsPage() {
|
||||
const session = await getSession()
|
||||
|
||||
if (!session) {
|
||||
redirect("/auth/login")
|
||||
}
|
||||
|
||||
// Fetch user role from database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { role: true },
|
||||
});
|
||||
|
||||
const isAdmin = user?.role === "club_admin"
|
||||
|
||||
const tournaments = await prisma.event.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
participants: true,
|
||||
teams: {
|
||||
include: {
|
||||
player1: true,
|
||||
player2: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Update tournament statuses based on event date
|
||||
const updatedTournaments = await Promise.all(
|
||||
tournaments.map(async (tournament) => {
|
||||
const calculatedStatus = getTournamentStatus(tournament.eventDate);
|
||||
|
||||
// Only update if the calculated status differs from the stored status
|
||||
if (tournament.status !== calculatedStatus) {
|
||||
await prisma.event.update({
|
||||
where: { id: tournament.id },
|
||||
data: { status: calculatedStatus },
|
||||
});
|
||||
return { ...tournament, status: calculatedStatus };
|
||||
}
|
||||
|
||||
return tournament;
|
||||
})
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h1 className="text-3xl font-bold text-gray-900">
|
||||
{isAdmin ? 'Tournament Management' : 'Tournaments'}
|
||||
</h1>
|
||||
{isAdmin && (
|
||||
<Link
|
||||
href="/admin/tournaments/new"
|
||||
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700"
|
||||
>
|
||||
Create Tournament
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-white shadow overflow-hidden sm:rounded-lg">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Tournament
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Format
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Status
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Participants
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Actions
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{updatedTournaments.map((tournament) => (
|
||||
<tr key={tournament.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<Link
|
||||
href={`/admin/tournaments/${tournament.id}`}
|
||||
className="text-green-600 hover:text-green-900 font-medium"
|
||||
>
|
||||
{tournament.name}
|
||||
</Link>
|
||||
{tournament.eventDate && (
|
||||
<p className="text-sm text-gray-500">
|
||||
{new Date(tournament.eventDate).toLocaleDateString()}
|
||||
</p>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
|
||||
{tournament.format}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className={`inline-flex px-2 py-1 text-xs font-semibold leading-5 rounded-full ${
|
||||
tournament.status === 'active' || tournament.status === 'in_progress'
|
||||
? 'bg-green-100 text-green-800'
|
||||
: tournament.status === 'completed'
|
||||
? 'bg-gray-100 text-gray-800'
|
||||
: 'bg-yellow-100 text-yellow-800'
|
||||
}`}>
|
||||
{tournament.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{tournament.participants.length}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
|
||||
<Link
|
||||
href={`/admin/tournaments/${tournament.id}`}
|
||||
className="text-green-600 hover:text-green-900 mr-3"
|
||||
>
|
||||
View
|
||||
</Link>
|
||||
{isAdmin && (
|
||||
<Link
|
||||
href={`/admin/tournaments/${tournament.id}/edit`}
|
||||
className="text-blue-600 hover:text-blue-900"
|
||||
>
|
||||
Edit
|
||||
</Link>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{updatedTournaments.length === 0 && (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-gray-500">No tournaments found.</p>
|
||||
{isAdmin && (
|
||||
<Link
|
||||
href="/admin/tournaments/new"
|
||||
className="text-green-600 hover:text-green-900 mt-2 inline-block"
|
||||
>
|
||||
Create your first tournament
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { auth } from "@/lib/auth";
|
||||
import { toNextJsHandler } from "better-auth/next-js";
|
||||
|
||||
export const { GET, POST } = toNextJsHandler(auth);
|
||||
@@ -0,0 +1,258 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import Papa from "papaparse";
|
||||
import { canManageTournament } from "@/lib/permissions";
|
||||
import { getSession } from "@/lib/auth-simple";
|
||||
import { calculateTeamElo, calculateExpectedTeamScore, calculateTeamEloChange } from "@/lib/elo-utils";
|
||||
|
||||
interface CSVRow {
|
||||
"Event #": string;
|
||||
Round: string;
|
||||
Table: string;
|
||||
"Seat 1": string;
|
||||
"Seat 3": string;
|
||||
"Odds Points": string;
|
||||
"Seat 2": string;
|
||||
"Seat 4": string;
|
||||
"Evens Points": string;
|
||||
Winner?: string;
|
||||
}
|
||||
|
||||
const K_FACTOR = 32; // Standard K-factor for Elo calculations
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const csvFile = formData.get("csvFile") as File;
|
||||
const eventId = formData.get("eventId") as string;
|
||||
|
||||
if (!csvFile) {
|
||||
return NextResponse.json(
|
||||
{ error: "No CSV file provided" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!eventId) {
|
||||
return NextResponse.json(
|
||||
{ error: "No tournament selected" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if user has permission to add matches to this tournament
|
||||
const permission = await canManageTournament(parseInt(eventId));
|
||||
if (!permission.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: permission.reason || 'Insufficient permissions to add matches' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Get the current user to assign as match creator
|
||||
const session = await getSession();
|
||||
const userId = session?.user?.id || null;
|
||||
|
||||
// Read and parse CSV
|
||||
const csvText = await csvFile.text();
|
||||
const parseResult = Papa.parse<CSVRow>(csvText, {
|
||||
header: true,
|
||||
skipEmptyLines: true,
|
||||
});
|
||||
|
||||
if (parseResult.errors.length > 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "CSV parsing errors", errors: parseResult.errors.map((e: any) => e.message) },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const rows = parseResult.data;
|
||||
let importedCount = 0;
|
||||
let errorCount = 0;
|
||||
const errors: string[] = [];
|
||||
|
||||
// Process each row
|
||||
for (const [index, row] of rows.entries()) {
|
||||
try {
|
||||
// Extract player names
|
||||
const player1Name = row["Seat 1"]?.trim();
|
||||
const player2Name = row["Seat 3"]?.trim();
|
||||
const player3Name = row["Seat 2"]?.trim();
|
||||
const player4Name = row["Seat 4"]?.trim();
|
||||
|
||||
if (!player1Name || !player2Name || !player3Name || !player4Name) {
|
||||
errors.push(`Row ${index + 2}: Missing player names`);
|
||||
errorCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find or create players
|
||||
const players = await Promise.all([
|
||||
findOrCreatePlayer(player1Name),
|
||||
findOrCreatePlayer(player2Name),
|
||||
findOrCreatePlayer(player3Name),
|
||||
findOrCreatePlayer(player4Name),
|
||||
]);
|
||||
|
||||
console.log('Players found/created:');
|
||||
players.forEach((p, i) => {
|
||||
console.log(` Player ${i + 1}: ${p.name} (ID: ${p.id}, Elo: ${p.currentElo})`);
|
||||
});
|
||||
|
||||
// Parse scores
|
||||
const team1Score = parseInt(row["Odds Points"]) || 0;
|
||||
const team2Score = parseInt(row["Evens Points"]) || 0;
|
||||
|
||||
// Determine winner
|
||||
const team1Won = team1Score > team2Score;
|
||||
const team2Won = team2Score > team1Score;
|
||||
const isTie = team1Score === team2Score;
|
||||
|
||||
// Calculate Elo ratings using standard formula
|
||||
const team1Rating = calculateTeamElo(players[0].currentElo, players[1].currentElo);
|
||||
const team2Rating = calculateTeamElo(players[2].currentElo, players[3].currentElo);
|
||||
|
||||
// Actual scores (1 for win, 0.5 for tie, 0 for loss)
|
||||
const team1ScoreActual = isTie ? 0.5 : (team1Won ? 1 : 0);
|
||||
const team2ScoreActual = isTie ? 0.5 : (team2Won ? 1 : 0);
|
||||
|
||||
// Elo change for each team
|
||||
const team1EloChange = calculateTeamEloChange(team1Rating, team2Rating, team1ScoreActual, K_FACTOR);
|
||||
const team2EloChange = calculateTeamEloChange(team2Rating, team1Rating, team2ScoreActual, K_FACTOR);
|
||||
|
||||
// Individual Elo changes (split evenly between team members)
|
||||
const player1EloChange = team1EloChange / 2;
|
||||
const player2EloChange = team1EloChange / 2;
|
||||
const player3EloChange = team2EloChange / 2;
|
||||
const player4EloChange = team2EloChange / 2;
|
||||
|
||||
// Create match
|
||||
await prisma.match.create({
|
||||
data: {
|
||||
eventId: parseInt(eventId),
|
||||
playedAt: new Date(),
|
||||
team1P1Id: players[0].id,
|
||||
team1P2Id: players[1].id,
|
||||
team2P1Id: players[2].id,
|
||||
team2P2Id: players[3].id,
|
||||
team1Score,
|
||||
team2Score,
|
||||
status: "completed",
|
||||
createdById: userId,
|
||||
},
|
||||
});
|
||||
|
||||
// Update individual player stats
|
||||
await updatePlayerStats(players[0].id, team1Won, player1EloChange);
|
||||
await updatePlayerStats(players[1].id, team1Won, player2EloChange);
|
||||
await updatePlayerStats(players[2].id, team2Won, player3EloChange);
|
||||
await updatePlayerStats(players[3].id, team2Won, player4EloChange);
|
||||
|
||||
// Update partnership stats (for tracking how players perform together)
|
||||
await updatePartnershipStats(players[0].id, players[1].id, team1Won, player1EloChange);
|
||||
await updatePartnershipStats(players[2].id, players[3].id, team2Won, player3EloChange);
|
||||
|
||||
importedCount++;
|
||||
} catch (err: any) {
|
||||
errors.push(`Row ${index + 2}: ${err.message}`);
|
||||
errorCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
importedCount,
|
||||
errorCount,
|
||||
errors: errors.length > 0 ? errors : undefined,
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error("Upload error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error.message || "Failed to upload CSV" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function findOrCreatePlayer(name: string) {
|
||||
// Try to find existing player with exact name match
|
||||
let player = await prisma.player.findFirst({
|
||||
where: { name },
|
||||
});
|
||||
|
||||
if (!player) {
|
||||
// Create a new player with a unique name
|
||||
const uniqueName = `${name}-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
|
||||
player = await prisma.player.create({
|
||||
data: {
|
||||
name: uniqueName,
|
||||
rating: 1000,
|
||||
currentElo: 1000,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return player;
|
||||
}
|
||||
|
||||
async function updatePlayerStats(playerId: number, won: boolean, eloChange: number) {
|
||||
// First, get the current player data to calculate the new values
|
||||
const player = await prisma.player.findUnique({
|
||||
where: { id: playerId },
|
||||
});
|
||||
|
||||
if (!player) {
|
||||
throw new Error(`Player ${playerId} not found`);
|
||||
}
|
||||
|
||||
// Update the player's statistics
|
||||
await prisma.player.update({
|
||||
where: { id: playerId },
|
||||
data: {
|
||||
currentElo: player.currentElo + Math.round(eloChange),
|
||||
gamesPlayed: player.gamesPlayed + 1,
|
||||
wins: won ? player.wins + 1 : player.wins,
|
||||
losses: won ? player.losses : player.losses + 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function updatePartnershipStats(player1Id: number, player2Id: number, won: boolean, eloChange: number) {
|
||||
// Sort IDs to ensure consistent partnership lookup
|
||||
const [smallId, largeId] = player1Id < player2Id ? [player1Id, player2Id] : [player2Id, player1Id];
|
||||
|
||||
// Find existing partnership
|
||||
const existing = await prisma.partnershipStat.findFirst({
|
||||
where: {
|
||||
player1Id: smallId,
|
||||
player2Id: largeId,
|
||||
},
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
// Update existing partnership
|
||||
await prisma.partnershipStat.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
gamesPlayed: { increment: 1 },
|
||||
wins: won ? { increment: 1 } : undefined,
|
||||
losses: won ? undefined : { increment: 1 },
|
||||
totalEloChange: { increment: eloChange },
|
||||
lastPlayed: new Date(),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
// Create new partnership
|
||||
await prisma.partnershipStat.create({
|
||||
data: {
|
||||
player1Id: smallId,
|
||||
player2Id: largeId,
|
||||
gamesPlayed: 1,
|
||||
wins: won ? 1 : 0,
|
||||
losses: won ? 0 : 1,
|
||||
totalEloChange: eloChange,
|
||||
lastPlayed: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { getTournamentStatus } from "@/lib/tournamentUtils";
|
||||
import { canCreateTournaments } from "@/lib/permissions";
|
||||
import { getSession } from "@/lib/auth-simple";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const tournaments = await prisma.event.findMany({
|
||||
where: { eventType: "tournament" },
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
participants: true,
|
||||
teams: {
|
||||
include: {
|
||||
player1: true,
|
||||
player2: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Update tournament statuses based on event date
|
||||
const updatedTournaments = await Promise.all(
|
||||
tournaments.map(async (tournament) => {
|
||||
const calculatedStatus = getTournamentStatus(tournament.eventDate);
|
||||
|
||||
// Only update if the calculated status differs from the stored status
|
||||
if (tournament.status !== calculatedStatus) {
|
||||
await prisma.event.update({
|
||||
where: { id: tournament.id },
|
||||
data: { status: calculatedStatus },
|
||||
});
|
||||
return { ...tournament, status: calculatedStatus };
|
||||
}
|
||||
|
||||
return tournament;
|
||||
})
|
||||
);
|
||||
|
||||
return NextResponse.json({ tournaments: updatedTournaments });
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch tournaments:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch tournaments" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
// Check if user has permission to create tournaments
|
||||
const permission = await canCreateTournaments();
|
||||
if (!permission.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: permission.reason || 'Insufficient permissions to create tournaments' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Get the current user to assign as owner
|
||||
const session = await getSession();
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'User not authenticated' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, format, eventDate } = body;
|
||||
|
||||
const tournament = await prisma.event.create({
|
||||
data: {
|
||||
name,
|
||||
format: format || "round_robin",
|
||||
eventDate: eventDate ? new Date(eventDate) : null,
|
||||
eventType: "tournament",
|
||||
status: "planned",
|
||||
ownerId: session.user.id, // Assign ownership to the creator
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({ tournament }, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error("Failed to create tournament:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to create tournament" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { getSession } from '@/lib/auth-simple';
|
||||
import { canAssignTournamentAdmin } from '@/lib/permissions';
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Users can only query their own role or if they're an admin
|
||||
// Fetch the requesting user's current role from database to avoid session cache issues
|
||||
const requestingUser = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
select: { role: true }
|
||||
});
|
||||
|
||||
if (!requestingUser) {
|
||||
return NextResponse.json({ error: 'Requesting user not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (session.user.id !== params.id && requestingUser.role !== 'club_admin') {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: params.id },
|
||||
select: { role: true }
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ role: user.role });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(
|
||||
request: NextRequest,
|
||||
{ params }: { params: { id: string } }
|
||||
) {
|
||||
try {
|
||||
// Check if the current user has permission to assign roles
|
||||
const permission = await canAssignTournamentAdmin();
|
||||
if (!permission.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: permission.reason || 'Insufficient permissions' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
const { role } = await request.json();
|
||||
|
||||
// Validate the role
|
||||
const validRoles = ['player', 'tournament_admin', 'club_admin'];
|
||||
if (!validRoles.includes(role)) {
|
||||
return NextResponse.json(
|
||||
{ error: `Invalid role. Must be one of: ${validRoles.join(', ')}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Update the user's role
|
||||
const updatedUser = await prisma.user.update({
|
||||
where: { id: params.id },
|
||||
data: { role }
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Role updated successfully',
|
||||
user: { id: updatedUser.id, email: updatedUser.email, role: updatedUser.role }
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to update user role:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to update user role" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
"use client"
|
||||
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useState } from "react"
|
||||
import { authClient } from "@/lib/auth-client"
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter()
|
||||
const [error, setError] = useState("")
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault()
|
||||
console.log("Login form submitted via JavaScript handler")
|
||||
setLoading(true)
|
||||
setError("")
|
||||
|
||||
const formData = new FormData(e.currentTarget)
|
||||
const email = formData.get("email") as string
|
||||
const password = formData.get("password") as string
|
||||
|
||||
try {
|
||||
const result = await authClient.signIn.email({
|
||||
email,
|
||||
password,
|
||||
})
|
||||
|
||||
if (result.error) {
|
||||
setError(result.error.message || "Failed to sign in")
|
||||
} else {
|
||||
// Navigate to admin page - Better Auth will handle session update
|
||||
router.push("/admin")
|
||||
}
|
||||
} catch (err) {
|
||||
setError("An unexpected error occurred")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-md w-full space-y-8">
|
||||
<div>
|
||||
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
|
||||
Sign in to your account
|
||||
</h2>
|
||||
</div>
|
||||
<form className="mt-8 space-y-6" method="POST" onSubmit={handleSubmit}>
|
||||
{error && (
|
||||
<div className="rounded-md bg-red-50 p-4">
|
||||
<div className="text-sm text-red-700">{error}</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="rounded-md shadow-sm -space-y-px">
|
||||
<div>
|
||||
<label htmlFor="email" className="sr-only">
|
||||
Email address
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-green-500 focus:border-green-500 focus:z-10 sm:text-sm"
|
||||
placeholder="Email address"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="password" className="sr-only">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-green-500 focus:border-green-500 focus:z-10 sm:text-sm"
|
||||
placeholder="Password"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? "Signing in..." : "Sign in"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-sm">
|
||||
<Link
|
||||
href="/auth/register"
|
||||
className="font-medium text-green-600 hover:text-green-500"
|
||||
>
|
||||
Create account
|
||||
</Link>
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
<Link
|
||||
href="/auth/password-reset"
|
||||
className="font-medium text-green-600 hover:text-green-500"
|
||||
>
|
||||
Forgot password?
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
"use client"
|
||||
|
||||
import Link from "next/link"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useState } from "react"
|
||||
import { authClient } from "@/lib/auth-client"
|
||||
import { useSession } from "@/components/SessionProvider"
|
||||
|
||||
export default function RegisterPage() {
|
||||
const router = useRouter()
|
||||
const { refreshSession } = useSession()
|
||||
const [error, setError] = useState("")
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
setError("")
|
||||
|
||||
const formData = new FormData(e.currentTarget)
|
||||
const name = formData.get("name") as string
|
||||
const email = formData.get("email") as string
|
||||
const password = formData.get("password") as string
|
||||
|
||||
try {
|
||||
console.log("Attempting signup...");
|
||||
const result = await authClient.signUp.email({
|
||||
email,
|
||||
password,
|
||||
name,
|
||||
})
|
||||
console.log("Signup result:", result);
|
||||
|
||||
if (result.error) {
|
||||
console.error("Signup error:", result.error);
|
||||
setError(result.error.message || "Failed to create account")
|
||||
} else {
|
||||
console.log("Signup successful, redirecting...");
|
||||
console.log("Result data:", result.data);
|
||||
// Refresh the session after successful registration
|
||||
try {
|
||||
await refreshSession()
|
||||
console.log("Session refreshed successfully");
|
||||
} catch (err) {
|
||||
console.error("Failed to refresh session:", err);
|
||||
}
|
||||
console.log("About to redirect to /admin");
|
||||
router.push("/admin")
|
||||
router.refresh()
|
||||
console.log("Redirect initiated");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Signup exception:", err);
|
||||
setError("An unexpected error occurred")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-md w-full space-y-8">
|
||||
<div>
|
||||
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
|
||||
Create your account
|
||||
</h2>
|
||||
</div>
|
||||
<form className="mt-8 space-y-6" method="POST" onSubmit={handleSubmit}>
|
||||
{error && (
|
||||
<div className="rounded-md bg-red-50 p-4">
|
||||
<div className="text-sm text-red-700">{error}</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="rounded-md shadow-sm -space-y-px">
|
||||
<div>
|
||||
<label htmlFor="name" className="sr-only">
|
||||
Full Name
|
||||
</label>
|
||||
<input
|
||||
id="name"
|
||||
name="name"
|
||||
type="text"
|
||||
required
|
||||
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-green-500 focus:border-green-500 focus:z-10 sm:text-sm"
|
||||
placeholder="Full Name"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="email" className="sr-only">
|
||||
Email address
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
required
|
||||
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-green-500 focus:border-green-500 focus:z-10 sm:text-sm"
|
||||
placeholder="Email address"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="password" className="sr-only">
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
required
|
||||
className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-green-500 focus:border-green-500 focus:z-10 sm:text-sm"
|
||||
placeholder="Password"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{loading ? "Creating..." : "Create Account"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="text-center text-sm">
|
||||
<Link
|
||||
href="/auth/login"
|
||||
className="font-medium text-green-600 hover:text-green-500"
|
||||
>
|
||||
Already have an account? Sign in
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
"use client"
|
||||
|
||||
export default function VerifyRequestPage() {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-md w-full space-y-8">
|
||||
<div>
|
||||
<h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
|
||||
Check your email
|
||||
</h2>
|
||||
<p className="mt-2 text-center text-sm text-gray-600">
|
||||
A sign in link has been sent to your email address.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
@@ -0,0 +1,26 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
--font-mono: 'Courier New', Courier, monospace;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Metadata } from "next";
|
||||
import "./globals.css";
|
||||
import { SessionProvider } from "@/components/SessionProvider";
|
||||
|
||||
const inter = {
|
||||
variable: "--font-inter",
|
||||
};
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "EuchreCamp - Tournament Management & Partnership Analytics",
|
||||
description: "Track your Euchre games, tournaments, and partnership performance",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html
|
||||
lang="en"
|
||||
className={`${inter.variable} h-full antialiased`}
|
||||
>
|
||||
<body className="min-h-full flex flex-col">
|
||||
<SessionProvider>
|
||||
{children}
|
||||
</SessionProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import Link from "next/link"
|
||||
|
||||
export default async function Home() {
|
||||
// Fetch top 10 players by Elo rating
|
||||
const topPlayers = await prisma.player.findMany({
|
||||
orderBy: { currentElo: "desc" },
|
||||
take: 10,
|
||||
include: {
|
||||
partnershipStats: true,
|
||||
partnershipStats2: true,
|
||||
},
|
||||
})
|
||||
|
||||
// Fetch most recent tournament
|
||||
const mostRecentTournament = await prisma.event.findFirst({
|
||||
where: {
|
||||
eventType: "tournament",
|
||||
status: { not: "draft" }
|
||||
},
|
||||
orderBy: { eventDate: "desc" },
|
||||
include: {
|
||||
matches: {
|
||||
include: {
|
||||
team1P1: true,
|
||||
team1P2: true,
|
||||
team2P1: true,
|
||||
team2P2: true,
|
||||
},
|
||||
orderBy: { playedAt: "desc" },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Fetch club president (first user with club_admin role)
|
||||
const clubPresident = await prisma.user.findFirst({
|
||||
where: { role: "club_admin" },
|
||||
select: { name: true, email: true },
|
||||
})
|
||||
|
||||
// Calculate win rates for top players
|
||||
const playersWithWinRates = topPlayers.map((player) => ({
|
||||
...player,
|
||||
winRate: player.gamesPlayed > 0
|
||||
? (player.wins / player.gamesPlayed) * 100
|
||||
: 0,
|
||||
}))
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-green-50 to-blue-50">
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
|
||||
{/* Header Section */}
|
||||
<div className="text-center mb-12">
|
||||
<h1 className="text-4xl md:text-5xl font-extrabold text-gray-900 mb-4">
|
||||
EuchreCamp
|
||||
</h1>
|
||||
<p className="text-xl text-gray-600 mb-8 max-w-3xl mx-auto">
|
||||
Track your Euchre games, tournaments, and partnership performance
|
||||
with our comprehensive tournament management system.
|
||||
</p>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-4 justify-center">
|
||||
<Link
|
||||
href="/auth/login"
|
||||
className="px-8 py-3 bg-green-600 text-white rounded-lg font-semibold hover:bg-green-700 transition-colors"
|
||||
>
|
||||
Sign In
|
||||
</Link>
|
||||
<Link
|
||||
href="/auth/register"
|
||||
className="px-8 py-3 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
Create Account
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Top 10 Players Section */}
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-8">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">
|
||||
Top 10 Players
|
||||
</h2>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Rank
|
||||
</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Player
|
||||
</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Elo Rating
|
||||
</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Games
|
||||
</th>
|
||||
<th className="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Win Rate
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{playersWithWinRates.map((player, index) => (
|
||||
<tr key={player.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-2 whitespace-nowrap text-sm font-medium text-gray-900">
|
||||
{index + 1}
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap">
|
||||
<Link
|
||||
href={`/players/${player.id}/profile`}
|
||||
className="text-green-600 hover:text-green-900"
|
||||
>
|
||||
{player.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap text-sm text-gray-900">
|
||||
{player.currentElo}
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
|
||||
{player.gamesPlayed}
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap text-sm text-gray-500">
|
||||
{player.gamesPlayed > 0
|
||||
? `${player.winRate.toFixed(1)}%`
|
||||
: "N/A"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="mt-4 text-center">
|
||||
<Link
|
||||
href="/rankings"
|
||||
className="text-green-600 hover:text-green-900 font-medium"
|
||||
>
|
||||
View Full Rankings →
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Most Recent Tournament Section */}
|
||||
{mostRecentTournament && (
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-8">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">
|
||||
Most Recent Tournament
|
||||
</h2>
|
||||
<div className="mb-4">
|
||||
<h3 className="text-xl font-semibold text-gray-800">
|
||||
{mostRecentTournament.name}
|
||||
</h3>
|
||||
{mostRecentTournament.eventDate && (
|
||||
<p className="text-gray-600">
|
||||
{new Date(mostRecentTournament.eventDate).toLocaleDateString()}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-gray-500">
|
||||
Status: {mostRecentTournament.status}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Tournament Matches */}
|
||||
<div className="mt-6">
|
||||
<h4 className="text-lg font-medium text-gray-900 mb-3">
|
||||
Matches ({mostRecentTournament.matches.length})
|
||||
</h4>
|
||||
<div className="space-y-3 max-h-96 overflow-y-auto">
|
||||
{mostRecentTournament.matches.map((match) => (
|
||||
<div
|
||||
key={match.id}
|
||||
className="bg-gray-50 rounded-lg p-4 border border-gray-200"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex-1 text-center">
|
||||
<div className="text-sm font-medium text-gray-900">
|
||||
{match.team1P1.name} & {match.team1P2.name}
|
||||
</div>
|
||||
<div className="text-lg font-bold text-gray-800">
|
||||
{match.team1Score}
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-3 text-gray-500">vs</div>
|
||||
<div className="flex-1 text-center">
|
||||
<div className="text-sm font-medium text-gray-900">
|
||||
{match.team2P1.name} & {match.team2P2.name}
|
||||
</div>
|
||||
<div className="text-lg font-bold text-gray-800">
|
||||
{match.team2Score}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 text-center text-sm text-gray-500">
|
||||
{match.playedAt && (
|
||||
<span>
|
||||
{new Date(match.playedAt).toLocaleDateString()} at{' '}
|
||||
{new Date(match.playedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Club President Section */}
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">
|
||||
Club Information
|
||||
</h2>
|
||||
<div className="flex items-center">
|
||||
<div className="flex-shrink-0">
|
||||
<div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-4">
|
||||
<h3 className="text-lg font-medium text-gray-900">Club President</h3>
|
||||
<p className="text-gray-600">
|
||||
{clubPresident?.name || clubPresident?.email || "Not assigned"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import Navigation from "@/components/Navigation"
|
||||
import Link from "next/link"
|
||||
import { notFound } from "next/navigation"
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
id: string
|
||||
}
|
||||
}
|
||||
|
||||
export default async function PlayerProfilePage({ params }: PageProps) {
|
||||
const playerId = parseInt(params.id)
|
||||
|
||||
const player = await prisma.player.findUnique({
|
||||
where: { id: playerId },
|
||||
})
|
||||
|
||||
if (!player) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
// Get partnership stats separately
|
||||
const partnershipStats = await prisma.partnershipStat.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ player1Id: playerId },
|
||||
{ player2Id: playerId },
|
||||
],
|
||||
},
|
||||
include: {
|
||||
player1: true,
|
||||
player2: true,
|
||||
},
|
||||
orderBy: { gamesPlayed: "desc" },
|
||||
})
|
||||
|
||||
// Use direct player stats for overall statistics (more accurate and consistent with rankings page)
|
||||
const totalGames = player.gamesPlayed
|
||||
const totalWins = player.wins
|
||||
const winRate = totalGames > 0 ? ((totalWins / totalGames) * 100).toFixed(1) : "0.0"
|
||||
|
||||
// Get best partnership
|
||||
const bestPartnership = partnershipStats.reduce((best, stat) => {
|
||||
if (stat.gamesPlayed < 3) return best // Need at least 3 games for partnership to be meaningful
|
||||
const currentRate = stat.wins / stat.gamesPlayed
|
||||
const bestRate = best ? best.wins / best.gamesPlayed : 0
|
||||
return currentRate > bestRate ? stat : best
|
||||
}, null as (typeof partnershipStats[0] | null))
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
{/* Player Header */}
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<div className="flex items-center">
|
||||
<div className="h-20 w-20 bg-green-100 rounded-full flex items-center justify-center text-green-800 text-2xl font-bold">
|
||||
{player.name.charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div className="ml-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">{player.name}</h1>
|
||||
<p className="text-gray-500">
|
||||
Member since {new Date(player.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats Grid */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6">
|
||||
<div className="bg-gray-50 rounded-lg p-4 text-center">
|
||||
<p className="text-sm text-gray-500">Current Elo</p>
|
||||
<p className="text-2xl font-bold text-gray-900">{player.currentElo}</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 rounded-lg p-4 text-center">
|
||||
<p className="text-sm text-gray-500">Total Games</p>
|
||||
<p className="text-2xl font-bold text-gray-900">{totalGames}</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 rounded-lg p-4 text-center">
|
||||
<p className="text-sm text-gray-500">Win Rate</p>
|
||||
<p className="text-2xl font-bold text-gray-900">{winRate}%</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 rounded-lg p-4 text-center">
|
||||
<p className="text-sm text-gray-500">Best Partner</p>
|
||||
<p className="text-lg font-bold text-gray-900">
|
||||
{bestPartnership
|
||||
? (bestPartnership.player1Id === player.id
|
||||
? bestPartnership.player2.name
|
||||
: bestPartnership.player1.name)
|
||||
: "N/A"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Partnership Performance */}
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-xl font-bold text-gray-900 mb-4">
|
||||
Partnership Performance
|
||||
</h2>
|
||||
|
||||
{partnershipStats.length === 0 ? (
|
||||
<p className="text-gray-500">No partnership data available yet.</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Partner
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Games
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Win Rate
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
ELO Change
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Last Played
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{partnershipStats.map((stat) => {
|
||||
const partner =
|
||||
stat.player1Id === player.id ? stat.player2 : stat.player1
|
||||
const winRate = stat.gamesPlayed > 0
|
||||
? ((stat.wins / stat.gamesPlayed) * 100).toFixed(1)
|
||||
: "0.0"
|
||||
|
||||
return (
|
||||
<tr key={stat.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<Link
|
||||
href={`/players/${partner.id}/profile`}
|
||||
className="text-green-600 hover:text-green-900"
|
||||
>
|
||||
{partner.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
|
||||
{stat.gamesPlayed}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{winRate}%
|
||||
</td>
|
||||
<td className={`px-6 py-4 whitespace-nowrap text-sm ${
|
||||
stat.totalEloChange >= 0 ? 'text-green-600' : 'text-red-600'
|
||||
}`}>
|
||||
{stat.totalEloChange >= 0 ? '+' : ''}{stat.totalEloChange}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{stat.lastPlayed
|
||||
? new Date(stat.lastPlayed).toLocaleDateString()
|
||||
: "N/A"}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import Navigation from "@/components/Navigation"
|
||||
import Link from "next/link"
|
||||
import { notFound } from "next/navigation"
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
id: string
|
||||
}
|
||||
}
|
||||
|
||||
export default async function PlayerSchedulePage({ params }: PageProps) {
|
||||
const playerId = parseInt(params.id)
|
||||
|
||||
const player = await prisma.player.findUnique({
|
||||
where: { id: playerId },
|
||||
include: {
|
||||
// Get upcoming matches
|
||||
matchesAsP1: {
|
||||
where: { playedAt: { gte: new Date() } },
|
||||
include: {
|
||||
event: true,
|
||||
team1P1: true,
|
||||
team1P2: true,
|
||||
team2P1: true,
|
||||
team2P2: true,
|
||||
},
|
||||
orderBy: { playedAt: "asc" },
|
||||
},
|
||||
matchesAsP2: {
|
||||
where: { playedAt: { gte: new Date() } },
|
||||
include: {
|
||||
event: true,
|
||||
team1P1: true,
|
||||
team1P2: true,
|
||||
team2P1: true,
|
||||
team2P2: true,
|
||||
},
|
||||
orderBy: { playedAt: "asc" },
|
||||
},
|
||||
matchesAsP3: {
|
||||
where: { playedAt: { gte: new Date() } },
|
||||
include: {
|
||||
event: true,
|
||||
team1P1: true,
|
||||
team1P2: true,
|
||||
team2P1: true,
|
||||
team2P2: true,
|
||||
},
|
||||
orderBy: { playedAt: "asc" },
|
||||
},
|
||||
matchesAsP4: {
|
||||
where: { playedAt: { gte: new Date() } },
|
||||
include: {
|
||||
event: true,
|
||||
team1P1: true,
|
||||
team1P2: true,
|
||||
team2P1: true,
|
||||
team2P2: true,
|
||||
},
|
||||
orderBy: { playedAt: "asc" },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!player) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
// Combine all upcoming matches
|
||||
const upcomingMatches = [
|
||||
...player.matchesAsP1,
|
||||
...player.matchesAsP2,
|
||||
...player.matchesAsP3,
|
||||
...player.matchesAsP4,
|
||||
].sort((a, b) => new Date(a.playedAt!).getTime() - new Date(b.playedAt!).getTime())
|
||||
|
||||
// Get active tournaments (events with status 'active' or 'in_progress')
|
||||
const activeTournaments = await prisma.event.findMany({
|
||||
where: {
|
||||
status: { in: ['active', 'in_progress', 'started'] },
|
||||
participants: {
|
||||
some: {
|
||||
playerId: playerId,
|
||||
},
|
||||
},
|
||||
},
|
||||
include: {
|
||||
participants: true,
|
||||
teams: {
|
||||
include: {
|
||||
player1: true,
|
||||
player2: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-6">
|
||||
My Schedule
|
||||
</h1>
|
||||
|
||||
{/* Upcoming Matches */}
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<h2 className="text-xl font-bold text-gray-900 mb-4">
|
||||
Upcoming Matches
|
||||
</h2>
|
||||
|
||||
{upcomingMatches.length === 0 ? (
|
||||
<p className="text-gray-500">No upcoming matches scheduled.</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{upcomingMatches.map((match) => {
|
||||
const team1Players = [
|
||||
match.team1P1.name,
|
||||
match.team1P2.name,
|
||||
].join(" + ")
|
||||
const team2Players = [
|
||||
match.team2P1.name,
|
||||
match.team2P2.name,
|
||||
].join(" + ")
|
||||
|
||||
return (
|
||||
<div
|
||||
key={match.id}
|
||||
className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex-1">
|
||||
<p className="text-sm text-gray-500">
|
||||
{match.event?.name || "Tournament"} - {match.playedAt?.toLocaleDateString()}
|
||||
</p>
|
||||
<p className="font-medium">
|
||||
{team1Players} vs {team2Players}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
<span className="text-gray-400">
|
||||
{match.playedAt?.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Active Tournaments */}
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-xl font-bold text-gray-900 mb-4">
|
||||
Active Tournaments
|
||||
</h2>
|
||||
|
||||
{activeTournaments.length === 0 ? (
|
||||
<p className="text-gray-500">No active tournaments.</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{activeTournaments.map((tournament) => {
|
||||
const playerTeam = tournament.teams.find(
|
||||
(team) =>
|
||||
team.player1Id === playerId || team.player2Id === playerId
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={tournament.id}
|
||||
className="border border-gray-200 rounded-lg p-4 hover:bg-gray-50"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<Link
|
||||
href={`/tournaments/${tournament.id}`}
|
||||
className="font-medium text-green-600 hover:text-green-900"
|
||||
>
|
||||
{tournament.name}
|
||||
</Link>
|
||||
<p className="text-sm text-gray-500">
|
||||
{tournament.format} - {tournament.status}
|
||||
</p>
|
||||
{playerTeam && (
|
||||
<p className="text-sm text-gray-600">
|
||||
Team: {playerTeam.player1.name} + {playerTeam.player2.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<p className="text-sm text-gray-500">
|
||||
{new Date(tournament.eventDate || tournament.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import Navigation from "@/components/Navigation"
|
||||
import Link from "next/link"
|
||||
|
||||
export default async function RankingsPage() {
|
||||
// Fetch players ordered by Elo rating
|
||||
const players = await prisma.player.findMany({
|
||||
orderBy: { currentElo: "desc" },
|
||||
take: 50,
|
||||
include: {
|
||||
partnershipStats: true,
|
||||
partnershipStats2: true,
|
||||
},
|
||||
})
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-6">
|
||||
Player Rankings
|
||||
</h1>
|
||||
|
||||
<div className="bg-white shadow overflow-hidden sm:rounded-lg">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Rank
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Player
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Elo Rating
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Games Played
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
|
||||
Win Rate
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{players.map((player, index) => (
|
||||
<tr key={player.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
|
||||
{index + 1}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<Link
|
||||
href={`/players/${player.id}/profile`}
|
||||
className="text-green-600 hover:text-green-900"
|
||||
>
|
||||
{player.name}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
|
||||
{player.currentElo}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{player.gamesPlayed}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
|
||||
{player.gamesPlayed > 0
|
||||
? `${((player.wins / player.gamesPlayed) * 100).toFixed(1)}%`
|
||||
: "N/A"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
'use client';
|
||||
import { authClient } from '@/lib/auth-client';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export default function TestApi() {
|
||||
const [result, setResult] = useState<any>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
async function test() {
|
||||
try {
|
||||
const response = await authClient.signIn.email({
|
||||
email: 'david@dhg.lol',
|
||||
password: 'admin1234'
|
||||
});
|
||||
setResult(response);
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
}
|
||||
test();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div style={{ padding: '2rem' }}>
|
||||
<h1>Test Auth API</h1>
|
||||
{error && <p style={{ color: 'red' }}>Error: {error}</p>}
|
||||
{result && <pre>{JSON.stringify(result, null, 2)}</pre>}
|
||||
{!result && !error && <p>Loading...</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Link from "next/link"
|
||||
import type { Event } from "@prisma/client"
|
||||
|
||||
interface EditTournamentFormProps {
|
||||
tournament: Event
|
||||
}
|
||||
|
||||
export default function EditTournamentForm({ tournament }: EditTournamentFormProps) {
|
||||
const router = useRouter()
|
||||
const [formData, setFormData] = useState({
|
||||
name: tournament.name,
|
||||
description: tournament.description || "",
|
||||
eventDate: tournament.eventDate ? tournament.eventDate.toISOString().split('T')[0] : "",
|
||||
eventType: tournament.eventType,
|
||||
format: tournament.format,
|
||||
status: tournament.status,
|
||||
maxParticipants: tournament.maxParticipants?.toString() || "",
|
||||
})
|
||||
const [error, setError] = useState("")
|
||||
const [success, setSuccess] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
|
||||
const { name, value } = e.target
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[name]: value,
|
||||
}))
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError("")
|
||||
setSuccess("")
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/tournaments/${tournament.id}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...formData,
|
||||
maxParticipants: formData.maxParticipants ? parseInt(formData.maxParticipants) : null,
|
||||
eventDate: formData.eventDate ? new Date(formData.eventDate).toISOString() : null,
|
||||
}),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
setError(data.error || "Failed to update tournament")
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setSuccess("Tournament updated successfully!")
|
||||
setIsLoading(false)
|
||||
|
||||
// Redirect to tournament detail after 2 seconds
|
||||
setTimeout(() => {
|
||||
router.push(`/admin/tournaments/${tournament.id}`)
|
||||
}, 2000)
|
||||
} catch (err) {
|
||||
setError("An error occurred. Please try again.")
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{error && (
|
||||
<div className="rounded-md bg-red-50 p-4">
|
||||
<div className="text-sm text-red-700">{error}</div>
|
||||
</div>
|
||||
)}
|
||||
{success && (
|
||||
<div className="rounded-md bg-green-50 p-4">
|
||||
<div className="text-sm text-green-700">{success}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<label htmlFor="name" className="block text-sm font-medium text-gray-700">
|
||||
Tournament Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="name"
|
||||
name="name"
|
||||
required
|
||||
value={formData.name}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="eventDate" className="block text-sm font-medium text-gray-700">
|
||||
Date
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
id="eventDate"
|
||||
name="eventDate"
|
||||
value={formData.eventDate}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="description" className="block text-sm font-medium text-gray-700">
|
||||
Description
|
||||
</label>
|
||||
<textarea
|
||||
id="description"
|
||||
name="description"
|
||||
rows={3}
|
||||
value={formData.description}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<div>
|
||||
<label htmlFor="eventType" className="block text-sm font-medium text-gray-700">
|
||||
Event Type
|
||||
</label>
|
||||
<select
|
||||
id="eventType"
|
||||
name="eventType"
|
||||
value={formData.eventType}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
>
|
||||
<option value="tournament">Tournament</option>
|
||||
<option value="league">League</option>
|
||||
<option value="casual">Casual Play</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="format" className="block text-sm font-medium text-gray-700">
|
||||
Format
|
||||
</label>
|
||||
<select
|
||||
id="format"
|
||||
name="format"
|
||||
value={formData.format}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
>
|
||||
<option value="round_robin">Round Robin</option>
|
||||
<option value="single_elimination">Single Elimination</option>
|
||||
<option value="double_elimination">Double Elimination</option>
|
||||
<option value="swiss">Swiss</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="status" className="block text-sm font-medium text-gray-700">
|
||||
Status
|
||||
</label>
|
||||
<select
|
||||
id="status"
|
||||
name="status"
|
||||
value={formData.status}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
>
|
||||
<option value="planned">Planned</option>
|
||||
<option value="registration">Registration Open</option>
|
||||
<option value="in_progress">In Progress</option>
|
||||
<option value="completed">Completed</option>
|
||||
<option value="cancelled">Cancelled</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="maxParticipants" className="block text-sm font-medium text-gray-700">
|
||||
Max Participants (optional)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
id="maxParticipants"
|
||||
name="maxParticipants"
|
||||
min="1"
|
||||
value={formData.maxParticipants}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-4">
|
||||
<Link
|
||||
href={`/admin/tournaments/${tournament.id}`}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
|
||||
>
|
||||
Cancel
|
||||
</Link>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? "Saving..." : "Save Changes"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import type { Player, Match } from "@prisma/client"
|
||||
|
||||
interface MatchEditorProps {
|
||||
tournamentId: number
|
||||
players: Player[]
|
||||
matches: Match[]
|
||||
}
|
||||
|
||||
interface MatchData {
|
||||
team1P1Id: number | null
|
||||
team1P2Id: number | null
|
||||
team2P1Id: number | null
|
||||
team2P2Id: number | null
|
||||
team1Score: number
|
||||
team2Score: number
|
||||
round: number
|
||||
table: string
|
||||
}
|
||||
|
||||
export default function MatchEditor({ tournamentId, players, matches }: MatchEditorProps) {
|
||||
const [formData, setFormData] = useState<MatchData>({
|
||||
team1P1Id: null,
|
||||
team1P2Id: null,
|
||||
team2P1Id: null,
|
||||
team2P2Id: null,
|
||||
team1Score: 0,
|
||||
team2Score: 0,
|
||||
round: 1,
|
||||
table: "Clubs",
|
||||
})
|
||||
const [error, setError] = useState("")
|
||||
const [success, setSuccess] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const tables = ["Clubs", "Hearts", "Diamonds", "Spades", "Stars"]
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLSelectElement | HTMLInputElement>) => {
|
||||
const { name, value } = e.target
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
[name]: name.includes("Id") ? (value ? parseInt(value) : null) :
|
||||
name === "round" ? parseInt(value) :
|
||||
name === "team1Score" || name === "team2Score" ? parseInt(value) :
|
||||
value,
|
||||
}))
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError("")
|
||||
setSuccess("")
|
||||
|
||||
// Validate that all players are selected
|
||||
if (!formData.team1P1Id || !formData.team1P2Id || !formData.team2P1Id || !formData.team2P2Id) {
|
||||
setError("Please select all 4 players")
|
||||
return
|
||||
}
|
||||
|
||||
// Validate that players are unique
|
||||
const playerIds = [formData.team1P1Id, formData.team1P2Id, formData.team2P1Id, formData.team2P2Id]
|
||||
if (new Set(playerIds).size !== 4) {
|
||||
setError("All players must be unique")
|
||||
return
|
||||
}
|
||||
|
||||
// Validate scores (at least one team must have points)
|
||||
if (formData.team1Score === 0 && formData.team2Score === 0) {
|
||||
setError("At least one team must have points")
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/matches", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
eventId: tournamentId,
|
||||
team1P1Id: formData.team1P1Id,
|
||||
team1P2Id: formData.team1P2Id,
|
||||
team2P1Id: formData.team2P1Id,
|
||||
team2P2Id: formData.team2P2Id,
|
||||
team1Score: formData.team1Score,
|
||||
team2Score: formData.team2Score,
|
||||
round: formData.round,
|
||||
table: formData.table,
|
||||
}),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
setError(data.error || "Failed to record match")
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setSuccess("Match recorded successfully!")
|
||||
setIsLoading(false)
|
||||
|
||||
// Reset form
|
||||
setFormData({
|
||||
team1P1Id: null,
|
||||
team1P2Id: null,
|
||||
team2P1Id: null,
|
||||
team2P2Id: null,
|
||||
team1Score: 0,
|
||||
team2Score: 0,
|
||||
round: formData.round,
|
||||
table: formData.table,
|
||||
})
|
||||
|
||||
// Reload the page to show updated matches
|
||||
setTimeout(() => {
|
||||
window.location.reload()
|
||||
}, 1000)
|
||||
} catch (err) {
|
||||
setError("An error occurred. Please try again.")
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{error && (
|
||||
<div className="rounded-md bg-red-50 p-4">
|
||||
<div className="text-sm text-red-700">{error}</div>
|
||||
</div>
|
||||
)}
|
||||
{success && (
|
||||
<div className="rounded-md bg-green-50 p-4">
|
||||
<div className="text-sm text-green-700">{success}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Round and Table Selection */}
|
||||
<div className="grid grid-cols-2 gap-6">
|
||||
<div>
|
||||
<label htmlFor="round" className="block text-sm font-medium text-gray-700">
|
||||
Round
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
id="round"
|
||||
name="round"
|
||||
min="1"
|
||||
value={formData.round}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="table" className="block text-sm font-medium text-gray-700">
|
||||
Table
|
||||
</label>
|
||||
<select
|
||||
id="table"
|
||||
name="table"
|
||||
value={formData.table}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
>
|
||||
{tables.map((table) => (
|
||||
<option key={table} value={table}>{table}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Team 1 */}
|
||||
<div className="border border-gray-200 rounded-lg p-4">
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-4">Team 1 (Odds)</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label htmlFor="team1P1Id" className="block text-sm font-medium text-gray-700">
|
||||
Player 1
|
||||
</label>
|
||||
<select
|
||||
id="team1P1Id"
|
||||
name="team1P1Id"
|
||||
value={formData.team1P1Id || ""}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Select player...</option>
|
||||
{players.map((player) => (
|
||||
<option key={player.id} value={player.id}>{player.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="team1P2Id" className="block text-sm font-medium text-gray-700">
|
||||
Player 2
|
||||
</label>
|
||||
<select
|
||||
id="team1P2Id"
|
||||
name="team1P2Id"
|
||||
value={formData.team1P2Id || ""}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Select player...</option>
|
||||
{players.map((player) => (
|
||||
<option key={player.id} value={player.id}>{player.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<label htmlFor="team1Score" className="block text-sm font-medium text-gray-700">
|
||||
Score
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
id="team1Score"
|
||||
name="team1Score"
|
||||
min="0"
|
||||
max="10"
|
||||
value={formData.team1Score}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Team 2 */}
|
||||
<div className="border border-gray-200 rounded-lg p-4">
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-4">Team 2 (Evens)</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label htmlFor="team2P1Id" className="block text-sm font-medium text-gray-700">
|
||||
Player 1
|
||||
</label>
|
||||
<select
|
||||
id="team2P1Id"
|
||||
name="team2P1Id"
|
||||
value={formData.team2P1Id || ""}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Select player...</option>
|
||||
{players.map((player) => (
|
||||
<option key={player.id} value={player.id}>{player.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="team2P2Id" className="block text-sm font-medium text-gray-700">
|
||||
Player 2
|
||||
</label>
|
||||
<select
|
||||
id="team2P2Id"
|
||||
name="team2P2Id"
|
||||
value={formData.team2P2Id || ""}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Select player...</option>
|
||||
{players.map((player) => (
|
||||
<option key={player.id} value={player.id}>{player.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<label htmlFor="team2Score" className="block text-sm font-medium text-gray-700">
|
||||
Score
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
id="team2Score"
|
||||
name="team2Score"
|
||||
min="0"
|
||||
max="10"
|
||||
value={formData.team2Score}
|
||||
onChange={handleChange}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-green-500 focus:ring-green-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? "Recording..." : "Record Match"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
"use client"
|
||||
|
||||
import Link from "next/link"
|
||||
import { useSession } from "./SessionProvider"
|
||||
import { authClient } from "@/lib/auth-client"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
export default function Navigation() {
|
||||
const { session, loading } = useSession()
|
||||
const [userRole, setUserRole] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Fetch user role from database if session exists
|
||||
if (session?.user?.id) {
|
||||
fetch(`/api/users/${session.user.id}/role`)
|
||||
.then(res => res.json())
|
||||
.then(data => setUserRole(data.role))
|
||||
.catch(() => setUserRole(null));
|
||||
}
|
||||
}, [session]);
|
||||
|
||||
const handleLogout = async () => {
|
||||
await authClient.signOut()
|
||||
window.location.href = '/auth/login'
|
||||
}
|
||||
|
||||
return (
|
||||
<nav className="bg-white shadow-sm">
|
||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||
<div className="flex justify-between h-16">
|
||||
<div className="flex items-center">
|
||||
<Link href="/" className="text-xl font-bold text-gray-900">
|
||||
EuchreCamp
|
||||
</Link>
|
||||
<div className="hidden md:ml-6 md:flex md:space-x-8">
|
||||
<Link
|
||||
href="/rankings"
|
||||
className="border-transparent text-gray-500 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
|
||||
>
|
||||
Rankings
|
||||
</Link>
|
||||
{session && (
|
||||
<>
|
||||
<Link
|
||||
href="/admin/tournaments"
|
||||
className="border-transparent text-gray-500 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
|
||||
>
|
||||
Tournaments
|
||||
</Link>
|
||||
{userRole === "club_admin" && (
|
||||
<Link
|
||||
href="/admin"
|
||||
className="border-transparent text-gray-500 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium"
|
||||
>
|
||||
Admin
|
||||
</Link>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
{loading ? (
|
||||
<div className="text-gray-500">Loading...</div>
|
||||
) : session ? (
|
||||
<div className="flex items-center space-x-4">
|
||||
<span className="text-gray-700 text-sm font-medium">
|
||||
{session.user?.name || session.user?.email}
|
||||
</span>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="text-gray-500 hover:text-gray-700 text-sm font-medium"
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center space-x-4">
|
||||
<Link
|
||||
href="/auth/login"
|
||||
className="text-gray-500 hover:text-gray-700 text-sm font-medium"
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
<Link
|
||||
href="/auth/register"
|
||||
className="bg-green-600 text-white px-3 py-1 rounded-md text-sm font-medium hover:bg-green-700"
|
||||
>
|
||||
Sign up
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
"use client"
|
||||
|
||||
import { createContext, useContext, useEffect, useState } from "react"
|
||||
import { authClient } from "@/lib/auth-client"
|
||||
|
||||
interface SessionContextType {
|
||||
session: { user: any; session: any } | null
|
||||
loading: boolean
|
||||
refreshSession: () => Promise<void>
|
||||
}
|
||||
|
||||
const SessionContext = createContext<SessionContextType | undefined>(undefined)
|
||||
|
||||
export function SessionProvider({ children }: { children: React.ReactNode }) {
|
||||
const [session, setSession] = useState<{ user: any; session: any } | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const refreshSession = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const result = await authClient.getSession()
|
||||
if (result.data) {
|
||||
setSession(result.data)
|
||||
} else {
|
||||
setSession(null)
|
||||
}
|
||||
} catch {
|
||||
setSession(null)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Initial session fetch - only run once on mount
|
||||
useEffect(() => {
|
||||
refreshSession()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
// Listen for session changes from Better Auth
|
||||
useEffect(() => {
|
||||
// Better Auth dispatches custom events when session changes
|
||||
const handleSessionChange = (event: Event) => {
|
||||
// Check if this is a session change event
|
||||
const customEvent = event as CustomEvent
|
||||
if (customEvent.detail?.session !== undefined) {
|
||||
// Session was updated
|
||||
if (customEvent.detail.session) {
|
||||
setSession(customEvent.detail.session)
|
||||
} else {
|
||||
setSession(null)
|
||||
}
|
||||
} else {
|
||||
// Fallback: refresh session from server
|
||||
refreshSession()
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for Better Auth's session change events
|
||||
window.addEventListener('better-auth:session', handleSessionChange as EventListener)
|
||||
|
||||
// Also listen for storage events for cross-tab communication
|
||||
window.addEventListener('storage', (e) => {
|
||||
if (e.key === 'better-auth.session_token') {
|
||||
refreshSession()
|
||||
}
|
||||
})
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('better-auth:session', handleSessionChange as EventListener)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<SessionContext.Provider value={{ session, loading, refreshSession }}>
|
||||
{children}
|
||||
</SessionContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useSession() {
|
||||
const context = useContext(SessionContext)
|
||||
if (!context) {
|
||||
throw new Error("useSession must be used within SessionProvider")
|
||||
}
|
||||
return context
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { createAuthClient } from "better-auth/client";
|
||||
|
||||
// Get base URL from environment or use localhost as fallback
|
||||
const getBaseURL = () => {
|
||||
if (typeof window === 'undefined') {
|
||||
return process.env.BETTER_AUTH_URL || "http://localhost:3000";
|
||||
}
|
||||
|
||||
// For client-side, use the current origin but allow localhost variations
|
||||
const origin = window.location.origin;
|
||||
if (origin.includes('localhost') || origin.includes('127.0.0.1') || origin.includes('0.0.0.0')) {
|
||||
return "http://localhost:3000"; // Normalize to localhost for Better Auth
|
||||
}
|
||||
|
||||
return origin;
|
||||
};
|
||||
|
||||
export const authClient = createAuthClient({
|
||||
baseURL: getBaseURL(),
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Server-side session helper for Better Auth
|
||||
* This provides getSession() for use in server components
|
||||
*/
|
||||
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
export async function getSession() {
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
|
||||
// Get the session token from cookies
|
||||
const sessionToken = cookieStore.get('better-auth.session_token');
|
||||
|
||||
if (!sessionToken) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Make a request to the Better Auth API to get the session
|
||||
// This is the standard way Better Auth handles session verification
|
||||
// Use disableCookieCache to bypass the cookie cache and get fresh data from the database
|
||||
const response = await fetch(`${process.env.BETTER_AUTH_URL || 'http://localhost:3000'}/api/auth/get-session?disableCookieCache=true`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Cookie': `${sessionToken.name}=${sessionToken.value}`
|
||||
},
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error('Failed to get session:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// For backward compatibility with existing code
|
||||
export type AuthUser = {
|
||||
user: {
|
||||
id: string;
|
||||
email: string;
|
||||
name?: string;
|
||||
role?: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
session: {
|
||||
token: string;
|
||||
expiresAt: Date;
|
||||
[key: string]: any;
|
||||
};
|
||||
} | null;
|
||||
@@ -0,0 +1,58 @@
|
||||
import { betterAuth } from "better-auth";
|
||||
import { prismaAdapter } from "better-auth/adapters/prisma";
|
||||
import { prisma } from "./prisma";
|
||||
import { testUtils } from "better-auth/plugins";
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: prismaAdapter(prisma, {
|
||||
provider: "sqlite",
|
||||
}),
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
autoSignIn: true, // Automatically sign in after registration
|
||||
requireEmailVerification: false, // Don't require email verification for tests
|
||||
},
|
||||
secret: process.env.BETTER_AUTH_SECRET,
|
||||
baseURL: process.env.BETTER_AUTH_URL || "http://localhost:3000",
|
||||
trustedOrigins: [
|
||||
process.env.BETTER_AUTH_URL || "http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
"http://0.0.0.0:3000",
|
||||
],
|
||||
session: {
|
||||
cookieCache: {
|
||||
enabled: false, // Disable cookie cache to avoid session cache issues
|
||||
},
|
||||
},
|
||||
|
||||
databaseHooks: {
|
||||
user: {
|
||||
create: {
|
||||
async after(user) {
|
||||
// Generate a unique player name using timestamp and random string
|
||||
const timestamp = Date.now();
|
||||
const randomId = Math.random().toString(36).substring(2, 8);
|
||||
const baseName = user.name || user.email.split('@')[0];
|
||||
const uniqueName = `${baseName}-${timestamp}-${randomId}`;
|
||||
|
||||
// Create a Player record for the new user
|
||||
const newPlayer = await prisma.player.create({
|
||||
data: {
|
||||
name: uniqueName,
|
||||
},
|
||||
});
|
||||
|
||||
// Update the User with the playerId
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { playerId: newPlayer.id },
|
||||
});
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
plugins: [
|
||||
testUtils()
|
||||
]
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Elo Rating Utilities
|
||||
*
|
||||
* Provides functions for calculating Elo ratings and changes
|
||||
* Based on the standard Elo rating system
|
||||
*/
|
||||
|
||||
/**
|
||||
* Calculate the expected score for a player based on rating difference
|
||||
* @param ratingA Player A's rating
|
||||
* @param ratingB Player B's rating
|
||||
* @returns Expected score (0-1) for Player A
|
||||
*/
|
||||
export function calculateExpectedScore(ratingA: number, ratingB: number): number {
|
||||
const ratingDiff = ratingA - ratingB;
|
||||
return 1 / (1 + Math.pow(10, -ratingDiff / 400));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Elo rating change for a single game
|
||||
* @param rating Player's current rating
|
||||
* @param opponentRating Opponent's rating
|
||||
* @param actualScore Actual score (1 = win, 0.5 = draw, 0 = loss)
|
||||
* @param kFactor K-factor (how much ratings change per game)
|
||||
* @returns Elo rating change (positive or negative)
|
||||
*/
|
||||
export function calculateEloChange(
|
||||
rating: number,
|
||||
opponentRating: number,
|
||||
actualScore: number,
|
||||
kFactor: number = 32
|
||||
): number {
|
||||
const expectedScore = calculateExpectedScore(rating, opponentRating);
|
||||
return kFactor * (actualScore - expectedScore);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate team Elo rating as average of individual ratings
|
||||
* @param rating1 Rating of player 1
|
||||
* @param rating2 Rating of player 2
|
||||
* @returns Team rating
|
||||
*/
|
||||
export function calculateTeamElo(rating1: number, rating2: number): number {
|
||||
return (rating1 + rating2) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update player statistics after a match
|
||||
* @param currentRating Current player rating
|
||||
* @param currentGamesPlayed Current games played count
|
||||
* @param currentWins Current wins count
|
||||
* @param eloChange Elo rating change
|
||||
* @param won Whether the player won
|
||||
* @returns Updated statistics
|
||||
*/
|
||||
export function updatePlayerStats(
|
||||
currentRating: number,
|
||||
currentGamesPlayed: number,
|
||||
currentWins: number,
|
||||
eloChange: number,
|
||||
won: boolean
|
||||
): {
|
||||
newRating: number;
|
||||
newGamesPlayed: number;
|
||||
newWins: number;
|
||||
newLosses: number;
|
||||
winRate: number;
|
||||
} {
|
||||
const newRating = currentRating + Math.round(eloChange);
|
||||
const newGamesPlayed = currentGamesPlayed + 1;
|
||||
const newWins = currentWins + (won ? 1 : 0);
|
||||
const newLosses = newGamesPlayed - newWins;
|
||||
const winRate = newGamesPlayed > 0 ? newWins / newGamesPlayed : 0;
|
||||
|
||||
return {
|
||||
newRating,
|
||||
newGamesPlayed,
|
||||
newWins,
|
||||
newLosses,
|
||||
winRate,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate new rating after a match
|
||||
* @param currentRating Current rating
|
||||
* @param opponentRating Opponent's rating
|
||||
* @param won Whether the player won
|
||||
* @param kFactor K-factor (default 32)
|
||||
* @returns New rating
|
||||
*/
|
||||
export function calculateNewRating(
|
||||
currentRating: number,
|
||||
opponentRating: number,
|
||||
won: boolean,
|
||||
kFactor: number = 32
|
||||
): number {
|
||||
const actualScore = won ? 1 : 0;
|
||||
const eloChange = calculateEloChange(currentRating, opponentRating, actualScore, kFactor);
|
||||
return Math.round(currentRating + eloChange);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate rating is within reasonable bounds
|
||||
* @param rating Rating to validate
|
||||
* @returns Whether the rating is valid
|
||||
*/
|
||||
export function isValidRating(rating: number): boolean {
|
||||
return rating >= 100 && rating <= 3000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get rating tier name based on rating
|
||||
* @param rating Player rating
|
||||
* @returns Tier name
|
||||
*/
|
||||
export function getRatingTier(rating: number): string {
|
||||
if (rating < 1100) return 'Beginner';
|
||||
if (rating < 1300) return 'Novice';
|
||||
if (rating < 1500) return 'Intermediate';
|
||||
if (rating < 1700) return 'Advanced';
|
||||
if (rating < 1900) return 'Expert';
|
||||
if (rating < 2100) return 'Master';
|
||||
return 'Grandmaster';
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate expected score for a team match
|
||||
* @param team1Rating Average rating of team 1
|
||||
* @param team2Rating Average rating of team 2
|
||||
* @returns Expected score for team 1
|
||||
*/
|
||||
export function calculateExpectedTeamScore(team1Rating: number, team2Rating: number): number {
|
||||
return calculateExpectedScore(team1Rating, team2Rating);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Elo change for team match
|
||||
* @param team1Rating Average rating of team 1
|
||||
* @param team2Rating Average rating of team 2
|
||||
* @param team1Score Actual score for team 1 (1 = win, 0.5 = draw, 0 = loss)
|
||||
* @param kFactor K-factor (default 32)
|
||||
* @returns Elo change for team 1
|
||||
*/
|
||||
export function calculateTeamEloChange(
|
||||
team1Rating: number,
|
||||
team2Rating: number,
|
||||
team1Score: number,
|
||||
kFactor: number = 32
|
||||
): number {
|
||||
return calculateEloChange(team1Rating, team2Rating, team1Score, kFactor);
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import { getSession } from './auth-simple';
|
||||
import { prisma } from './prisma';
|
||||
|
||||
export type UserRole = 'player' | 'tournament_admin' | 'club_admin';
|
||||
|
||||
export interface PermissionCheck {
|
||||
allowed: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current user has the required role
|
||||
* Reads role from database to avoid session cache issues
|
||||
*/
|
||||
export async function hasRole(requiredRole: UserRole): Promise<PermissionCheck> {
|
||||
const session = await getSession();
|
||||
|
||||
if (!session) {
|
||||
return { allowed: false, reason: 'Not authenticated' };
|
||||
}
|
||||
|
||||
const userId = session.user?.id;
|
||||
if (!userId) {
|
||||
return { allowed: false, reason: 'User ID not found in session' };
|
||||
}
|
||||
|
||||
// Fetch user from database to get current role (bypasses session cache)
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { role: true }
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return { allowed: false, reason: 'User not found in database' };
|
||||
}
|
||||
|
||||
const userRole = user.role as UserRole;
|
||||
|
||||
// Role hierarchy: player < tournament_admin < club_admin
|
||||
const roleHierarchy: Record<UserRole, number> = {
|
||||
'player': 1,
|
||||
'tournament_admin': 2,
|
||||
'club_admin': 3
|
||||
};
|
||||
|
||||
const hasRequiredRole = roleHierarchy[userRole] >= roleHierarchy[requiredRole];
|
||||
|
||||
return {
|
||||
allowed: hasRequiredRole,
|
||||
reason: hasRequiredRole ? undefined : `Requires ${requiredRole} role, but user has ${userRole}`
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user owns the tournament (for tournament_admin)
|
||||
*/
|
||||
export async function ownsTournament(tournamentId: number): Promise<PermissionCheck> {
|
||||
const session = await getSession();
|
||||
|
||||
if (!session) {
|
||||
return { allowed: false, reason: 'Not authenticated' };
|
||||
}
|
||||
|
||||
const userId = session.user?.id;
|
||||
if (!userId) {
|
||||
return { allowed: false, reason: 'User ID not found in session' };
|
||||
}
|
||||
|
||||
const tournament = await prisma.event.findUnique({
|
||||
where: { id: tournamentId },
|
||||
select: { ownerId: true }
|
||||
});
|
||||
|
||||
if (!tournament) {
|
||||
return { allowed: false, reason: 'Tournament not found' };
|
||||
}
|
||||
|
||||
const isOwner = tournament.ownerId === userId;
|
||||
|
||||
return {
|
||||
allowed: isOwner,
|
||||
reason: isOwner ? undefined : 'User does not own this tournament'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user can manage a specific tournament
|
||||
* Tournament admins can only manage their own tournaments
|
||||
* Club admins can manage all tournaments
|
||||
* Reads role from database to avoid session cache issues
|
||||
*/
|
||||
export async function canManageTournament(tournamentId: number): Promise<PermissionCheck> {
|
||||
const session = await getSession();
|
||||
|
||||
if (!session) {
|
||||
return { allowed: false, reason: 'Not authenticated' };
|
||||
}
|
||||
|
||||
const userId = session.user?.id;
|
||||
if (!userId) {
|
||||
return { allowed: false, reason: 'User ID not found in session' };
|
||||
}
|
||||
|
||||
// Fetch user from database to get current role (bypasses session cache)
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { role: true }
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return { allowed: false, reason: 'User not found in database' };
|
||||
}
|
||||
|
||||
const userRole = user.role as UserRole;
|
||||
|
||||
// Club admins can manage all tournaments
|
||||
if (userRole === 'club_admin') {
|
||||
return { allowed: true };
|
||||
}
|
||||
|
||||
// Tournament admins can only manage their own tournaments
|
||||
if (userRole === 'tournament_admin') {
|
||||
return ownsTournament(tournamentId);
|
||||
}
|
||||
|
||||
return { allowed: false, reason: 'Insufficient permissions to manage tournament' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user can create tournaments
|
||||
*/
|
||||
export async function canCreateTournaments(): Promise<PermissionCheck> {
|
||||
return hasRole('tournament_admin');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user can manage a specific match
|
||||
* Tournament admins can manage matches in their own tournaments
|
||||
* Club admins can manage all matches
|
||||
*/
|
||||
export async function canManageMatch(matchId: number): Promise<PermissionCheck> {
|
||||
const session = await getSession();
|
||||
|
||||
if (!session) {
|
||||
return { allowed: false, reason: 'Not authenticated' };
|
||||
}
|
||||
|
||||
const userRole = session.user?.role as UserRole;
|
||||
|
||||
// Club admins can manage all matches
|
||||
if (userRole === 'club_admin') {
|
||||
return { allowed: true };
|
||||
}
|
||||
|
||||
// Tournament admins can only manage matches in their own tournaments
|
||||
if (userRole === 'tournament_admin') {
|
||||
const match = await prisma.match.findUnique({
|
||||
where: { id: matchId },
|
||||
include: { event: true }
|
||||
});
|
||||
|
||||
if (!match || !match.event) {
|
||||
return { allowed: false, reason: 'Match or tournament not found' };
|
||||
}
|
||||
|
||||
return ownsTournament(match.event.id);
|
||||
}
|
||||
|
||||
return { allowed: false, reason: 'Insufficient permissions to manage match' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user can assign tournament_admin privileges
|
||||
* Only club admins can assign tournament_admin role
|
||||
*/
|
||||
export async function canAssignTournamentAdmin(): Promise<PermissionCheck> {
|
||||
return hasRole('club_admin');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tournaments that the current user can manage
|
||||
*/
|
||||
export async function getManageableTournaments() {
|
||||
const session = await getSession();
|
||||
|
||||
if (!session) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const userRole = session.user?.role as UserRole;
|
||||
const userId = session.user?.id;
|
||||
|
||||
if (userRole === 'club_admin') {
|
||||
// Club admins can see all tournaments
|
||||
return prisma.event.findMany({
|
||||
where: { eventType: 'tournament' },
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
}
|
||||
|
||||
if (userRole === 'tournament_admin') {
|
||||
// Tournament admins can only see their own tournaments
|
||||
return prisma.event.findMany({
|
||||
where: {
|
||||
eventType: 'tournament',
|
||||
ownerId: userId
|
||||
},
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
}
|
||||
|
||||
// Regular players can only view tournaments (not manage them)
|
||||
return prisma.event.findMany({
|
||||
where: { eventType: 'tournament', status: { not: 'draft' } },
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined
|
||||
}
|
||||
|
||||
export const prisma = globalForPrisma.prisma ?? new PrismaClient()
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Tournament utility functions
|
||||
* Used for calculating dynamic tournament status based on event date
|
||||
*/
|
||||
|
||||
/**
|
||||
* Calculates the tournament status based on the event date
|
||||
* @param eventDate - The date of the tournament event
|
||||
* @returns The calculated status string: "planned" or "completed"
|
||||
*/
|
||||
export function getTournamentStatus(eventDate: Date | null): string {
|
||||
if (!eventDate) {
|
||||
return "planned";
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const eventDateObj = new Date(eventDate);
|
||||
|
||||
// If event date is in the past, it's completed
|
||||
if (eventDateObj < now) {
|
||||
return "completed";
|
||||
}
|
||||
|
||||
// If event date is today or in the future, it's planned
|
||||
return "planned";
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a tournament date is in the past
|
||||
* @param eventDate - The date of the tournament event
|
||||
* @returns true if the event date is in the past, false otherwise
|
||||
*/
|
||||
export function isTournamentPast(eventDate: Date | null): boolean {
|
||||
if (!eventDate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const eventDateObj = new Date(eventDate);
|
||||
return eventDateObj < now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a tournament date is in the future
|
||||
* @param eventDate - The date of the tournament event
|
||||
* @returns true if the event date is in the future, false otherwise
|
||||
*/
|
||||
export function isTournamentFuture(eventDate: Date | null): boolean {
|
||||
if (!eventDate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const eventDateObj = new Date(eventDate);
|
||||
return eventDateObj > now;
|
||||
}
|
||||
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
declare module "papaparse" {
|
||||
export interface ParseResult<T> {
|
||||
data: T[]
|
||||
errors: Array<{
|
||||
type: string
|
||||
code: string
|
||||
message: string
|
||||
row?: number
|
||||
}>
|
||||
meta: {
|
||||
delimiter: string
|
||||
linebreak: string
|
||||
aborted: boolean
|
||||
fields?: string[]
|
||||
truncated: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export function parse<T = any>(
|
||||
input: string,
|
||||
config?: {
|
||||
header?: boolean
|
||||
skipEmptyLines?: boolean
|
||||
delimiter?: string
|
||||
}
|
||||
): ParseResult<T>
|
||||
}
|
||||
|
||||
export {}
|
||||
Reference in New Issue
Block a user