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,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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user