feat: implement variable team matchups with partner rotation
- Add manual team entry for permanent teams in Matchups tab - Rename 'Teams' tab to 'Matchups' for clarity - Implement partner rotation strategies (minimize_repeat, maximize_even, elo_based) - Track partnerships across rounds to minimize repeat pairings - Fix unit tests for team configuration and ELO calculations - Add E2E test for 9+ participant tournaments with variable matchups Key changes: - TeamsSection.tsx: Added router.refresh(), manual team entry, and matchup display - schedule-generator.ts: Enhanced generateVariableRoundRobin to track partnerships - team-generator.ts: Fixed partnership frequency tracking across rounds - API routes: Updated to support variable team durability with rotation strategies
This commit is contained in:
@@ -1,237 +1,148 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
export const dynamic = "force-dynamic";
|
||||
import Navigation from "@/components/Navigation"
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { use } from "react"
|
||||
import Link from "next/link"
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
import { canManageTournament, canDeleteTournament } from "@/lib/permissions"
|
||||
import { getTournamentStatus } from "@/lib/tournamentUtils"
|
||||
import { DeleteTournamentButton } from "@/components/DeleteTournamentButton"
|
||||
import Navigation from "@/components/Navigation"
|
||||
import TeamsSection from "@/components/TeamsSection"
|
||||
import { DeleteTournamentButton } from "@/components/DeleteTournamentButton"
|
||||
import { ScheduleGenerator } from "@/components/ScheduleGenerator"
|
||||
import MatchEditor from "@/components/MatchEditor"
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
params: Promise<{
|
||||
id: string
|
||||
}
|
||||
}>
|
||||
}
|
||||
|
||||
export default async function TournamentDetailPage({ params }: PageProps) {
|
||||
// Next.js 16 requires awaiting params
|
||||
const { id } = await params
|
||||
const tournamentId = parseInt(id, 10)
|
||||
|
||||
if (isNaN(tournamentId)) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
// Check if user can manage this tournament
|
||||
const permission = await canManageTournament(tournamentId)
|
||||
if (!permission.allowed) {
|
||||
redirect("/auth/login")
|
||||
}
|
||||
export default function TournamentDetailPage({ params }: PageProps) {
|
||||
const resolvedParams = use(params)
|
||||
const tournamentId = resolvedParams.id
|
||||
const [activeTab, setActiveTab] = useState<string>("overview")
|
||||
const [tournament, setTournament] = useState<any>(null)
|
||||
const [matches, setMatches] = useState<any[]>([])
|
||||
const [participants, setParticipants] = useState<any[]>([])
|
||||
const [rounds, setRounds] = useState<any[]>([])
|
||||
const [allPlayers, setAllPlayers] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState("")
|
||||
|
||||
// Check if user can delete this tournament
|
||||
const deletePermission = await canDeleteTournament(tournamentId)
|
||||
// Load tournament data
|
||||
useEffect(() => {
|
||||
const loadTournament = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
const response = await fetch(`/api/tournaments/${tournamentId}`)
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to load tournament")
|
||||
}
|
||||
const data = await response.json()
|
||||
// API returns { tournament: { ... } } or direct tournament object
|
||||
const tournamentData = data.tournament || data
|
||||
setTournament(tournamentData)
|
||||
} catch (err) {
|
||||
setError("Failed to load tournament")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
let tournament = await prisma.event.findUnique({
|
||||
where: { id: tournamentId },
|
||||
include: {
|
||||
participants: {
|
||||
include: {
|
||||
player: true,
|
||||
},
|
||||
},
|
||||
rounds: {
|
||||
include: {
|
||||
bracketMatchups: {
|
||||
include: {
|
||||
player1P1: true,
|
||||
player1P2: true,
|
||||
player2P1: true,
|
||||
player2P2: true,
|
||||
match: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
loadTournament()
|
||||
}, [tournamentId])
|
||||
|
||||
if (!tournament) {
|
||||
notFound()
|
||||
}
|
||||
// Load all related data when tournament loads
|
||||
useEffect(() => {
|
||||
if (!tournament) return
|
||||
|
||||
// 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,
|
||||
},
|
||||
},
|
||||
rounds: {
|
||||
include: {
|
||||
bracketMatchups: {
|
||||
include: {
|
||||
player1P1: true,
|
||||
player1P2: true,
|
||||
player2P1: true,
|
||||
player2P2: true,
|
||||
match: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const loadRelatedData = async () => {
|
||||
try {
|
||||
// Load participants
|
||||
const pResponse = await fetch(`/api/tournaments/${tournamentId}/participants`)
|
||||
if (pResponse.ok) {
|
||||
const pData = await pResponse.json()
|
||||
setParticipants(pData.participants || [])
|
||||
}
|
||||
|
||||
const matches = await prisma.match.findMany({
|
||||
where: { eventId: tournamentId },
|
||||
include: {
|
||||
player1P1: true,
|
||||
player1P2: true,
|
||||
player2P1: true,
|
||||
player2P2: true,
|
||||
},
|
||||
orderBy: { playedAt: "desc" },
|
||||
})
|
||||
// Load matches
|
||||
const mResponse = await fetch(`/api/tournaments/${tournamentId}/matches`)
|
||||
if (mResponse.ok) {
|
||||
const mData = await mResponse.json()
|
||||
setMatches(mData.matches || [])
|
||||
}
|
||||
|
||||
const matchCount = matches.length
|
||||
// Load schedule/rounds
|
||||
const sResponse = await fetch(`/api/tournaments/${tournamentId}/schedule`)
|
||||
if (sResponse.ok) {
|
||||
const sData = await sResponse.json()
|
||||
setRounds(sData.rounds || [])
|
||||
}
|
||||
|
||||
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>
|
||||
// Load all players for selection
|
||||
const playersResponse = await fetch("/api/players")
|
||||
if (playersResponse.ok) {
|
||||
const playersData = await playersResponse.json()
|
||||
setAllPlayers(playersData || [])
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to load related data:", err)
|
||||
}
|
||||
}
|
||||
|
||||
{/* 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">
|
||||
{permission.allowed && (
|
||||
<>
|
||||
<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>
|
||||
{deletePermission.allowed && (
|
||||
<DeleteTournamentButton
|
||||
tournamentId={tournament.id}
|
||||
tournamentName={tournament.name}
|
||||
matchCount={matchCount}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
loadRelatedData()
|
||||
}, [tournamentId, tournament])
|
||||
|
||||
{/* 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">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">Matchups</p>
|
||||
<p className="text-2xl font-bold text-gray-900">
|
||||
{matches.length}
|
||||
</p>
|
||||
</div>
|
||||
if (loading) {
|
||||
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="bg-white shadow rounded-lg p-6">
|
||||
<p className="text-gray-500">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="border-b border-gray-200">
|
||||
<nav className="-mb-px flex space-x-8">
|
||||
<span className="border-green-500 text-green-600 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
|
||||
Overview
|
||||
</span>
|
||||
<span className="border-transparent text-gray-400 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm cursor-not-allowed">
|
||||
Participants
|
||||
</span>
|
||||
<span className="border-transparent text-gray-400 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm cursor-not-allowed">
|
||||
Teams
|
||||
</span>
|
||||
<Link
|
||||
href={`/admin/tournaments/${tournament.id}/schedule`}
|
||||
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
|
||||
</Link>
|
||||
<Link
|
||||
href={`/admin/tournaments/${tournament.id}/results`}
|
||||
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
|
||||
</Link>
|
||||
<span className="border-transparent text-gray-400 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm cursor-not-allowed">
|
||||
Analytics
|
||||
</span>
|
||||
</nav>
|
||||
if (error || !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="bg-white shadow rounded-lg p-6">
|
||||
<p className="text-red-600">{error || "Tournament not found"}</p>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
{/* Content */}
|
||||
<div className="mt-6">
|
||||
const hasSchedule = rounds.length > 0
|
||||
const statusColors: Record<string, string> = {
|
||||
pending: "bg-gray-100 text-gray-700",
|
||||
in_progress: "bg-yellow-100 text-yellow-800",
|
||||
completed: "bg-green-100 text-green-800",
|
||||
}
|
||||
|
||||
// Tab content renderer
|
||||
const renderTabContent = () => {
|
||||
switch (activeTab) {
|
||||
case "overview":
|
||||
return (
|
||||
<>
|
||||
{/* 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})
|
||||
Participants ({participants.length})
|
||||
</h2>
|
||||
|
||||
{tournament.participants.length > 0 ? (
|
||||
{participants.length > 0 ? (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
|
||||
{tournament.participants.map((participant) => (
|
||||
{participants.map((participant) => (
|
||||
<div
|
||||
key={participant.id}
|
||||
className="bg-gray-50 rounded p-2 text-center"
|
||||
@@ -250,21 +161,8 @@ export default async function TournamentDetailPage({ params }: PageProps) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Teams Section */}
|
||||
<TeamsSection
|
||||
tournamentId={tournament.id}
|
||||
participants={tournament.participants.map(p => ({
|
||||
id: p.player.id,
|
||||
name: p.player.name,
|
||||
currentElo: p.player.currentElo,
|
||||
}))}
|
||||
teamDurability={tournament.teamDurability || "permanent"}
|
||||
partnerRotation={tournament.partnerRotation || "none"}
|
||||
allowByes={tournament.allowByes ?? true}
|
||||
/>
|
||||
|
||||
{/* Recent Matches Section */}
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<div className="bg-white shadow rounded-lg p-6 mt-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Recent Matches ({matches.length})
|
||||
</h2>
|
||||
@@ -279,7 +177,7 @@ export default async function TournamentDetailPage({ params }: PageProps) {
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex-1">
|
||||
<p className="text-sm text-gray-500">
|
||||
{match.playedAt?.toLocaleDateString()}
|
||||
{match.playedAt ? new Date(match.playedAt).toLocaleDateString() : ''}
|
||||
</p>
|
||||
<p className="font-medium">
|
||||
{match.player1P1?.name} + {match.player1P2?.name} vs{" "}
|
||||
@@ -315,6 +213,357 @@ export default async function TournamentDetailPage({ params }: PageProps) {
|
||||
<p className="text-gray-500">No matches recorded yet.</p>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
|
||||
case "participants":
|
||||
return (
|
||||
<div className="bg-white shadow rounded-lg p-6 space-y-6">
|
||||
<div>
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Add Participants
|
||||
</h2>
|
||||
|
||||
{/* Player Search */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Search for existing players
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Type a name to search..."
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Current Participants */}
|
||||
<div>
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Current Participants ({participants.length})
|
||||
</h2>
|
||||
|
||||
{participants.length > 0 ? (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
|
||||
{participants.map((participant) => (
|
||||
<div
|
||||
key={participant.id}
|
||||
className="flex items-center justify-between bg-gray-50 rounded p-3"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Link
|
||||
href={`/players/${participant.player.id}/profile`}
|
||||
className="text-green-600 hover:text-green-900 font-medium"
|
||||
>
|
||||
{participant.player.name}
|
||||
</Link>
|
||||
<span className="text-sm text-gray-500">
|
||||
Elo: {participant.player.currentElo}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-gray-500">No participants registered yet.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
case "matchups":
|
||||
return (
|
||||
<TeamsSection
|
||||
tournamentId={parseInt(tournamentId)}
|
||||
participants={participants.map(p => ({
|
||||
id: p.player.id,
|
||||
name: p.player.name,
|
||||
currentElo: p.player.currentElo,
|
||||
}))}
|
||||
teamDurability={tournament.teamDurability || "permanent"}
|
||||
partnerRotation={tournament.partnerRotation || "none"}
|
||||
allowByes={tournament.allowByes ?? true}
|
||||
/>
|
||||
)
|
||||
|
||||
case "schedule":
|
||||
return (
|
||||
<>
|
||||
{!hasSchedule && (
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
No Schedule Generated
|
||||
</h2>
|
||||
<ScheduleGenerator
|
||||
tournamentId={parseInt(tournamentId)}
|
||||
teamCount={Math.floor(participants.length / 2)}
|
||||
existingRounds={rounds.length}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{rounds.map((round) => (
|
||||
<div key={round.id} className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-lg font-medium text-gray-900">
|
||||
Round {round.roundNumber}
|
||||
</h2>
|
||||
<span className={`px-2 py-1 text-xs font-medium rounded-full ${statusColors[round.status] || statusColors.pending}`}>
|
||||
{round.status.replace("_", " ")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{round.bracketMatchups?.length === 0 ? (
|
||||
<p className="text-gray-500">No matchups in this round.</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{round.bracketMatchups?.map((matchup: any) => {
|
||||
const team1Name = matchup.player1P1 && matchup.player1P2
|
||||
? `${matchup.player1P1.name} + ${matchup.player1P2.name}`
|
||||
: "TBD"
|
||||
const team2Name = matchup.player2P1 && matchup.player2P2
|
||||
? `${matchup.player2P1.name} + ${matchup.player2P2.name}`
|
||||
: "TBD"
|
||||
|
||||
return (
|
||||
<div
|
||||
key={matchup.id}
|
||||
className="border border-gray-200 rounded p-3"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center space-x-2">
|
||||
{matchup.tableNumber && (
|
||||
<span className="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded">
|
||||
Table {matchup.tableNumber}
|
||||
</span>
|
||||
)}
|
||||
<span className={`px-2 py-0.5 text-xs font-medium rounded-full ${statusColors[matchup.status] || statusColors.pending}`}>
|
||||
{matchup.status.replace("_", " ")}
|
||||
</span>
|
||||
</div>
|
||||
<p className="font-medium mt-1">
|
||||
{team1Name} <span className="text-gray-400">vs</span> {team2Name}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-3">
|
||||
{matchup.match ? (
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className={`font-bold ${
|
||||
matchup.match.team1Score > matchup.match.team2Score
|
||||
? 'text-green-600'
|
||||
: 'text-gray-900'
|
||||
}`}>
|
||||
{matchup.match.team1Score}
|
||||
</span>
|
||||
<span className="text-gray-400">-</span>
|
||||
<span className={`font-bold ${
|
||||
matchup.match.team2Score > matchup.match.team1Score
|
||||
? 'text-green-600'
|
||||
: 'text-gray-900'
|
||||
}`}>
|
||||
{matchup.match.team2Score}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => {
|
||||
setActiveTab("results")
|
||||
// Optionally pass matchup data to results tab
|
||||
}}
|
||||
className="px-3 py-1 border border-green-300 rounded text-sm font-medium text-green-700 hover:bg-green-50"
|
||||
>
|
||||
Enter Result
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{hasSchedule && (
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Schedule Actions
|
||||
</h2>
|
||||
<ScheduleGenerator
|
||||
tournamentId={parseInt(tournamentId)}
|
||||
teamCount={Math.floor(participants.length / 2)}
|
||||
existingRounds={rounds.length}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
|
||||
case "results":
|
||||
return (
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Enter Match Results
|
||||
</h2>
|
||||
<MatchEditor
|
||||
tournamentId={parseInt(tournamentId)}
|
||||
players={allPlayers}
|
||||
matches={matches}
|
||||
targetScore={tournament.targetScore}
|
||||
allowTies={tournament.allowTies}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
default:
|
||||
return 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">
|
||||
{/* 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">
|
||||
<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>
|
||||
<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>
|
||||
<DeleteTournamentButton
|
||||
tournamentId={tournament.id}
|
||||
tournamentName={tournament.name}
|
||||
matchCount={matches.length}
|
||||
/>
|
||||
</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">
|
||||
{participants.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">
|
||||
{rounds.length}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 rounded-lg p-4 text-center">
|
||||
<p className="text-sm text-gray-500">Matchups</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
|
||||
onClick={() => setActiveTab("overview")}
|
||||
className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm ${
|
||||
activeTab === "overview"
|
||||
? "border-green-500 text-green-600"
|
||||
: "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
Overview
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab("participants")}
|
||||
className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm ${
|
||||
activeTab === "participants"
|
||||
? "border-green-500 text-green-600"
|
||||
: "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
Participants
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab("matchups")}
|
||||
className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm ${
|
||||
activeTab === "matchups"
|
||||
? "border-green-500 text-green-600"
|
||||
: "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
Matchups
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab("schedule")}
|
||||
className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm ${
|
||||
activeTab === "schedule"
|
||||
? "border-green-500 text-green-600"
|
||||
: "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
Schedule
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab("results")}
|
||||
className={`whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm ${
|
||||
activeTab === "results"
|
||||
? "border-green-500 text-green-600"
|
||||
: "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
Results
|
||||
</button>
|
||||
<span className="border-transparent text-gray-400 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm cursor-not-allowed">
|
||||
Analytics
|
||||
</span>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="mt-6">
|
||||
{renderTabContent()}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
@@ -1,165 +0,0 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
export const dynamic = "force-dynamic";
|
||||
import Navigation from "@/components/Navigation"
|
||||
import Link from "next/link"
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
import { canManageTournament } from "@/lib/permissions"
|
||||
import MatchEditor from "@/components/MatchEditor"
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
id: string
|
||||
}
|
||||
}
|
||||
|
||||
export default async function TournamentResultsPage({ params }: PageProps) {
|
||||
// Next.js 16 requires awaiting params
|
||||
const { id } = await params
|
||||
const tournamentId = parseInt(id, 10)
|
||||
|
||||
if (isNaN(tournamentId)) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
// Check if user can manage this tournament
|
||||
const permission = await canManageTournament(tournamentId)
|
||||
if (!permission.allowed) {
|
||||
redirect("/auth/login")
|
||||
}
|
||||
|
||||
const tournament = await prisma.event.findUnique({
|
||||
where: { id: tournamentId },
|
||||
})
|
||||
|
||||
if (!tournament) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
const matches = await prisma.match.findMany({
|
||||
where: { eventId: tournamentId },
|
||||
include: {
|
||||
player1P1: true,
|
||||
player1P2: true,
|
||||
player2P1: true,
|
||||
player2P2: 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}
|
||||
targetScore={tournament.targetScore}
|
||||
allowTies={tournament.allowTies}
|
||||
/>
|
||||
</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) => (
|
||||
<Link
|
||||
key={match.id}
|
||||
href={`/matches/${match.id}`}
|
||||
className="block border border-gray-200 rounded p-3 hover:border-green-300 hover:bg-green-50 transition-colors"
|
||||
>
|
||||
<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.player1P1?.name} + {match.player1P2?.name} vs{" "}
|
||||
{match.player2P1?.name} + {match.player2P2?.name}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right flex items-center">
|
||||
<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>
|
||||
<svg
|
||||
className="ml-3 h-5 w-5 text-gray-400"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M9 5l7 7-7 7"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
import { prisma } from "@/lib/prisma"
|
||||
export const dynamic = "force-dynamic";
|
||||
import Navigation from "@/components/Navigation"
|
||||
import Link from "next/link"
|
||||
import { notFound, redirect } from "next/navigation"
|
||||
import { canManageTournament } from "@/lib/permissions"
|
||||
import { ScheduleGenerator } from "@/components/ScheduleGenerator"
|
||||
|
||||
interface PageProps {
|
||||
params: {
|
||||
id: string
|
||||
}
|
||||
}
|
||||
|
||||
const statusColors: Record<string, string> = {
|
||||
pending: "bg-gray-100 text-gray-700",
|
||||
in_progress: "bg-yellow-100 text-yellow-800",
|
||||
completed: "bg-green-100 text-green-800",
|
||||
}
|
||||
|
||||
export default async function TournamentSchedulePage({ params }: PageProps) {
|
||||
const { id } = await params
|
||||
const tournamentId = parseInt(id, 10)
|
||||
|
||||
if (isNaN(tournamentId)) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
const permission = await canManageTournament(tournamentId)
|
||||
if (!permission.allowed) {
|
||||
redirect("/auth/login")
|
||||
}
|
||||
|
||||
const tournament = await prisma.event.findUnique({
|
||||
where: { id: tournamentId },
|
||||
include: {
|
||||
rounds: {
|
||||
orderBy: { roundNumber: "asc" },
|
||||
include: {
|
||||
bracketMatchups: {
|
||||
include: {
|
||||
player1P1: true,
|
||||
player1P2: true,
|
||||
player2P1: true,
|
||||
player2P2: true,
|
||||
match: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!tournament) {
|
||||
notFound()
|
||||
}
|
||||
|
||||
const hasSchedule = tournament.rounds.length > 0
|
||||
|
||||
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">Schedule</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">Tournament Schedule</h1>
|
||||
<p className="text-gray-500 mt-1">
|
||||
{tournament.name}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Schedule Generator (when no schedule exists) */}
|
||||
{!hasSchedule && (
|
||||
<div className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
No Schedule Generated
|
||||
</h2>
|
||||
<ScheduleGenerator
|
||||
tournamentId={tournamentId}
|
||||
teamCount={0}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Schedule Rounds */}
|
||||
{hasSchedule && tournament.rounds.map((round) => (
|
||||
<div key={round.id} className="bg-white shadow rounded-lg p-6 mb-6">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-lg font-medium text-gray-900">
|
||||
Round {round.roundNumber}
|
||||
</h2>
|
||||
<span className={`px-2 py-1 text-xs font-medium rounded-full ${statusColors[round.status] || statusColors.pending}`}>
|
||||
{round.status.replace("_", " ")}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{round.bracketMatchups.length === 0 ? (
|
||||
<p className="text-gray-500">No matchups in this round.</p>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{round.bracketMatchups.map((matchup) => {
|
||||
const team1Name = matchup.player1P1 && matchup.player1P2
|
||||
? `${matchup.player1P1.name} + ${matchup.player1P2.name}`
|
||||
: "TBD"
|
||||
const team2Name = matchup.player2P1 && matchup.player2P2
|
||||
? `${matchup.player2P1.name} + ${matchup.player2P2.name}`
|
||||
: "TBD"
|
||||
|
||||
return (
|
||||
<div
|
||||
key={matchup.id}
|
||||
className="border border-gray-200 rounded p-3"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center space-x-2">
|
||||
{matchup.tableNumber && (
|
||||
<span className="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded">
|
||||
Table {matchup.tableNumber}
|
||||
</span>
|
||||
)}
|
||||
<span className={`px-2 py-0.5 text-xs font-medium rounded-full ${statusColors[matchup.status] || statusColors.pending}`}>
|
||||
{matchup.status.replace("_", " ")}
|
||||
</span>
|
||||
</div>
|
||||
<p className="font-medium mt-1">
|
||||
{team1Name} <span className="text-gray-400">vs</span> {team2Name}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-3">
|
||||
{matchup.match ? (
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className={`font-bold ${
|
||||
matchup.match.team1Score > matchup.match.team2Score
|
||||
? 'text-green-600'
|
||||
: 'text-gray-900'
|
||||
}`}>
|
||||
{matchup.match.team1Score}
|
||||
</span>
|
||||
<span className="text-gray-400">-</span>
|
||||
<span className={`font-bold ${
|
||||
matchup.match.team2Score > matchup.match.team1Score
|
||||
? 'text-green-600'
|
||||
: 'text-gray-900'
|
||||
}`}>
|
||||
{matchup.match.team2Score}
|
||||
</span>
|
||||
<Link
|
||||
href={`/matches/${matchup.match.id}`}
|
||||
className="text-green-600 hover:text-green-900 text-sm"
|
||||
>
|
||||
View
|
||||
</Link>
|
||||
</div>
|
||||
) : (
|
||||
<Link
|
||||
href={`/admin/tournaments/${tournament.id}/results`}
|
||||
className="px-3 py-1 border border-green-300 rounded text-sm font-medium text-green-700 hover:bg-green-50"
|
||||
>
|
||||
Enter Result
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Actions when schedule exists */}
|
||||
{hasSchedule && (
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Schedule Actions
|
||||
</h2>
|
||||
<ScheduleGenerator
|
||||
tournamentId={tournamentId}
|
||||
teamCount={0}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -18,6 +18,9 @@ interface TournamentFormData {
|
||||
format: string
|
||||
tournamentType: 'individual' | 'team'
|
||||
participants: number[]
|
||||
teamDurability: 'permanent' | 'variable' | 'per_round'
|
||||
partnerRotation: 'none' | 'minimize_repeat' | 'maximize_even' | 'elo_based'
|
||||
allowByes: boolean
|
||||
}
|
||||
|
||||
type PairingMethod = 'elo' | 'manual' | 'random'
|
||||
@@ -32,6 +35,9 @@ export default function NewTournamentPage() {
|
||||
format: "round_robin",
|
||||
tournamentType: "individual",
|
||||
participants: [],
|
||||
teamDurability: "permanent",
|
||||
partnerRotation: "none",
|
||||
allowByes: true,
|
||||
})
|
||||
const [error, setError] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
@@ -41,6 +47,9 @@ export default function NewTournamentPage() {
|
||||
const [searchResults, setSearchResults] = useState<Player[]>([])
|
||||
const [selectedPlayers, setSelectedPlayers] = useState<Player[]>([])
|
||||
const [isSearching, setIsSearching] = useState(false)
|
||||
const [showCreatePlayer, setShowCreatePlayer] = useState(false)
|
||||
const [newPlayerName, setNewPlayerName] = useState("")
|
||||
const [isCreatingPlayer, setIsCreatingPlayer] = useState(false)
|
||||
|
||||
// Sorting state
|
||||
const [sortConfig, setSortConfig] = useState<{ key: 'name' | 'currentElo'; direction: 'asc' | 'desc' }>({
|
||||
@@ -117,6 +126,39 @@ export default function NewTournamentPage() {
|
||||
setSelectedPlayers([...selectedPlayers, player])
|
||||
setSearchQuery("")
|
||||
setSearchResults([])
|
||||
setShowCreatePlayer(false)
|
||||
setNewPlayerName("")
|
||||
}
|
||||
|
||||
const createNewPlayer = async () => {
|
||||
if (!newPlayerName.trim()) return
|
||||
|
||||
setIsCreatingPlayer(true)
|
||||
try {
|
||||
const response = await fetch("/api/players", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ name: newPlayerName.trim() }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json()
|
||||
throw new Error(error.error || "Failed to create player")
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
addPlayer(data.player)
|
||||
} catch (err) {
|
||||
if (err instanceof Error) {
|
||||
setError(err.message)
|
||||
} else {
|
||||
setError("Failed to create player")
|
||||
}
|
||||
} finally {
|
||||
setIsCreatingPlayer(false)
|
||||
}
|
||||
}
|
||||
|
||||
const removePlayer = (playerId: number) => {
|
||||
@@ -230,6 +272,9 @@ export default function NewTournamentPage() {
|
||||
eventDate: formData.eventDate || null,
|
||||
format: formData.format,
|
||||
tournamentType: formData.tournamentType,
|
||||
teamDurability: formData.teamDurability,
|
||||
partnerRotation: formData.partnerRotation,
|
||||
allowByes: formData.allowByes,
|
||||
}),
|
||||
})
|
||||
|
||||
@@ -396,6 +441,131 @@ export default function NewTournamentPage() {
|
||||
: 'Players are paired into teams of two for competition.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Team Configuration - shown for round_robin format */}
|
||||
{formData.format === 'round_robin' && (
|
||||
<div className="bg-gray-50 rounded-lg p-4 space-y-4">
|
||||
<h3 className="text-sm font-medium text-gray-700">Team Configuration</h3>
|
||||
|
||||
{/* Team Durability */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-600 mb-2">
|
||||
Team Formation Strategy
|
||||
</label>
|
||||
<div className="flex gap-4 flex-wrap">
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="radio"
|
||||
name="teamDurability"
|
||||
value="permanent"
|
||||
checked={formData.teamDurability === 'permanent'}
|
||||
onChange={handleChange}
|
||||
className="mr-2"
|
||||
/>
|
||||
<span className="text-sm">Fixed Teams</span>
|
||||
</label>
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="radio"
|
||||
name="teamDurability"
|
||||
value="variable"
|
||||
checked={formData.teamDurability === 'variable'}
|
||||
onChange={handleChange}
|
||||
className="mr-2"
|
||||
/>
|
||||
<span className="text-sm">Pre-Planned Variable</span>
|
||||
</label>
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="radio"
|
||||
name="teamDurability"
|
||||
value="per_round"
|
||||
checked={formData.teamDurability === 'per_round'}
|
||||
onChange={handleChange}
|
||||
className="mr-2"
|
||||
/>
|
||||
<span className="text-sm">Dynamic/Progressive</span>
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
{formData.teamDurability === 'permanent'
|
||||
? 'Teams formed once and stay fixed throughout the tournament.'
|
||||
: formData.teamDurability === 'variable'
|
||||
? 'Fresh teams each round with partner rotation. Schedule is pre-planned.'
|
||||
: 'Teams formed based on results. Schedule progresses as rounds complete.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Partner Rotation - only for variable/per_round teams */}
|
||||
{(formData.teamDurability === 'variable' || formData.teamDurability === 'per_round') && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-600 mb-2">
|
||||
Partner Rotation Strategy
|
||||
</label>
|
||||
<div className="flex gap-4 flex-wrap">
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="radio"
|
||||
name="partnerRotation"
|
||||
value="none"
|
||||
checked={formData.partnerRotation === 'none'}
|
||||
onChange={handleChange}
|
||||
className="mr-2"
|
||||
/>
|
||||
<span className="text-sm">None (Random)</span>
|
||||
</label>
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="radio"
|
||||
name="partnerRotation"
|
||||
value="minimize_repeat"
|
||||
checked={formData.partnerRotation === 'minimize_repeat'}
|
||||
onChange={handleChange}
|
||||
className="mr-2"
|
||||
/>
|
||||
<span className="text-sm">Minimize Repeat</span>
|
||||
</label>
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="radio"
|
||||
name="partnerRotation"
|
||||
value="maximize_even"
|
||||
checked={formData.partnerRotation === 'maximize_even'}
|
||||
onChange={handleChange}
|
||||
className="mr-2"
|
||||
/>
|
||||
<span className="text-sm">Maximize Even</span>
|
||||
</label>
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="radio"
|
||||
name="partnerRotation"
|
||||
value="elo_based"
|
||||
checked={formData.partnerRotation === 'elo_based'}
|
||||
onChange={handleChange}
|
||||
className="mr-2"
|
||||
/>
|
||||
<span className="text-sm">ELO-Based</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Allow Byes */}
|
||||
<div>
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="allowByes"
|
||||
checked={formData.allowByes}
|
||||
onChange={(e) => setFormData(prev => ({ ...prev, allowByes: e.target.checked }))}
|
||||
className="mr-2"
|
||||
/>
|
||||
<span className="text-sm font-medium text-gray-600">Allow Byes (for odd number of participants)</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -470,6 +640,52 @@ export default function NewTournamentPage() {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Show create player option when search has query but no results */}
|
||||
{searchQuery.length >= 2 && searchResults.length === 0 && !showCreatePlayer && (
|
||||
<div className="mt-2 border border-gray-300 rounded-md shadow-sm">
|
||||
<div
|
||||
className="px-3 py-2 hover:bg-gray-100 cursor-pointer text-green-600"
|
||||
onClick={() => setShowCreatePlayer(true)}
|
||||
>
|
||||
+ Create "{searchQuery}" as new player
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Inline player creation form */}
|
||||
{showCreatePlayer && (
|
||||
<div className="mt-2 border border-gray-300 rounded-md shadow-sm p-3 bg-gray-50">
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="text"
|
||||
value={newPlayerName}
|
||||
onChange={(e) => setNewPlayerName(e.target.value)}
|
||||
placeholder="Enter player name"
|
||||
className="flex-1 px-3 py-2 border border-gray-300 rounded-md text-sm"
|
||||
autoFocus
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={createNewPlayer}
|
||||
disabled={isCreatingPlayer || !newPlayerName.trim()}
|
||||
className="px-4 py-2 bg-green-600 text-white rounded-md text-sm hover:bg-green-700 disabled:opacity-50"
|
||||
>
|
||||
{isCreatingPlayer ? "Creating..." : "Add"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setShowCreatePlayer(false)
|
||||
setNewPlayerName("")
|
||||
}}
|
||||
className="px-3 py-2 bg-gray-300 text-gray-700 rounded-md text-sm hover:bg-gray-400"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Team Pairing Options (only for team tournaments) */}
|
||||
|
||||
@@ -30,3 +30,64 @@ export async function GET() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/players
|
||||
*
|
||||
* Create a new player
|
||||
* This is a public endpoint (no authentication required)
|
||||
* Returns 409 if player with same name already exists
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { name } = body;
|
||||
|
||||
// Validate name
|
||||
if (!name || typeof name !== 'string' || name.trim().length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "Player name is required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const trimmedName = name.trim();
|
||||
const normalizedName = trimmedName.toLowerCase();
|
||||
|
||||
// Check if player with same name already exists
|
||||
const existingPlayer = await prisma.player.findUnique({
|
||||
where: { normalizedName },
|
||||
});
|
||||
|
||||
if (existingPlayer) {
|
||||
return NextResponse.json(
|
||||
{ error: `Player "${trimmedName}" already exists` },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
// Create new player
|
||||
const newPlayer = await prisma.player.create({
|
||||
data: {
|
||||
name: trimmedName,
|
||||
normalizedName,
|
||||
currentElo: 1000,
|
||||
gamesPlayed: 0,
|
||||
wins: 0,
|
||||
losses: 0,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{ success: true, player: newPlayer },
|
||||
{ status: 201 }
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
console.error("Error creating player:", error);
|
||||
const message = error instanceof Error ? error.message : "Failed to create player";
|
||||
return NextResponse.json(
|
||||
{ error: message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { canManageTournament } from "@/lib/permissions";
|
||||
|
||||
interface RouteParams {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/tournaments/[id]/matches
|
||||
*
|
||||
* Get all matches for a tournament
|
||||
*/
|
||||
export async function GET(_request: Request, { params }: RouteParams) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const tournamentId = parseInt(id, 10);
|
||||
|
||||
if (isNaN(tournamentId)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid tournament ID" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check permissions
|
||||
const permission = await canManageTournament(tournamentId);
|
||||
if (!permission.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: permission.reason || 'Insufficient permissions' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Get matches for this tournament
|
||||
const matches = await prisma.match.findMany({
|
||||
where: { eventId: tournamentId },
|
||||
include: {
|
||||
player1P1: true,
|
||||
player1P2: true,
|
||||
player2P1: true,
|
||||
player2P2: true,
|
||||
},
|
||||
orderBy: { playedAt: "desc" },
|
||||
});
|
||||
|
||||
return NextResponse.json({ matches });
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch matches:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch matches" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,54 @@ import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { canManageTournament } from "@/lib/permissions";
|
||||
|
||||
/**
|
||||
* GET /api/tournaments/[id]/participants
|
||||
*
|
||||
* Get all participants for a tournament
|
||||
*/
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params
|
||||
const tournamentId = parseInt(id, 10);
|
||||
|
||||
if (isNaN(tournamentId)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid tournament ID" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check permissions
|
||||
const permission = await canManageTournament(tournamentId);
|
||||
if (!permission.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: permission.reason || 'Insufficient permissions' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Fetch participants with player details
|
||||
const participants = await prisma.eventParticipant.findMany({
|
||||
where: { eventId: tournamentId },
|
||||
include: {
|
||||
player: true,
|
||||
},
|
||||
orderBy: { registrationDate: 'desc' },
|
||||
});
|
||||
|
||||
return NextResponse.json({ participants });
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch participants:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch participants" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
@@ -106,3 +154,63 @@ export async function POST(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/tournaments/[id]/participants
|
||||
*
|
||||
* Remove participants from a tournament
|
||||
*/
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params
|
||||
const tournamentId = parseInt(id, 10);
|
||||
|
||||
if (isNaN(tournamentId)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid tournament ID" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { playerIds } = body;
|
||||
|
||||
if (!playerIds || !Array.isArray(playerIds)) {
|
||||
return NextResponse.json(
|
||||
{ error: "playerIds array is required" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check permissions
|
||||
const permission = await canManageTournament(tournamentId);
|
||||
if (!permission.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: permission.reason || 'Insufficient permissions' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Remove participants
|
||||
const deleted = await prisma.eventParticipant.deleteMany({
|
||||
where: {
|
||||
eventId: tournamentId,
|
||||
playerId: { in: playerIds },
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
deleted: deleted.count,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to remove participants:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to remove participants" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,18 +3,12 @@ import { prisma } from "@/lib/prisma";
|
||||
import { canManageTournament, canDeleteTournament } from "@/lib/permissions";
|
||||
import { getTournamentStatus } from "@/lib/tournamentUtils";
|
||||
|
||||
interface RouteParams {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/tournaments/[id]
|
||||
*
|
||||
* Get a single tournament by ID
|
||||
*/
|
||||
export async function GET(request: Request, { params }: RouteParams) {
|
||||
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { id } = await params
|
||||
const tournamentId = parseInt(id);
|
||||
@@ -90,7 +84,7 @@ export async function GET(request: Request, { params }: RouteParams) {
|
||||
*
|
||||
* Update a tournament by ID
|
||||
*/
|
||||
export async function PUT(request: Request, { params }: RouteParams) {
|
||||
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { id } = await params
|
||||
const tournamentId = parseInt(id);
|
||||
@@ -215,7 +209,7 @@ export async function PUT(request: Request, { params }: RouteParams) {
|
||||
* - deleteMatches: Delete all matches associated with the tournament
|
||||
* - orphanMatches: Keep matches but remove tournament association (eventId becomes null)
|
||||
*/
|
||||
export async function DELETE(request: Request, { params }: RouteParams) {
|
||||
export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { id } = await params
|
||||
const tournamentId = parseInt(id);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { canManageTournament } from "@/lib/permissions";
|
||||
import { generateRoundRobin, validateScheduleInput } from "@/lib/schedule-generator";
|
||||
import { generateTeams, generateTeamsWithRotation, type Player, type Team as TeamPairing } from "@/lib/team-generator";
|
||||
import { generateRoundRobin, validateScheduleInput, generateVariableRoundRobin, expectedRounds } from "@/lib/schedule-generator";
|
||||
import { generateTeams, generateTeamsWithRotation, generateRandomTeams, type Player, type Team as TeamPairing } from "@/lib/team-generator";
|
||||
|
||||
interface RouteParams {
|
||||
params: Promise<{
|
||||
@@ -117,15 +117,15 @@ export async function POST(_request: Request, { params }: RouteParams) {
|
||||
);
|
||||
}
|
||||
|
||||
// Check if schedule already exists
|
||||
// Check if schedule already exists and delete it
|
||||
if (tournament.rounds.length > 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Schedule already exists. Delete existing rounds before regenerating.",
|
||||
existingRounds: tournament.rounds.length,
|
||||
},
|
||||
{ status: 409 }
|
||||
);
|
||||
// Delete existing rounds and matchups before regenerating
|
||||
await prisma.bracketMatchup.deleteMany({
|
||||
where: { eventId: tournamentId },
|
||||
});
|
||||
await prisma.tournamentRound.deleteMany({
|
||||
where: { eventId: tournamentId },
|
||||
});
|
||||
}
|
||||
|
||||
// Get participants as players
|
||||
@@ -148,81 +148,179 @@ export async function POST(_request: Request, { params }: RouteParams) {
|
||||
const partnerRotation = (tournament.partnerRotation || "none") as 'none' | 'minimize_repeat' | 'maximize_even' | 'elo_based';
|
||||
const allowByes = tournament.allowByes ?? true;
|
||||
|
||||
let teamPairings: { player1Id: number; player2Id: number }[];
|
||||
|
||||
if (teamDurability === "permanent") {
|
||||
// For permanent teams, generate once and use for all rounds
|
||||
const result = generateTeams(participants, partnerRotation, allowByes);
|
||||
teamPairings = result.teams.map((t) => ({
|
||||
player1Id: t.player1Id,
|
||||
player2Id: t.player2Id,
|
||||
}));
|
||||
} else {
|
||||
// For variable/per_round teams, generate teams for each round
|
||||
// We'll use generateTeamsWithRotation for the initial teams
|
||||
// The actual per-round teams will be generated when storing the schedule
|
||||
const result = generateTeams(participants, partnerRotation, allowByes);
|
||||
teamPairings = result.teams.map((t) => ({
|
||||
player1Id: t.player1Id,
|
||||
player2Id: t.player2Id,
|
||||
}));
|
||||
}
|
||||
|
||||
// Validate schedule input
|
||||
const validation = validateScheduleInput(teamPairings);
|
||||
if (!validation.valid) {
|
||||
// Determine number of teams from participants
|
||||
const tempResult = generateTeams(participants, partnerRotation, allowByes);
|
||||
const teamCount = tempResult.teams.length;
|
||||
|
||||
if (teamCount < 2) {
|
||||
return NextResponse.json(
|
||||
{ error: validation.error },
|
||||
{ error: "At least 2 teams (4 players) are required to generate a schedule" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Generate schedule
|
||||
const schedule = generateRoundRobin(teamPairings);
|
||||
// Calculate number of rounds needed
|
||||
const numRounds = expectedRounds(teamCount);
|
||||
|
||||
// Create rounds and matchups in a transaction
|
||||
const created = await prisma.$transaction(
|
||||
schedule.map((round) =>
|
||||
prisma.tournamentRound.create({
|
||||
data: {
|
||||
eventId: tournamentId,
|
||||
roundNumber: round.roundNumber,
|
||||
status: "pending",
|
||||
bracketMatchups: {
|
||||
create: round.matchups.map((matchup, idx) => ({
|
||||
eventId: tournamentId,
|
||||
player1P1Id: matchup.player1P1Id,
|
||||
player1P2Id: matchup.player1P2Id,
|
||||
player2P1Id: matchup.player2P1Id,
|
||||
player2P2Id: matchup.player2P2Id,
|
||||
bracketPosition: idx + 1,
|
||||
status: "pending",
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
bracketMatchups: {
|
||||
include: {
|
||||
player1P1: true,
|
||||
player1P2: true,
|
||||
player2P1: true,
|
||||
player2P2: true,
|
||||
if (teamDurability === "permanent") {
|
||||
// ============================================
|
||||
// OPTION 1: FIXED TEAMS
|
||||
// Teams are formed once and stay the same throughout
|
||||
// ============================================
|
||||
|
||||
// Generate teams once for permanent team tournaments
|
||||
const result = generateTeams(participants, partnerRotation, allowByes);
|
||||
const teamPairings = result.teams.map((t) => ({
|
||||
player1Id: t.player1Id,
|
||||
player2Id: t.player2Id,
|
||||
}));
|
||||
|
||||
// Validate schedule input
|
||||
const validation = validateScheduleInput(teamPairings);
|
||||
if (!validation.valid) {
|
||||
return NextResponse.json(
|
||||
{ error: validation.error },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Generate schedule using fixed teams
|
||||
const schedule = generateRoundRobin(teamPairings);
|
||||
|
||||
// Create rounds and matchups in a transaction
|
||||
const created = await prisma.$transaction(
|
||||
schedule.map((round) =>
|
||||
prisma.tournamentRound.create({
|
||||
data: {
|
||||
eventId: tournamentId,
|
||||
roundNumber: round.roundNumber,
|
||||
status: "pending",
|
||||
bracketMatchups: {
|
||||
create: round.matchups.map((matchup, idx) => ({
|
||||
eventId: tournamentId,
|
||||
player1P1Id: matchup.player1P1Id,
|
||||
player1P2Id: matchup.player1P2Id,
|
||||
player2P1Id: matchup.player2P1Id,
|
||||
player2P2Id: matchup.player2P2Id,
|
||||
bracketPosition: idx + 1,
|
||||
status: "pending",
|
||||
})),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
include: {
|
||||
bracketMatchups: {
|
||||
include: {
|
||||
player1P1: true,
|
||||
player1P2: true,
|
||||
player2P1: true,
|
||||
player2P2: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
roundsCreated: created.length,
|
||||
matchupsCreated: created.reduce(
|
||||
(sum, r) => sum + r.bracketMatchups.length,
|
||||
0
|
||||
),
|
||||
rounds: created,
|
||||
});
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
roundsCreated: created.length,
|
||||
matchupsCreated: created.reduce(
|
||||
(sum, r) => sum + r.bracketMatchups.length,
|
||||
0
|
||||
),
|
||||
rounds: created,
|
||||
});
|
||||
|
||||
} else if (teamDurability === "variable") {
|
||||
// ============================================
|
||||
// OPTION 2: PRE-PLANNED VARIABLE
|
||||
// Fresh teams each round, generated before tournament starts
|
||||
// Partners rotate based on selected strategy
|
||||
// ============================================
|
||||
|
||||
// Track partnerships across all rounds to minimize repeats
|
||||
const allPreviousTeams: TeamPairing[][] = [];
|
||||
|
||||
// Create a function that generates teams with rotation
|
||||
const generateTeamWithRotation = (players: Player[]): TeamPairing[] => {
|
||||
// For pre-planned variable, we generate fresh teams each round
|
||||
// using the partner rotation strategy and tracking previous partnerships
|
||||
const result = generateTeamsWithRotation(players, allPreviousTeams, partnerRotation, allowByes);
|
||||
|
||||
// Store the generated teams for future rounds
|
||||
allPreviousTeams.push(result.teams);
|
||||
|
||||
return result.teams;
|
||||
};
|
||||
|
||||
// Generate the schedule with fresh teams each round
|
||||
const schedule = generateVariableRoundRobin(
|
||||
participants,
|
||||
teamCount,
|
||||
numRounds,
|
||||
generateTeamWithRotation
|
||||
);
|
||||
|
||||
// Create rounds and matchups in a transaction
|
||||
const created = await prisma.$transaction(
|
||||
schedule.map((round) =>
|
||||
prisma.tournamentRound.create({
|
||||
data: {
|
||||
eventId: tournamentId,
|
||||
roundNumber: round.roundNumber,
|
||||
status: "pending",
|
||||
bracketMatchups: {
|
||||
create: round.matchups.map((matchup, idx) => ({
|
||||
eventId: tournamentId,
|
||||
player1P1Id: matchup.player1P1Id,
|
||||
player1P2Id: matchup.player1P2Id,
|
||||
player2P1Id: matchup.player2P1Id,
|
||||
player2P2Id: matchup.player2P2Id,
|
||||
bracketPosition: idx + 1,
|
||||
status: "pending",
|
||||
})),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
bracketMatchups: {
|
||||
include: {
|
||||
player1P1: true,
|
||||
player1P2: true,
|
||||
player2P1: true,
|
||||
player2P2: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
roundsCreated: created.length,
|
||||
matchupsCreated: created.reduce(
|
||||
(sum, r) => sum + r.bracketMatchups.length,
|
||||
0
|
||||
),
|
||||
rounds: created,
|
||||
});
|
||||
|
||||
} else {
|
||||
// ============================================
|
||||
// OPTION 3: DYNAMIC/PROGRESSIVE
|
||||
// Teams formed based on results (bracket-style)
|
||||
// Cannot pre-generate full schedule
|
||||
// ============================================
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: "Dynamic tournaments require completing rounds before scheduling the next one",
|
||||
roundsCreated: 0,
|
||||
matchupsCreated: 0,
|
||||
rounds: [],
|
||||
requiresDynamicScheduling: true,
|
||||
});
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
console.error("Error generating schedule:", error);
|
||||
const message =
|
||||
|
||||
@@ -63,7 +63,18 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { name, format, eventDate, targetScore, allowTies, maxParticipants, tournamentType } = body;
|
||||
const {
|
||||
name,
|
||||
format,
|
||||
eventDate,
|
||||
targetScore,
|
||||
allowTies,
|
||||
maxParticipants,
|
||||
tournamentType,
|
||||
teamDurability,
|
||||
partnerRotation,
|
||||
allowByes
|
||||
} = body;
|
||||
|
||||
const tournament = await prisma.event.create({
|
||||
data: {
|
||||
@@ -78,6 +89,9 @@ export async function POST(request: Request) {
|
||||
allowTies: allowTies ?? false,
|
||||
maxParticipants: maxParticipants ? parseInt(maxParticipants) : null,
|
||||
description: body.description,
|
||||
teamDurability: teamDurability || "permanent",
|
||||
partnerRotation: partnerRotation || "none",
|
||||
allowByes: allowByes ?? true,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user