feat: Implement tournament schedule tab and fix E2E tests (#27)
Release / release (push) Failing after 9s
Build CI Images / build-ci-base (push) Failing after 18s

## Summary

This PR implements the tournament schedule tab functionality and fixes all remaining E2E test failures.

### Changes Included

1. **Tournament Schedule Feature**
   - Added tournament schedule page at `/admin/tournaments/[id]/schedule`
   - Implemented "Generate Schedule" button functionality
   - Added schedule generation logic for round-robin tournaments

2. **E2E Test Fixes**
   - Fixed database connection issues in production builds
   - Improved test reliability with better error handling and debugging
   - Updated test infrastructure to use environment variables instead of hardcoded values

3. **CI/CD Updates**
   - Added E2E test job to PR workflow
   - Configured tests to run against development database
   - Moved database password to Gitea secrets

4. **Code Quality**
   - Removed hardcoded passwords from codebase
   - Improved Prisma client configuration
   - Enhanced authentication and navigation components

### Test Results
All 16 E2E test scenarios are now passing:
- Authentication tests: 
- Registration tests: 
- Tournament schedule tests: 
- Player schedule tests: 
- Admin navigation tests: 

### Database Configuration
- Tests run against `euchre_camp_dev` database
- Production builds use environment variables for database configuration
- Database password stored in Gitea secrets as `DB_PASSWORD`

### CI Pipeline
The PR workflow now includes:
1. Unit tests
2. E2E tests (using production build)
3. Version bump analysis

E2E tests must pass before PR can be merged.

Reviewed-on: #27
Co-authored-by: David Gwilliam <dhgwilliam@gmail.com>
Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #27.
This commit is contained in:
2026-04-27 01:59:16 +00:00
committed by david
parent 75358bf20d
commit bb6be245b7
97 changed files with 7950 additions and 1341 deletions
+34
View File
@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { getSession } from '@/lib/auth-simple'
export async function GET(request: NextRequest) {
const session = await getSession()
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { searchParams } = new URL(request.url)
const limit = parseInt(searchParams.get('limit') || '20')
const offset = parseInt(searchParams.get('offset') || '0')
const type = searchParams.get('type')
const where: any = {}
if (type) {
where.type = type
}
const activities = await prisma.activity.findMany({
where,
orderBy: { createdAt: 'desc' },
take: limit,
skip: offset,
include: {
user: { select: { name: true } },
player: { select: { name: true } },
event: { select: { name: true } },
},
})
return NextResponse.json(activities)
}
+12 -12
View File
@@ -82,35 +82,35 @@ export async function POST(request: Request) {
// Update all foreign key references to point to canonical player
const updates = [];
// Update matches - team1P1Id
// Update matches - player1P1Id
updates.push(
prisma.match.updateMany({
where: { team1P1Id: { in: duplicatePlayers.map(p => p.id) } },
data: { team1P1Id: canonicalPlayer.id },
where: { player1P1Id: { in: duplicatePlayers.map(p => p.id) } },
data: { player1P1Id: canonicalPlayer.id },
})
);
// Update matches - team1P2Id
// Update matches - player1P2Id
updates.push(
prisma.match.updateMany({
where: { team1P2Id: { in: duplicatePlayers.map(p => p.id) } },
data: { team1P2Id: canonicalPlayer.id },
where: { player1P2Id: { in: duplicatePlayers.map(p => p.id) } },
data: { player1P2Id: canonicalPlayer.id },
})
);
// Update matches - team2P1Id
// Update matches - player2P1Id
updates.push(
prisma.match.updateMany({
where: { team2P1Id: { in: duplicatePlayers.map(p => p.id) } },
data: { team2P1Id: canonicalPlayer.id },
where: { player2P1Id: { in: duplicatePlayers.map(p => p.id) } },
data: { player2P1Id: canonicalPlayer.id },
})
);
// Update matches - team2P2Id
// Update matches - player2P2Id
updates.push(
prisma.match.updateMany({
where: { team2P2Id: { in: duplicatePlayers.map(p => p.id) } },
data: { team2P2Id: canonicalPlayer.id },
where: { player2P2Id: { in: duplicatePlayers.map(p => p.id) } },
data: { player2P2Id: canonicalPlayer.id },
})
);
+46
View File
@@ -0,0 +1,46 @@
import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { getSession } from '@/lib/auth-simple'
export async function GET() {
const session = await getSession()
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const settings = await (prisma as any).clubSettings.findFirst()
return NextResponse.json(settings)
}
export async function PATCH(request: NextRequest) {
const session = await getSession()
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const data = await request.json()
// Get the existing settings record (should be id: 1 or first record)
let settings = await (prisma as any).clubSettings.findFirst()
if (!settings) {
// Create default settings if none exist
settings = await (prisma as any).clubSettings.create({
data: {
clubName: 'Euchre Club',
defaultEloRating: 1200,
partnershipEnabled: true,
notificationsEnabled: true,
matchVerification: false,
},
})
}
// Update the settings
const updatedSettings = await (prisma as any).clubSettings.update({
where: { id: settings.id },
data,
})
return NextResponse.json(updatedSettings)
}
+4 -4
View File
@@ -119,10 +119,10 @@ export async function POST(request: Request) {
const createdMatch = await prisma.match.create({
data: matchData,
include: {
team1P1: true,
team1P2: true,
team2P1: true,
team2P2: true,
player1P1: true,
player1P2: true,
player2P1: true,
player2P2: true,
},
});
+8 -30
View File
@@ -59,32 +59,10 @@ export async function GET() {
name: true,
},
},
team1P1: { select: { id: true, name: true } },
team1P2: { select: { id: true, name: true } },
team2P1: { select: { id: true, name: true } },
team2P2: { select: { id: true, name: true } },
},
orderBy: { playedAt: 'desc' },
});
} else if (userRole === 'tournament_admin') {
// Tournament admins can only see matches in their own tournaments
matches = await prisma.match.findMany({
where: {
event: {
ownerId: userId,
},
},
include: {
event: {
select: {
id: true,
name: true,
},
},
team1P1: { select: { id: true, name: true } },
team1P2: { select: { id: true, name: true } },
team2P1: { select: { id: true, name: true } },
team2P2: { select: { id: true, name: true } },
player1P1: { select: { id: true, name: true } },
player1P2: { select: { id: true, name: true } },
player2P1: { select: { id: true, name: true } },
player2P2: { select: { id: true, name: true } },
},
orderBy: { playedAt: 'desc' },
});
@@ -236,10 +214,10 @@ export async function POST(request: Request) {
eventId: eventId ? parseInt(eventId) : null,
isCasual: isCasual,
playedAt: playedAt ? new Date(playedAt) : new Date(),
team1P1Id: parseInt(team1P1Id),
team1P2Id: parseInt(team1P2Id),
team2P1Id: parseInt(team2P1Id),
team2P2Id: parseInt(team2P2Id),
player1P1Id: parseInt(team1P1Id),
player1P2Id: parseInt(team1P2Id),
player2P1Id: parseInt(team2P1Id),
player2P2Id: parseInt(team2P2Id),
team1Score,
team2Score,
status: "completed",
+4 -4
View File
@@ -132,10 +132,10 @@ export async function POST(request: Request) {
data: {
eventId: parseInt(eventId),
playedAt: new Date(),
team1P1Id: players[0].id,
team1P2Id: players[1].id,
team2P1Id: players[2].id,
team2P2Id: players[3].id,
player1P1Id: players[0].id,
player1P2Id: players[1].id,
player2P1Id: players[2].id,
player2P2Id: players[3].id,
team1Score,
team2Score,
status: "completed",
+78 -3
View File
@@ -1,4 +1,4 @@
import { NextResponse } from "next/server";
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
/**
@@ -6,10 +6,22 @@ import { prisma } from "@/lib/prisma";
*
* Get all players with their user associations
* This is a public endpoint (no authentication required)
* Supports search query parameter
*/
export async function GET() {
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const search = searchParams.get('search') || ''
const limit = parseInt(searchParams.get('limit') || '50')
const offset = parseInt(searchParams.get('offset') || '0')
const where: any = {}
if (search) {
where.name = { contains: search, mode: 'insensitive' }
}
const players = await prisma.player.findMany({
where,
include: {
user: {
select: {
@@ -17,7 +29,9 @@ export async function GET() {
},
},
},
orderBy: { name: "asc" },
orderBy: { currentElo: 'desc' },
take: limit,
skip: offset,
});
return NextResponse.json(players);
@@ -30,3 +44,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 }
);
}
}
+1
View File
@@ -15,6 +15,7 @@ export async function GET(request: NextRequest) {
where: {
name: {
contains: query,
mode: "insensitive",
},
},
orderBy: { name: "asc" },
@@ -94,10 +94,10 @@ export async function POST(
await prisma.match.create({
data: {
eventId: tournamentId,
team1P1Id: player1.id,
team1P2Id: player2.id,
team2P1Id: player3.id,
team2P2Id: player4.id,
player1P1Id: player1.id,
player1P2Id: player2.id,
player2P1Id: player3.id,
player2P2Id: player4.id,
team1Score: game.score1,
team2Score: game.score2,
status: "completed",
@@ -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 }> }
@@ -36,7 +84,30 @@ export async function POST(
);
}
// Add participants to tournament
// Fetch tournament to check type
const tournament = await prisma.event.findUnique({
where: { id: tournamentId },
select: { tournamentType: true },
});
if (!tournament) {
return NextResponse.json(
{ error: "Tournament not found" },
{ status: 404 }
);
}
const isTeamTournament = tournament.tournamentType === "team";
// For team tournaments, validate even number of players
if (isTeamTournament && playerIds.length % 2 !== 0) {
return NextResponse.json(
{ error: "Team tournaments require an even number of players" },
{ status: 400 }
);
}
// Add participants - teams will be generated later during schedule generation
const participants = await Promise.all(
playerIds.map(async (playerId: number) => {
try {
@@ -83,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 }
);
}
}
+34 -49
View File
@@ -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);
@@ -45,28 +39,14 @@ export async function GET(request: Request, { params }: RouteParams) {
player: true,
},
},
teams: {
include: {
player1: true,
player2: true,
},
},
rounds: {
include: {
bracketMatchups: {
include: {
team1: {
include: {
player1: true,
player2: true,
},
},
team2: {
include: {
player1: true,
player2: true,
},
},
player1P1: true,
player1P2: true,
player2P1: true,
player2P2: true,
match: true,
},
},
@@ -104,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);
@@ -144,33 +124,43 @@ export async function PUT(request: Request, { params }: RouteParams) {
description,
eventDate,
eventType,
tournamentType,
format,
status,
maxParticipants,
ownerId,
targetScore,
allowTies,
teamDurability,
partnerRotation,
allowByes,
} = body;
// Validate required fields
if (!name || typeof name !== 'string' || name.trim().length === 0) {
return NextResponse.json(
{ error: "Tournament name is required" },
{ status: 400 }
);
// Validate name only if it's being updated
if (body.hasOwnProperty('name')) {
if (!name || typeof name !== 'string' || name.trim().length === 0) {
return NextResponse.json(
{ error: "Tournament name is required" },
{ status: 400 }
);
}
}
// Prepare update data
const updateData: Record<string, unknown> = {
name: name.trim(),
description: description || null,
eventDate: eventDate ? new Date(eventDate) : null,
eventType: eventType || "tournament",
format: format || "round_robin",
maxParticipants: maxParticipants ? parseInt(maxParticipants) : null,
targetScore: targetScore ? parseInt(targetScore) : null,
allowTies: allowTies ?? false,
};
// Prepare update data - only include fields that are present in the request
const updateData: Record<string, unknown> = {};
if (body.hasOwnProperty('name')) updateData.name = name.trim();
if (body.hasOwnProperty('description')) updateData.description = description || null;
if (body.hasOwnProperty('eventDate')) updateData.eventDate = eventDate ? new Date(eventDate) : null;
if (body.hasOwnProperty('eventType')) updateData.eventType = eventType || "tournament";
if (body.hasOwnProperty('tournamentType')) updateData.tournamentType = tournamentType || "individual";
if (body.hasOwnProperty('format')) updateData.format = format || "round_robin";
if (body.hasOwnProperty('maxParticipants')) updateData.maxParticipants = maxParticipants ? parseInt(maxParticipants) : null;
if (body.hasOwnProperty('targetScore')) updateData.targetScore = targetScore ? parseInt(targetScore) : null;
if (body.hasOwnProperty('allowTies')) updateData.allowTies = allowTies ?? false;
if (body.hasOwnProperty('teamDurability')) updateData.teamDurability = teamDurability || "permanent";
if (body.hasOwnProperty('partnerRotation')) updateData.partnerRotation = partnerRotation || "none";
if (body.hasOwnProperty('allowByes')) updateData.allowByes = allowByes ?? true;
// Only allow status updates if they don't conflict with auto-calculation
if (status) {
@@ -219,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);
@@ -285,11 +275,6 @@ export async function DELETE(request: Request, { params }: RouteParams) {
where: { eventId: tournamentId },
});
// Delete teams
await prisma.team.deleteMany({
where: { eventId: tournamentId },
});
// Delete tournament rounds
await prisma.tournamentRound.deleteMany({
where: { eventId: tournamentId },
@@ -0,0 +1,378 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { canManageTournament } from "@/lib/permissions";
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<{
id: string;
}>;
}
/**
* GET /api/tournaments/[id]/schedule
*
* Fetch the tournament schedule (rounds with matchups).
*/
export async function GET(_request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const tournamentId = parseInt(id);
if (isNaN(tournamentId)) {
return NextResponse.json(
{ error: "Invalid tournament ID" },
{ status: 400 }
);
}
const permission = await canManageTournament(tournamentId);
if (!permission.allowed) {
return NextResponse.json(
{ error: permission.reason || "Not authorized to view this tournament" },
{ status: 403 }
);
}
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) {
return NextResponse.json(
{ error: "Tournament not found" },
{ status: 404 }
);
}
return NextResponse.json({ rounds: tournament.rounds });
} catch (error: unknown) {
console.error("Error fetching schedule:", error);
const message =
error instanceof Error ? error.message : "Failed to fetch schedule";
return NextResponse.json({ error: message }, { status: 500 });
}
}
/**
* POST /api/tournaments/[id]/schedule
*
* Generate a round-robin schedule for the tournament.
* Creates TournamentRound and BracketMatchup records.
*/
export async function POST(_request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const tournamentId = parseInt(id);
if (isNaN(tournamentId)) {
return NextResponse.json(
{ error: "Invalid tournament ID" },
{ status: 400 }
);
}
const permission = await canManageTournament(tournamentId);
if (!permission.allowed) {
return NextResponse.json(
{ error: permission.reason || "Not authorized to manage this tournament" },
{ status: 403 }
);
}
// Check tournament exists
const tournament = await prisma.event.findUnique({
where: { id: tournamentId },
include: {
participants: {
include: {
player: true,
},
},
rounds: true,
},
});
if (!tournament) {
return NextResponse.json(
{ error: "Tournament not found" },
{ status: 404 }
);
}
// Check if schedule already exists and delete it
if (tournament.rounds.length > 0) {
// 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
const participants: Player[] = tournament.participants.map((p) => ({
id: p.player.id,
name: p.player.name,
currentElo: p.player.currentElo,
}));
// Check minimum participants
if (participants.length < 2) {
return NextResponse.json(
{ error: "At least 2 participants are required to generate a schedule" },
{ status: 400 }
);
}
// Generate teams based on configuration
const teamDurability = tournament.teamDurability || "permanent";
const partnerRotation = (tournament.partnerRotation || "none") as 'none' | 'minimize_repeat' | 'maximize_even' | 'elo_based';
const allowByes = tournament.allowByes ?? true;
// Determine number of teams from participants
const tempResult = generateTeams(participants, partnerRotation, allowByes);
const teamCount = tempResult.teams.length;
if (teamCount < 2) {
return NextResponse.json(
{ error: "At least 2 teams (4 players) are required to generate a schedule" },
{ status: 400 }
);
}
// Calculate number of rounds needed
const numRounds = expectedRounds(teamCount);
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,
});
} 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 =
error instanceof Error ? error.message : "Failed to generate schedule";
return NextResponse.json({ error: message }, { status: 500 });
}
}
/**
* DELETE /api/tournaments/[id]/schedule
*
* Delete all rounds and matchups for a tournament.
*/
export async function DELETE(_request: Request, { params }: RouteParams) {
try {
const { id } = await params;
const tournamentId = parseInt(id);
if (isNaN(tournamentId)) {
return NextResponse.json(
{ error: "Invalid tournament ID" },
{ status: 400 }
);
}
const permission = await canManageTournament(tournamentId);
if (!permission.allowed) {
return NextResponse.json(
{ error: permission.reason || "Not authorized to manage this tournament" },
{ status: 403 }
);
}
// Delete bracket matchups first (FK constraint)
const deletedMatchups = await prisma.bracketMatchup.deleteMany({
where: { eventId: tournamentId },
});
// Delete rounds
const deletedRounds = await prisma.tournamentRound.deleteMany({
where: { eventId: tournamentId },
});
return NextResponse.json({
success: true,
deletedRounds: deletedRounds.count,
deletedMatchups: deletedMatchups.count,
});
} catch (error: unknown) {
console.error("Error deleting schedule:", error);
const message =
error instanceof Error ? error.message : "Failed to delete schedule";
return NextResponse.json({ error: message }, { status: 500 });
}
}
+19 -8
View File
@@ -11,12 +11,6 @@ export async function GET() {
orderBy: { createdAt: "desc" },
include: {
participants: true,
teams: {
include: {
player1: true,
player2: true,
},
},
},
});
@@ -69,7 +63,18 @@ export async function POST(request: Request) {
}
const body = await request.json();
const { name, format, eventDate, targetScore, allowTies } = body;
const {
name,
format,
eventDate,
targetScore,
allowTies,
maxParticipants,
tournamentType,
teamDurability,
partnerRotation,
allowByes
} = body;
const tournament = await prisma.event.create({
data: {
@@ -77,10 +82,16 @@ export async function POST(request: Request) {
format: format || "round_robin",
eventDate: eventDate ? new Date(eventDate) : null,
eventType: "tournament",
tournamentType: tournamentType || "individual",
status: "planned",
ownerId: session.user.id, // Assign ownership to the creator
ownerId: session.user.id,
targetScore: targetScore ? parseInt(targetScore) : null,
allowTies: allowTies ?? false,
maxParticipants: maxParticipants ? parseInt(maxParticipants) : null,
description: body.description,
teamDurability: teamDurability || "permanent",
partnerRotation: partnerRotation || "none",
allowByes: allowByes ?? true,
},
});