feat: add manual match entry form and match detail pages with diagram

This commit is contained in:
2026-03-31 02:01:35 -07:00
parent e0d159ad8d
commit 141ca7c93e
6 changed files with 1164 additions and 186 deletions
+434 -80
View File
@@ -4,33 +4,82 @@ import { useState, useRef, useEffect } from "react"
import { useRouter } from "next/navigation"
import Navigation from "@/components/Navigation"
// Interface for a single manual match entry
interface ManualMatchEntry {
id: number
round: string
table: string
team1P1: string
team1P2: string
team2P1: string
team2P2: string
team1Score: string
team2Score: string
isCasual: boolean
}
export default function UploadMatchesPage() {
const router = useRouter()
const [activeTab, setActiveTab] = useState<"csv" | "manual">("csv")
// CSV Upload state
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [selectedTournament, setSelectedTournament] = useState<string>("")
const [error, setError] = useState("")
const [success, setSuccess] = useState("")
const [isLoading, setIsLoading] = useState(false)
const [tournaments, setTournaments] = useState<{ id: number; name: string }[]>([])
const [csvError, setCsvError] = useState("")
const [csvSuccess, setCsvSuccess] = useState("")
const [isCsvLoading, setIsCsvLoading] = useState(false)
const fileInputRef = useRef<HTMLInputElement>(null)
// Fetch tournaments on mount
// Manual Entry state
const [manualTournament, setManualTournament] = useState<string>("")
const [manualMatches, setManualMatches] = useState<ManualMatchEntry[]>([
{
id: Date.now(),
round: "",
table: "",
team1P1: "",
team1P2: "",
team2P1: "",
team2P2: "",
team1Score: "",
team2Score: "",
isCasual: false,
},
])
const [manualError, setManualError] = useState("")
const [manualSuccess, setManualSuccess] = useState("")
const [isManualLoading, setIsManualLoading] = useState(false)
// Player list for autocomplete
const [players, setPlayers] = useState<{ id: number; name: string }[]>([])
const [tournaments, setTournaments] = useState<{ id: number; name: string }[]>([])
// Fetch tournaments and players on mount
useEffect(() => {
// Fetch tournaments
fetch(`${window.location.origin}/api/tournaments`)
.then((res) => res.json())
.then((data) => {
if (data.tournaments) {
setTournaments(data.tournaments)
// If no tournaments exist, create one automatically
if (data.tournaments.length === 0) {
createDefaultTournament()
} else if (data.tournaments.length > 0) {
// Auto-select the most recent tournament
setSelectedTournament(data.tournaments[0].id.toString())
if (data.tournaments.length > 0) {
const recentId = data.tournaments[0].id.toString()
setSelectedTournament(recentId)
setManualTournament(recentId)
}
}
})
.catch((err) => console.error("Failed to fetch tournaments:", err))
// Fetch players
fetch(`${window.location.origin}/api/players`)
.then((res) => res.json())
.then((data) => {
if (data.players) {
setPlayers(data.players)
}
})
.catch((err) => console.error("Failed to fetch players:", err))
}, [])
const createDefaultTournament = async () => {
@@ -46,42 +95,45 @@ export default function UploadMatchesPage() {
})
const data = await response.json()
if (response.ok && data.tournament) {
setTournaments([data.tournament])
const newTournaments = [data.tournament]
setTournaments(newTournaments)
setSelectedTournament(data.tournament.id.toString())
setManualTournament(data.tournament.id.toString())
}
} catch (err) {
console.error("Failed to create default tournament:", err)
}
}
// CSV Upload handlers
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
if (!file.name.endsWith(".csv")) {
setError("Please upload a CSV file")
setCsvError("Please upload a CSV file")
return
}
setSelectedFile(file)
setError("")
setCsvError("")
}
}
const handleSubmit = async (e: React.FormEvent) => {
const handleCsvSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError("")
setSuccess("")
setCsvError("")
setCsvSuccess("")
if (!selectedFile) {
setError("Please select a CSV file to upload")
setCsvError("Please select a CSV file to upload")
return
}
if (!selectedTournament) {
setError("Please select a tournament")
setCsvError("Please select a tournament")
return
}
setIsLoading(true)
setIsCsvLoading(true)
try {
const formData = new FormData()
@@ -99,7 +151,7 @@ export default function UploadMatchesPage() {
throw new Error(data.error || "Failed to upload CSV")
}
setSuccess(
setCsvSuccess(
`Successfully imported ${data.importedCount} matches. ` +
`${data.errorCount || 0} errors occurred.` +
(data.errors ? `\n\nErrors:\n${data.errors.join("\n")}` : "")
@@ -107,18 +159,127 @@ export default function UploadMatchesPage() {
// Reset form
setSelectedFile(null)
setSelectedTournament("")
if (fileInputRef.current) {
fileInputRef.current.value = ""
}
} catch (err) {
if (err instanceof Error) {
setError(err.message)
setCsvError(err.message)
} else {
setError("An unknown error occurred")
setCsvError("An unknown error occurred")
}
} finally {
setIsLoading(false)
setIsCsvLoading(false)
}
}
// Manual Entry handlers
const addMatchEntry = () => {
const newEntry: ManualMatchEntry = {
id: Date.now(),
round: "",
table: "",
team1P1: "",
team1P2: "",
team2P1: "",
team2P2: "",
team1Score: "",
team2Score: "",
isCasual: false,
}
setManualMatches([...manualMatches, newEntry])
}
const removeMatchEntry = (id: number) => {
if (manualMatches.length > 1) {
setManualMatches(manualMatches.filter((m) => m.id !== id))
}
}
const updateMatchEntry = (id: number, field: keyof ManualMatchEntry, value: string | boolean) => {
setManualMatches(
manualMatches.map((m) => (m.id === id ? { ...m, [field]: value } : m))
)
}
const handleManualSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setManualError("")
setManualSuccess("")
if (!manualTournament) {
setManualError("Please select a tournament")
return
}
// Validate at least one match has required data
const validMatches = manualMatches.filter(
(m) =>
m.team1P1 && m.team1P2 && m.team2P1 && m.team2P2 && m.team1Score && m.team2Score
)
if (validMatches.length === 0) {
setManualError("Please enter at least one match with all player names and scores")
return
}
setIsManualLoading(true)
try {
const matchesData = validMatches.map((m) => ({
eventId: parseInt(manualTournament),
round: m.round ? parseInt(m.round) : undefined,
table: m.table || undefined,
team1P1Name: m.team1P1,
team1P2Name: m.team1P2,
team2P1Name: m.team2P1,
team2P2Name: m.team2P2,
team1Score: parseInt(m.team1Score),
team2Score: parseInt(m.team2Score),
isCasual: m.isCasual,
}))
const response = await fetch(`${window.location.origin}/api/matches/bulk`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ matches: matchesData }),
})
const data = await response.json()
if (!response.ok) {
throw new Error(data.error || "Failed to create matches")
}
setManualSuccess(
`Successfully created ${data.importedCount} matches. ` +
`${data.errorCount || 0} errors occurred.` +
(data.errors ? `\n\nErrors:\n${data.errors.join("\n")}` : "")
)
// Reset form
setManualMatches([
{
id: Date.now(),
round: "",
table: "",
team1P1: "",
team1P2: "",
team2P1: "",
team2P2: "",
team1Score: "",
team2Score: "",
isCasual: false,
},
])
} catch (err) {
if (err instanceof Error) {
setManualError(err.message)
} else {
setManualError("An unknown error occurred")
}
} finally {
setIsManualLoading(false)
}
}
@@ -126,26 +287,54 @@ export default function UploadMatchesPage() {
<div className="min-h-screen bg-gray-50">
<Navigation />
<main className="max-w-3xl mx-auto py-6 sm:px-6 lg:px-8">
<main className="max-w-4xl mx-auto py-6 sm:px-6 lg:px-8">
<div className="px-4 py-6 sm:px-0">
<h1 className="text-3xl font-bold text-gray-900 mb-6">
Upload Match Results (CSV)
Upload Match Results
</h1>
{/* Tab Navigation */}
<div className="border-b border-gray-200 mb-6">
<nav className="-mb-px flex space-x-8">
<button
onClick={() => setActiveTab("csv")}
className={`${
activeTab === "csv"
? "border-green-500 text-green-600"
: "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`}
>
CSV Upload
</button>
<button
onClick={() => setActiveTab("manual")}
className={`${
activeTab === "manual"
? "border-green-500 text-green-600"
: "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`}
>
Manual Entry
</button>
</nav>
</div>
<div className="bg-white shadow rounded-lg p-6">
<form onSubmit={handleSubmit} className="space-y-6">
{error && (
{/* CSV Upload Tab */}
{activeTab === "csv" && (
<form onSubmit={handleCsvSubmit} className="space-y-6">
{csvError && (
<div className="rounded-md bg-red-50 p-4">
<div className="text-sm text-red-700 whitespace-pre-wrap">
{error}
{csvError}
</div>
</div>
)}
{success && (
{csvSuccess && (
<div className="rounded-md bg-green-50 p-4">
<div className="text-sm text-green-700 whitespace-pre-wrap">
{success}
{csvSuccess}
</div>
</div>
)}
@@ -169,34 +358,6 @@ export default function UploadMatchesPage() {
</option>
))}
</select>
<button
type="button"
onClick={() => {
const name = prompt("Enter tournament name:");
if (name) {
fetch(`${window.location.origin}/api/tournaments`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name,
format: "round_robin",
eventDate: new Date().toISOString(),
}),
})
.then((res) => res.json())
.then((data) => {
if (data.tournament) {
setTournaments([...tournaments, data.tournament])
setSelectedTournament(data.tournament.id.toString())
}
})
.catch((err) => console.error("Failed to create tournament:", err))
}
}}
className="px-3 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
>
New
</button>
</div>
</div>
@@ -259,14 +420,13 @@ export default function UploadMatchesPage() {
<ul className="text-sm text-blue-700 space-y-1">
<li><strong>Event #:</strong> Tournament ID (optional if selected above)</li>
<li><strong>Round:</strong> Round number (1, 2, 3...)</li>
<li><strong>Table:</strong> Table name (Clubs, Hearts, Diamonds, Spades, Stars)</li>
<li><strong>Seat 1:</strong> Player 1 name (Odds team)</li>
<li><strong>Seat 3:</strong> Player 2 name (Odds team)</li>
<li><strong>Odds Points:</strong> Score for Odds team</li>
<li><strong>Seat 2:</strong> Player 1 name (Evens team)</li>
<li><strong>Seat 4:</strong> Player 2 name (Evens team)</li>
<li><strong>Evens Points:</strong> Score for Evens team</li>
<li><strong>Winner:</strong> &quot;Odds&quot; or &quot;Evens&quot; (optional)</li>
<li><strong>Table:</strong> Table name</li>
<li><strong>Seat 1:</strong> Player 1 name (Team 1)</li>
<li><strong>Seat 3:</strong> Player 2 name (Team 1)</li>
<li><strong>Odds Points:</strong> Score for Team 1</li>
<li><strong>Seat 2:</strong> Player 1 name (Team 2)</li>
<li><strong>Seat 4:</strong> Player 2 name (Team 2)</li>
<li><strong>Evens Points:</strong> Score for Team 2</li>
</ul>
</div>
@@ -274,26 +434,220 @@ export default function UploadMatchesPage() {
<div className="flex justify-end">
<button
type="submit"
disabled={isLoading}
disabled={isCsvLoading}
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
>
{isLoading ? "Uploading..." : "Upload CSV"}
{isCsvLoading ? "Uploading..." : "Upload CSV"}
</button>
</div>
</form>
)}
{/* Sample CSV */}
<div className="mt-6 bg-white shadow rounded-lg p-6">
<h2 className="text-lg font-medium text-gray-900 mb-3">
Sample CSV Format
</h2>
<pre className="bg-gray-50 rounded p-4 text-xs overflow-x-auto">
{`Event #,Round,Table,Seat 1,Seat 3,Odds Points,Seat 2,Seat 4,Evens Points,Winner
1,1,Clubs,Derrick,Jesse C,5,Emma,Alissa,10,Evens
1,1,Hearts,Kevin,Andy,8,Ellie,Jesse,6,Odds`}
</pre>
{/* Manual Entry Tab */}
{activeTab === "manual" && (
<form onSubmit={handleManualSubmit} className="space-y-6">
{manualError && (
<div className="rounded-md bg-red-50 p-4">
<div className="text-sm text-red-700 whitespace-pre-wrap">
{manualError}
</div>
</div>
)}
{manualSuccess && (
<div className="rounded-md bg-green-50 p-4">
<div className="text-sm text-green-700 whitespace-pre-wrap">
{manualSuccess}
</div>
</div>
)}
{/* Tournament Selection */}
<div>
<label className="block text-sm font-medium text-gray-700">
Select Tournament *
</label>
<div className="mt-1 flex gap-2">
<select
value={manualTournament}
onChange={(e) => setManualTournament(e.target.value)}
className="flex-1 block border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
>
<option value="">Choose a tournament...</option>
{tournaments.map((tournament) => (
<option key={tournament.id} value={tournament.id}>
{tournament.name}
</option>
))}
</select>
</div>
</div>
{/* Manual Match Entries */}
<div className="space-y-6">
<div className="flex items-center justify-between">
<h3 className="text-lg font-medium text-gray-900">
Match Entries ({manualMatches.length})
</h3>
<button
type="button"
onClick={addMatchEntry}
className="px-3 py-1 text-sm bg-green-100 text-green-700 rounded-md hover:bg-green-200"
>
+ Add Match
</button>
</div>
{manualMatches.map((match, index) => (
<div key={match.id} className="border border-gray-200 rounded-md p-4 space-y-4">
<div className="flex items-center justify-between">
<span className="font-medium text-gray-700">Match {index + 1}</span>
{manualMatches.length > 1 && (
<button
type="button"
onClick={() => removeMatchEntry(match.id)}
className="text-red-600 hover:text-red-800 text-sm"
>
Remove
</button>
)}
</div>
<div className="grid grid-cols-2 gap-4">
{/* Round and Table */}
<div>
<label className="block text-xs font-medium text-gray-500">
Round
</label>
<input
type="text"
value={match.round}
onChange={(e) => updateMatchEntry(match.id, "round", e.target.value)}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-green-500 focus:border-green-500"
placeholder="1"
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-500">
Table
</label>
<input
type="text"
value={match.table}
onChange={(e) => updateMatchEntry(match.id, "table", e.target.value)}
className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-green-500 focus:border-green-500"
placeholder="Table 1"
/>
</div>
</div>
{/* Team 1 */}
<div className="bg-blue-50 rounded-md p-3 space-y-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-blue-800">Team 1</span>
<input
type="number"
value={match.team1Score}
onChange={(e) => updateMatchEntry(match.id, "team1Score", e.target.value)}
className="w-16 text-center border border-blue-300 rounded py-1 px-2 text-sm"
placeholder="Score"
min="0"
/>
</div>
<div className="grid grid-cols-2 gap-2">
<input
type="text"
value={match.team1P1}
onChange={(e) => updateMatchEntry(match.id, "team1P1", e.target.value)}
list="players-list"
className="block w-full border border-blue-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Player 1"
/>
<input
type="text"
value={match.team1P2}
onChange={(e) => updateMatchEntry(match.id, "team1P2", e.target.value)}
list="players-list"
className="block w-full border border-blue-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
placeholder="Player 2"
/>
</div>
</div>
{/* Team 2 */}
<div className="bg-red-50 rounded-md p-3 space-y-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-red-800">Team 2</span>
<input
type="number"
value={match.team2Score}
onChange={(e) => updateMatchEntry(match.id, "team2Score", e.target.value)}
className="w-16 text-center border border-red-300 rounded py-1 px-2 text-sm"
placeholder="Score"
min="0"
/>
</div>
<div className="grid grid-cols-2 gap-2">
<input
type="text"
value={match.team2P1}
onChange={(e) => updateMatchEntry(match.id, "team2P1", e.target.value)}
list="players-list"
className="block w-full border border-red-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-red-500 focus:border-red-500"
placeholder="Player 1"
/>
<input
type="text"
value={match.team2P2}
onChange={(e) => updateMatchEntry(match.id, "team2P2", e.target.value)}
list="players-list"
className="block w-full border border-red-300 rounded-md shadow-sm py-1 px-2 text-sm focus:outline-none focus:ring-red-500 focus:border-red-500"
placeholder="Player 2"
/>
</div>
</div>
{/* Casual Match Checkbox */}
<div className="flex items-center">
<input
id={`casual-${match.id}`}
type="checkbox"
checked={match.isCasual}
onChange={(e) => updateMatchEntry(match.id, "isCasual", e.target.checked)}
className="h-4 w-4 text-green-600 focus:ring-green-500 border-gray-300 rounded"
/>
<label
htmlFor={`casual-${match.id}`}
className="ml-2 block text-sm text-gray-900"
>
Casual match (not part of a tournament)
</label>
</div>
</div>
))}
</div>
{/* Player autocomplete datalist */}
<datalist id="players-list">
{players.map((player) => (
<option key={player.id} value={player.name} />
))}
</datalist>
{/* Submit Button */}
<div className="flex justify-end pt-4 border-t">
<button
type="submit"
disabled={isManualLoading}
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
>
{isManualLoading ? "Creating Matches..." : "Create Matches"}
</button>
</div>
</form>
)}
{/* Back Button */}
<div className="mt-4 flex justify-end">
<button
onClick={() => router.back()}
@@ -102,9 +102,10 @@ export default async function TournamentResultsPage({ params }: PageProps) {
<div className="space-y-3">
{matches.slice(0, 10).map((match) => (
<div
<Link
key={match.id}
className="border border-gray-200 rounded p-3"
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">
@@ -116,7 +117,7 @@ export default async function TournamentResultsPage({ params }: PageProps) {
{match.team2P1.name} + {match.team2P2.name}
</p>
</div>
<div className="text-right">
<div className="text-right flex items-center">
<span className={`font-bold ${
match.team1Score > match.team2Score
? 'text-green-600'
@@ -136,9 +137,22 @@ export default async function TournamentResultsPage({ params }: PageProps) {
}`}>
{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>
</div>
</Link>
))}
</div>
</div>
+305
View File
@@ -0,0 +1,305 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { calculateTeamElo, calculateTeamEloChange } from "@/lib/elo-utils";
import { getSession } from "@/lib/auth-simple";
interface MatchInput {
eventId?: number;
round?: number;
table?: string;
team1P1Name: string;
team1P2Name: string;
team2P1Name: string;
team2P2Name: string;
team1Score: number;
team2Score: number;
isCasual?: boolean;
}
/**
* POST /api/matches/bulk
*
* Create multiple matches in bulk
*/
export async function POST(request: Request) {
try {
const body = await request.json();
const { matches } = body;
if (!Array.isArray(matches) || matches.length === 0) {
return NextResponse.json(
{ error: "matches array is required and must not be empty" },
{ status: 400 }
);
}
// Validate each match
const errors: string[] = [];
const validMatches: MatchInput[] = [];
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
const matchNum = i + 1;
if (!match.team1P1Name || !match.team1P2Name || !match.team2P1Name || !match.team2P2Name) {
errors.push(`Match ${matchNum}: All player names are required`);
continue;
}
if (typeof match.team1Score !== "number" || typeof match.team2Score !== "number") {
errors.push(`Match ${matchNum}: Scores must be numbers`);
continue;
}
if (match.team1Score < 0 || match.team2Score < 0) {
errors.push(`Match ${matchNum}: Scores cannot be negative`);
continue;
}
if (match.team1Score === match.team2Score && match.isCasual) {
// Allow ties in casual matches
}
validMatches.push(match);
}
const importedMatches: any[] = [];
// Process each valid match
for (const match of validMatches) {
try {
// Find or create players
const player1Name = match.team1P1Name.trim();
const player2Name = match.team1P2Name.trim();
const player3Name = match.team2P1Name.trim();
const player4Name = match.team2P2Name.trim();
const player1 = await findOrCreatePlayer(player1Name);
const player2 = await findOrCreatePlayer(player2Name);
const player3 = await findOrCreatePlayer(player3Name);
const player4 = await findOrCreatePlayer(player4Name);
// Check if this is a casual match or tournament match
const isCasual = match.isCasual || !match.eventId;
// Calculate ELO changes
const player1Rating = player1.currentElo;
const player2Rating = player2.currentElo;
const player3Rating = player3.currentElo;
const player4Rating = player4.currentElo;
const team1Rating = calculateTeamElo(player1Rating, player2Rating);
const team2Rating = calculateTeamElo(player3Rating, player4Rating);
const team1ScoreNormalized = match.team1Score > match.team2Score ? 1 : match.team1Score === match.team2Score ? 0.5 : 0;
const team1Change = calculateTeamEloChange(team1Rating, team2Rating, team1ScoreNormalized);
const team2Change = -team1Change;
const p1Change = Math.round(team1Change / 2);
const p2Change = Math.round(team1Change / 2);
const p3Change = Math.round(team2Change / 2);
const p4Change = Math.round(team2Change / 2);
// Create the match
const matchData: any = {
team1P1Id: player1.id,
team1P2Id: player2.id,
team2P1Id: player3.id,
team2P2Id: player4.id,
team1Score: match.team1Score,
team2Score: match.team2Score,
playedAt: new Date(),
isCasual,
};
if (match.eventId) {
matchData.eventId = match.eventId;
}
const createdMatch = await prisma.match.create({
data: matchData,
include: {
team1P1: true,
team1P2: true,
team2P1: true,
team2P2: true,
},
});
// Update player stats
await prisma.player.update({
where: { id: player1.id },
data: {
currentElo: player1.currentElo + p1Change,
gamesPlayed: { increment: 1 },
wins: match.team1Score > match.team2Score ? { increment: 1 } : undefined,
losses: match.team1Score < match.team2Score ? { increment: 1 } : undefined,
},
});
await prisma.player.update({
where: { id: player2.id },
data: {
currentElo: player2.currentElo + p2Change,
gamesPlayed: { increment: 1 },
wins: match.team1Score > match.team2Score ? { increment: 1 } : undefined,
losses: match.team1Score < match.team2Score ? { increment: 1 } : undefined,
},
});
await prisma.player.update({
where: { id: player3.id },
data: {
currentElo: player3.currentElo + p3Change,
gamesPlayed: { increment: 1 },
wins: match.team2Score > match.team1Score ? { increment: 1 } : undefined,
losses: match.team2Score < match.team1Score ? { increment: 1 } : undefined,
},
});
await prisma.player.update({
where: { id: player4.id },
data: {
currentElo: player4.currentElo + p4Change,
gamesPlayed: { increment: 1 },
wins: match.team2Score > match.team1Score ? { increment: 1 } : undefined,
losses: match.team2Score < match.team1Score ? { increment: 1 } : undefined,
},
});
// Create Elo snapshots
await prisma.eloSnapshot.createMany({
data: [
{ playerId: player1.id, matchId: createdMatch.id, ratingBefore: player1Rating, ratingAfter: player1Rating + p1Change, ratingChange: p1Change },
{ playerId: player2.id, matchId: createdMatch.id, ratingBefore: player2Rating, ratingAfter: player2Rating + p2Change, ratingChange: p2Change },
{ playerId: player3.id, matchId: createdMatch.id, ratingBefore: player3Rating, ratingAfter: player3Rating + p3Change, ratingChange: p3Change },
{ playerId: player4.id, matchId: createdMatch.id, ratingBefore: player4Rating, ratingAfter: player4Rating + p4Change, ratingChange: p4Change },
],
});
// Update partnership stats
await updatePartnershipStats(player1.id, player2.id, match.team1Score > match.team2Score, p1Change + p2Change);
await updatePartnershipStats(player3.id, player4.id, match.team2Score > match.team1Score, p3Change + p4Change);
// Add players to tournament if applicable
if (match.eventId) {
await prisma.eventParticipant.upsert({
where: {
eventId_playerId: {
eventId: match.eventId,
playerId: player1.id,
},
},
update: {},
create: { eventId: match.eventId, playerId: player1.id },
});
await prisma.eventParticipant.upsert({
where: {
eventId_playerId: {
eventId: match.eventId,
playerId: player2.id,
},
},
update: {},
create: { eventId: match.eventId, playerId: player2.id },
});
await prisma.eventParticipant.upsert({
where: {
eventId_playerId: {
eventId: match.eventId,
playerId: player3.id,
},
},
update: {},
create: { eventId: match.eventId, playerId: player3.id },
});
await prisma.eventParticipant.upsert({
where: {
eventId_playerId: {
eventId: match.eventId,
playerId: player4.id,
},
},
update: {},
create: { eventId: match.eventId, playerId: player4.id },
});
}
importedMatches.push(createdMatch);
} catch (error) {
const matchNum = validMatches.indexOf(match) + 1;
errors.push(`Match ${matchNum}: ${error instanceof Error ? error.message : "Unknown error"}`);
}
}
return NextResponse.json({
importedCount: importedMatches.length,
errorCount: errors.length,
errors: errors.length > 0 ? errors : undefined,
matches: importedMatches,
});
} catch (error) {
console.error("Error creating matches:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
async function findOrCreatePlayer(name: string) {
const normalizedName = name.trim().toLowerCase();
let player = await prisma.player.findFirst({
where: { normalizedName },
});
if (!player) {
player = await prisma.player.create({
data: {
name: name.trim(),
normalizedName,
rating: 1000,
currentElo: 1000,
},
});
}
return player;
}
async function updatePartnershipStats(player1Id: number, player2Id: number, won: boolean, eloChange: number) {
// Ensure player1Id < player2Id for consistent key generation
const [smallId, largeId] = player1Id < player2Id ? [player1Id, player2Id] : [player2Id, player1Id];
const existingStat = await prisma.partnershipStat.findFirst({
where: {
player1Id: smallId,
player2Id: largeId,
},
});
if (existingStat) {
await prisma.partnershipStat.update({
where: { id: existingStat.id },
data: {
gamesPlayed: { increment: 1 },
wins: won ? { increment: 1 } : undefined,
losses: won ? undefined : { increment: 1 },
totalEloChange: { increment: eloChange },
lastPlayed: new Date(),
},
});
} else {
await prisma.partnershipStat.create({
data: {
player1Id: smallId,
player2Id: largeId,
gamesPlayed: 1,
wins: won ? 1 : 0,
losses: won ? 0 : 1,
totalEloChange: eloChange,
lastPlayed: new Date(),
},
});
}
}
+299
View File
@@ -0,0 +1,299 @@
import { prisma } from "@/lib/prisma";
import { notFound } from "next/navigation";
import Link from "next/link";
import Navigation from "@/components/Navigation";
interface PageProps {
params: {
id: string;
};
}
export default async function MatchDetailPage({ params }: PageProps) {
const { id } = await params;
const matchId = parseInt(id, 10);
if (isNaN(matchId)) {
notFound();
}
// Fetch match with all player data
const match = await prisma.match.findUnique({
where: { id: matchId },
include: {
team1P1: true,
team1P2: true,
team2P1: true,
team2P2: true,
event: true,
eloSnapshots: {
include: {
player: true,
},
orderBy: {
playerId: "asc",
},
},
},
});
if (!match) {
notFound();
}
// Calculate Elo changes from snapshots
const eloChanges: { [playerId: number]: number } = {};
match.eloSnapshots.forEach((snapshot) => {
eloChanges[snapshot.playerId] = snapshot.ratingChange;
});
return (
<div className="min-h-screen bg-gray-50">
<Navigation />
<main className="max-w-3xl mx-auto py-6 sm:px-6 lg:px-8">
<div className="px-4 py-6 sm:px-0">
{/* Header */}
<div className="mb-6">
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold text-gray-900">
Match #{match.id}
</h1>
<Link
href="/matches"
className="text-green-600 hover:text-green-900"
>
All Matches
</Link>
</div>
{match.event && (
<p className="mt-2 text-sm text-gray-600">
Part of{" "}
<Link
href={`/admin/tournaments/${match.event.id}`}
className="text-green-600 hover:text-green-900"
>
{match.event.name}
</Link>
</p>
)}
</div>
{/* Match Diagram */}
<div className="bg-white shadow rounded-lg p-6 mb-6">
<h2 className="text-xl font-bold text-gray-900 mb-4">Match Setup</h2>
<div className="flex justify-center">
<div className="relative">
{/* Table Square */}
<div className="w-48 h-48 bg-amber-100 border-4 border-amber-600 rounded-lg relative shadow-lg">
{/* Team 1 (Top) */}
<div className="absolute top-0 left-0 right-0 h-1/2 flex flex-col justify-end items-center pb-2 space-y-1">
<div className="text-center">
<p className="text-sm font-medium text-amber-900">
{match.team1P1.name}
</p>
<p className="text-xs text-amber-700">
Elo: {match.team1P1.currentElo}
{eloChanges[match.team1P1.id] !== undefined && (
<span className={eloChanges[match.team1P1.id] >= 0 ? "text-green-600 ml-1" : "text-red-600 ml-1"}>
({eloChanges[match.team1P1.id] >= 0 ? "+" : ""}{eloChanges[match.team1P1.id]})
</span>
)}
</p>
</div>
<div className="text-xs text-amber-600">Team 1</div>
</div>
{/* Team 2 (Bottom) */}
<div className="absolute bottom-0 left-0 right-0 h-1/2 flex flex-col justify-start items-center pt-2 space-y-1">
<div className="text-xs text-red-600">Team 2</div>
<div className="text-center">
<p className="text-sm font-medium text-red-900">
{match.team2P1.name}
</p>
<p className="text-xs text-red-700">
Elo: {match.team2P1.currentElo}
{eloChanges[match.team2P1.id] !== undefined && (
<span className={eloChanges[match.team2P1.id] >= 0 ? "text-green-600 ml-1" : "text-red-600 ml-1"}>
({eloChanges[match.team2P1.id] >= 0 ? "+" : ""}{eloChanges[match.team2P1.id]})
</span>
)}
</p>
</div>
<div className="text-center">
<p className="text-sm font-medium text-red-900">
{match.team2P2.name}
</p>
<p className="text-xs text-red-700">
Elo: {match.team2P2.currentElo}
{eloChanges[match.team2P2.id] !== undefined && (
<span className={eloChanges[match.team2P2.id] >= 0 ? "text-green-600 ml-1" : "text-red-600 ml-1"}>
({eloChanges[match.team2P2.id] >= 0 ? "+" : ""}{eloChanges[match.team2P2.id]})
</span>
)}
</p>
</div>
</div>
{/* Left side - Team 1 (Player 2) */}
<div className="absolute left-0 top-0 bottom-0 w-1/2 flex flex-col justify-center items-center pl-2">
<div className="text-center rotate-[-90deg]">
<p className="text-xs font-medium text-amber-900">
{match.team1P2.name}
</p>
<p className="text-[10px] text-amber-700">
Elo: {match.team1P2.currentElo}
{eloChanges[match.team1P2.id] !== undefined && (
<span className={eloChanges[match.team1P2.id] >= 0 ? "text-green-600" : "text-red-600"}>
({eloChanges[match.team1P2.id] >= 0 ? "+" : ""}{eloChanges[match.team1P2.id]})
</span>
)}
</p>
</div>
</div>
{/* Right side - Team 2 (Player 2) */}
<div className="absolute right-0 top-0 bottom-0 w-1/2 flex flex-col justify-center items-center pr-2">
<div className="text-center rotate-[90deg]">
<p className="text-xs font-medium text-red-900">
{match.team2P2.name}
</p>
<p className="text-[10px] text-red-700">
Elo: {match.team2P2.currentElo}
{eloChanges[match.team2P2.id] !== undefined && (
<span className={eloChanges[match.team2P2.id] >= 0 ? "text-green-600" : "text-red-600"}>
({eloChanges[match.team2P2.id] >= 0 ? "+" : ""}{eloChanges[match.team2P2.id]})
</span>
)}
</p>
</div>
</div>
{/* Score in Center */}
<div className="absolute inset-0 flex items-center justify-center">
<div className="bg-white border-2 border-gray-300 rounded-lg px-4 py-2 shadow-md">
<div className="text-center">
<p className="text-lg font-bold text-amber-600">
{match.team1Score}
</p>
<p className="text-xs text-gray-500">Team 1</p>
</div>
<div className="text-center text-gray-400"></div>
<div className="text-center">
<p className="text-lg font-bold text-red-600">
{match.team2Score}
</p>
<p className="text-xs text-gray-500">Team 2</p>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Legend */}
<div className="mt-4 flex justify-center gap-6 text-sm">
<div className="flex items-center">
<div className="w-3 h-3 bg-amber-100 border border-amber-600 rounded mr-2"></div>
<span>Team 1</span>
</div>
<div className="flex items-center">
<div className="w-3 h-3 bg-red-100 border border-red-600 rounded mr-2"></div>
<span>Team 2</span>
</div>
</div>
</div>
{/* Match Details */}
<div className="bg-white shadow rounded-lg p-6 mb-6">
<h2 className="text-xl font-bold text-gray-900 mb-4">Match Details</h2>
<dl className="grid grid-cols-2 gap-4">
<div>
<dt className="text-sm font-medium text-gray-500">Match ID</dt>
<dd className="mt-1 text-sm text-gray-900">{match.id}</dd>
</div>
{match.playedAt && (
<div>
<dt className="text-sm font-medium text-gray-500">Date Played</dt>
<dd className="mt-1 text-sm text-gray-900">
{new Date(match.playedAt).toLocaleDateString()}
</dd>
</div>
)}
{match.event && (
<div>
<dt className="text-sm font-medium text-gray-500">Tournament</dt>
<dd className="mt-1 text-sm text-gray-900">
<Link
href={`/admin/tournaments/${match.event.id}`}
className="text-green-600 hover:text-green-900"
>
{match.event.name}
</Link>
</dd>
</div>
)}
<div>
<dt className="text-sm font-medium text-gray-500">Match Type</dt>
<dd className="mt-1 text-sm text-gray-900">
{match.isCasual ? "Casual" : "Tournament"}
</dd>
</div>
</dl>
</div>
{/* Elo Changes */}
<div className="bg-white shadow rounded-lg p-6">
<h2 className="text-xl font-bold text-gray-900 mb-4">Elo Changes</h2>
<div className="grid grid-cols-2 gap-4">
{/* Team 1 */}
<div className="bg-amber-50 rounded-md p-4">
<h3 className="font-medium text-amber-900 mb-3">Team 1</h3>
<div className="space-y-2">
<div className="flex justify-between items-center">
<span>{match.team1P1.name}</span>
<span className={eloChanges[match.team1P1.id] >= 0 ? "text-green-600" : "text-red-600"}>
{eloChanges[match.team1P1.id] >= 0 ? "+" : ""}{eloChanges[match.team1P1.id]}
</span>
</div>
<div className="flex justify-between items-center">
<span>{match.team1P2.name}</span>
<span className={eloChanges[match.team1P2.id] >= 0 ? "text-green-600" : "text-red-600"}>
{eloChanges[match.team1P2.id] >= 0 ? "+" : ""}{eloChanges[match.team1P2.id]}
</span>
</div>
</div>
</div>
{/* Team 2 */}
<div className="bg-red-50 rounded-md p-4">
<h3 className="font-medium text-red-900 mb-3">Team 2</h3>
<div className="space-y-2">
<div className="flex justify-between items-center">
<span>{match.team2P1.name}</span>
<span className={eloChanges[match.team2P1.id] >= 0 ? "text-green-600" : "text-red-600"}>
{eloChanges[match.team2P1.id] >= 0 ? "+" : ""}{eloChanges[match.team2P1.id]}
</span>
</div>
<div className="flex justify-between items-center">
<span>{match.team2P2.name}</span>
<span className={eloChanges[match.team2P2.id] >= 0 ? "text-green-600" : "text-red-600"}>
{eloChanges[match.team2P2.id] >= 0 ? "+" : ""}{eloChanges[match.team2P2.id]}
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
);
}
+4 -3
View File
@@ -168,9 +168,10 @@ export default async function Home() {
</h4>
<div className="space-y-3 max-h-96 overflow-y-auto">
{mostRecentTournament.matches.map((match) => (
<div
<Link
key={match.id}
className="bg-gray-50 rounded-lg p-4 border border-gray-200"
href={`/matches/${match.id}`}
className="block bg-gray-50 rounded-lg p-4 border border-gray-200 hover:border-green-300 hover:bg-green-50 transition-colors"
>
<div className="flex justify-between items-center">
<div className="flex-1 text-center">
@@ -199,7 +200,7 @@ export default async function Home() {
</span>
)}
</div>
</div>
</Link>
))}
</div>
</div>
+5
View File
@@ -251,9 +251,14 @@ export default async function PlayerProfilePage({ params }: PageProps) {
return (
<tr key={match.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
<Link
href={`/matches/${match.id}`}
className="text-green-600 hover:text-green-900"
>
{match.playedAt
? new Date(match.playedAt).toLocaleDateString()
: "N/A"}
</Link>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{match.event?.name || "N/A"}