nextjs-rewrite (#5)
Reviewed-on: #5 Co-authored-by: David Gwilliam <dhgwilliam@gmail.com> Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #5.
This commit is contained in:
@@ -0,0 +1,306 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useRef, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import Navigation from "@/components/Navigation"
|
||||
|
||||
export default function UploadMatchesPage() {
|
||||
const router = useRouter()
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [selectedTournament, setSelectedTournament] = useState<string>("")
|
||||
const [error, setError] = useState("")
|
||||
const [success, setSuccess] = useState("")
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [tournaments, setTournaments] = useState<any[]>([])
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// Fetch tournaments on mount
|
||||
useEffect(() => {
|
||||
fetch(`${window.location.origin}/api/tournaments`)
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
if (data.tournaments) {
|
||||
setTournaments(data.tournaments)
|
||||
// If no tournaments exist, create one automatically
|
||||
if (data.tournaments.length === 0) {
|
||||
createDefaultTournament()
|
||||
} else if (data.tournaments.length > 0) {
|
||||
// Auto-select the most recent tournament
|
||||
setSelectedTournament(data.tournaments[0].id.toString())
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((err) => console.error("Failed to fetch tournaments:", err))
|
||||
}, [])
|
||||
|
||||
const createDefaultTournament = async () => {
|
||||
try {
|
||||
const response = await fetch(`${window.location.origin}/api/tournaments`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name: `Tournament ${new Date().toLocaleDateString()}`,
|
||||
format: "round_robin",
|
||||
eventDate: new Date().toISOString(),
|
||||
}),
|
||||
})
|
||||
const data = await response.json()
|
||||
if (response.ok && data.tournament) {
|
||||
setTournaments([data.tournament])
|
||||
setSelectedTournament(data.tournament.id.toString())
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error("Failed to create default tournament:", err)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) {
|
||||
if (!file.name.endsWith(".csv")) {
|
||||
setError("Please upload a CSV file")
|
||||
return
|
||||
}
|
||||
setSelectedFile(file)
|
||||
setError("")
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError("")
|
||||
setSuccess("")
|
||||
|
||||
if (!selectedFile) {
|
||||
setError("Please select a CSV file to upload")
|
||||
return
|
||||
}
|
||||
|
||||
if (!selectedTournament) {
|
||||
setError("Please select a tournament")
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const formData = new FormData()
|
||||
formData.append("csvFile", selectedFile)
|
||||
formData.append("eventId", selectedTournament)
|
||||
|
||||
const response = await fetch(`${window.location.origin}/api/matches/upload`, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || "Failed to upload CSV")
|
||||
}
|
||||
|
||||
setSuccess(
|
||||
`Successfully imported ${data.importedCount} matches. ` +
|
||||
`${data.errorCount || 0} errors occurred.` +
|
||||
(data.errors ? `\n\nErrors:\n${data.errors.join("\n")}` : "")
|
||||
)
|
||||
|
||||
// Reset form
|
||||
setSelectedFile(null)
|
||||
setSelectedTournament("")
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ""
|
||||
}
|
||||
} catch (err: any) {
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Navigation />
|
||||
|
||||
<main className="max-w-3xl mx-auto py-6 sm:px-6 lg:px-8">
|
||||
<div className="px-4 py-6 sm:px-0">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-6">
|
||||
Upload Match Results (CSV)
|
||||
</h1>
|
||||
|
||||
<div className="bg-white shadow rounded-lg p-6">
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{error && (
|
||||
<div className="rounded-md bg-red-50 p-4">
|
||||
<div className="text-sm text-red-700 whitespace-pre-wrap">
|
||||
{error}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div className="rounded-md bg-green-50 p-4">
|
||||
<div className="text-sm text-green-700 whitespace-pre-wrap">
|
||||
{success}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tournament Selection */}
|
||||
<div>
|
||||
<label htmlFor="tournament" className="block text-sm font-medium text-gray-700">
|
||||
Select Tournament *
|
||||
</label>
|
||||
<div className="mt-1 flex gap-2">
|
||||
<select
|
||||
id="tournament"
|
||||
value={selectedTournament}
|
||||
onChange={(e) => setSelectedTournament(e.target.value)}
|
||||
className="flex-1 block border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-green-500 focus:border-green-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Choose a tournament...</option>
|
||||
{tournaments.map((tournament) => (
|
||||
<option key={tournament.id} value={tournament.id}>
|
||||
{tournament.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const name = prompt("Enter tournament name:");
|
||||
if (name) {
|
||||
fetch(`${window.location.origin}/api/tournaments`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
format: "round_robin",
|
||||
eventDate: new Date().toISOString(),
|
||||
}),
|
||||
})
|
||||
.then((res) => res.json())
|
||||
.then((data) => {
|
||||
if (data.tournament) {
|
||||
setTournaments([...tournaments, data.tournament])
|
||||
setSelectedTournament(data.tournament.id.toString())
|
||||
}
|
||||
})
|
||||
.catch((err) => console.error("Failed to create tournament:", err))
|
||||
}
|
||||
}}
|
||||
className="px-3 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
|
||||
>
|
||||
New
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* File Upload */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
CSV File *
|
||||
</label>
|
||||
<div className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
|
||||
<div className="space-y-1 text-center">
|
||||
<svg
|
||||
className="mx-auto h-12 w-12 text-gray-400"
|
||||
stroke="currentColor"
|
||||
fill="none"
|
||||
viewBox="0 0 48 48"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
|
||||
strokeWidth={2}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
<div className="flex text-sm text-gray-600">
|
||||
<label
|
||||
htmlFor="file-upload"
|
||||
className="relative cursor-pointer bg-white rounded-md font-medium text-green-600 hover:text-green-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-green-500"
|
||||
>
|
||||
<span>Upload a file</span>
|
||||
<input
|
||||
id="file-upload"
|
||||
name="file-upload"
|
||||
type="file"
|
||||
className="sr-only"
|
||||
accept=".csv"
|
||||
onChange={handleFileChange}
|
||||
ref={fileInputRef}
|
||||
/>
|
||||
</label>
|
||||
<p className="pl-1">or drag and drop</p>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">
|
||||
CSV file with match results
|
||||
</p>
|
||||
{selectedFile && (
|
||||
<p className="text-sm text-green-600 mt-2">
|
||||
Selected: {selectedFile.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* CSV Format Guide */}
|
||||
<div className="bg-blue-50 rounded-md p-4">
|
||||
<h3 className="text-sm font-medium text-blue-800 mb-2">
|
||||
CSV Format Requirements
|
||||
</h3>
|
||||
<ul className="text-sm text-blue-700 space-y-1">
|
||||
<li><strong>Event #:</strong> Tournament ID (optional if selected above)</li>
|
||||
<li><strong>Round:</strong> Round number (1, 2, 3...)</li>
|
||||
<li><strong>Table:</strong> Table name (Clubs, Hearts, Diamonds, Spades, Stars)</li>
|
||||
<li><strong>Seat 1:</strong> Player 1 name (Odds team)</li>
|
||||
<li><strong>Seat 3:</strong> Player 2 name (Odds team)</li>
|
||||
<li><strong>Odds Points:</strong> Score for Odds team</li>
|
||||
<li><strong>Seat 2:</strong> Player 1 name (Evens team)</li>
|
||||
<li><strong>Seat 4:</strong> Player 2 name (Evens team)</li>
|
||||
<li><strong>Evens Points:</strong> Score for Evens team</li>
|
||||
<li><strong>Winner:</strong> "Odds" or "Evens" (optional)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? "Uploading..." : "Upload CSV"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* Sample CSV */}
|
||||
<div className="mt-6 bg-white shadow rounded-lg p-6">
|
||||
<h2 className="text-lg font-medium text-gray-900 mb-3">
|
||||
Sample CSV Format
|
||||
</h2>
|
||||
<pre className="bg-gray-50 rounded p-4 text-xs overflow-x-auto">
|
||||
{`Event #,Round,Table,Seat 1,Seat 3,Odds Points,Seat 2,Seat 4,Evens Points,Winner
|
||||
1,1,Clubs,Derrick,Jesse C,5,Emma,Alissa,10,Evens
|
||||
1,1,Hearts,Kevin,Andy,8,Ellie,Jesse,6,Odds`}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex justify-end">
|
||||
<button
|
||||
onClick={() => router.back()}
|
||||
className="text-green-600 hover:text-green-900"
|
||||
>
|
||||
← Back
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user