all that's left is adding slightly better error handling for map to check if a hunt is active or not and to add the clues pages.

Grey = cant click
Red = current
Green = complete
blue = skipped?
This commit is contained in:
bobbert committed 2025-03-16 17:33:55 +00:00
1 parent 95348df5a9
commit 0269fdfe68
8 files changed
+601 -22

No files matched your search

+12 -9
View File
@@ -275,23 +275,26 @@ export default function TeamPage({ params }) {
)} )}
</div> </div>
{/* Replace the outdated navbar with the correct one */}
<div className="nav-bar"> <div className="nav-bar">
{/* Update the Home link to point to the current team page */} <Link href="/map" className="nav-item">
<Link href={`/${teamId}`} className="nav-item"> <div className="nav-icon">🗺️</div>
<div className="nav-icon">🏠</div> <div className="nav-label">Map</div>
<div className="nav-label">Home</div>
</Link> </Link>
<Link href="/leaderboard" className="nav-item"> <Link href="/stats" className="nav-item">
<div className="nav-icon">📊</div> <div className="nav-icon">📊</div>
<div className="nav-label">Stats</div> <div className="nav-label">Stats</div>
</Link> </Link>
<Link href="/team-selection" className="nav-item active"> <Link
href={team ? `/${team.id}` : "/team-selection"}
className="nav-item active"
>
<div className="nav-icon">👥</div> <div className="nav-icon">👥</div>
<div className="nav-label">Team</div> <div className="nav-label">Team</div>
</Link> </Link>
<Link href="/profile" className="nav-item"> <Link href="/leaderboard" className="nav-item">
<div className="nav-icon">👤</div> <div className="nav-icon">🏆</div>
<div className="nav-label">Profile</div> <div className="nav-label">Leaderboard</div>
</Link> </Link>
</div> </div>
+210
View File
@@ -0,0 +1,210 @@
"use client";
import { useState, useEffect } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import styles from "./stats.module.css";
export default function StatsPage() {
const { data: session, status } = useSession();
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [teamStats, setTeamStats] = useState(null);
const [expanded, setExpanded] = useState(false);
const router = useRouter();
useEffect(() => {
// Redirect to login if not authenticated
if (status === "unauthenticated") {
router.push("/login");
return;
}
if (status === "authenticated") {
fetchTeamStats();
}
}, [status, router]);
const fetchTeamStats = async () => {
try {
setLoading(true);
setError(null);
const response = await fetch("/api/team-stats", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate",
},
credentials: "include",
});
if (!response.ok) {
// Handle specific error cases
const errorData = await response.json().catch(() => ({}));
if (response.status === 401) {
throw new Error("Authentication error: Not logged in");
} else if (
response.status === 404 ||
errorData.error?.includes("not part of a team")
) {
throw new Error("You need to join a team before viewing stats");
} else {
throw new Error(errorData.error || "Failed to fetch team stats");
}
}
const data = await response.json();
setTeamStats(data);
} catch (err) {
console.error("Error fetching team stats:", err);
setError(err.message);
} finally {
setLoading(false);
}
};
const toggleExpanded = () => {
setExpanded(!expanded);
};
// Format timestamp to a more readable format
const formatTimestamp = (timestamp) => {
const date = new Date(timestamp);
return date.toLocaleString(undefined, {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
};
if (loading) {
return (
<div className={styles.container}>
<div className={styles.loadingSpinner}></div>
<p className={styles.loadingText}>Loading team stats...</p>
</div>
);
}
if (error) {
return (
<div className={styles.container}>
<div className={styles.errorContainer}>
<h2 className={styles.errorTitle}>Error</h2>
<p className={styles.errorMessage}>{error}</p>
<div className={styles.buttonContainer}>
<button onClick={fetchTeamStats} className={styles.retryButton}>
Retry
</button>
<button
onClick={() => router.push("/team-selection")}
className={styles.teamButton}
>
Join a Team
</button>
</div>
</div>
</div>
);
}
if (!teamStats) {
return (
<div className={styles.container}>
<p className={styles.noData}>No team stats available.</p>
</div>
);
}
return (
<div className={styles.container}>
<div className={styles.header}>
<h1 className={styles.title}>Team Stats</h1>
<h2 className={styles.teamName}>{teamStats.team.name}</h2>
</div>
<div className={styles.statsCard}>
<div className={styles.summaryStats}>
<div className={styles.statItem}>
<span className={styles.statLabel}>Total Clues:</span>
<span className={styles.statValue}>{teamStats.totalClues}</span>
</div>
<div className={styles.statItem}>
<span className={styles.statLabel}>Clues Found:</span>
<span className={styles.statValue}>
{teamStats.foundClues.length}
</span>
</div>
<div className={styles.statItem}>
<span className={styles.statLabel}>Clues Remaining:</span>
<span className={styles.statValue}>{teamStats.remainingClues}</span>
</div>
<div className={styles.statItem}>
<span className={styles.statLabel}>Clues Skipped:</span>
<span className={styles.statValue}>{teamStats.skippedClues}</span>
</div>
<div className={`${styles.statItem} ${styles.rankItem}`}>
<span className={styles.statLabel}>Current Rank:</span>
<span className={styles.statValue}>{teamStats.currentRank}</span>
</div>
</div>
<div className={styles.collapsibleSection}>
<button
className={styles.collapsibleButton}
onClick={toggleExpanded}
aria-expanded={expanded}
>
<span className={styles.collapsibleTitle}>
Clues Found: {teamStats.foundClues.length}
</span>
<span className={styles.collapsibleIcon}>
{expanded ? "▼" : "►"}
</span>
</button>
{expanded && (
<div className={styles.cluesList}>
{teamStats.foundClues.length === 0 ? (
<p className={styles.emptyMessage}>No clues found yet.</p>
) : (
teamStats.foundClues.map((clue) => (
<div key={clue.id} className={styles.clueItem}>
<span className={styles.clueTitle}>{clue.title}</span>
<span className={styles.clueTimestamp}>
{formatTimestamp(clue.found_at)}
</span>
</div>
))
)}
</div>
)}
</div>
</div>
<div className={styles.navBar}>
<Link href="/map" className={styles.navItem}>
<div className={styles.navIcon}>🗺️</div>
<div className={styles.navLabel}>Map</div>
</Link>
<Link href="/stats" className={`${styles.navItem} ${styles.active}`}>
<div className={styles.navIcon}>📊</div>
<div className={styles.navLabel}>Stats</div>
</Link>
<Link
href={teamStats?.team ? `/${teamStats.team.id}` : "/team-selection"}
className={styles.navItem}
>
<div className={styles.navIcon}>👥</div>
<div className={styles.navLabel}>Team</div>
</Link>
<Link href="/leaderboard" className={styles.navItem}>
<div className={styles.navIcon}>🏆</div>
<div className={styles.navLabel}>Leaderboard</div>
</Link>
</div>
</div>
);
}
+243
View File
@@ -0,0 +1,243 @@
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
background-color: #f4f4f4;
padding-bottom: 70px; /* Space for the navbar */
}
.header {
background-color: #68543c;
color: white;
padding: 20px;
text-align: center;
}
.title {
font-size: 1.5rem;
margin: 0 0 5px 0;
}
.teamName {
font-size: 1.2rem;
margin: 0;
font-weight: normal;
}
.statsCard {
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
margin: 20px;
overflow: hidden;
}
.summaryStats {
padding: 20px;
border-bottom: 1px solid #eee;
}
.statItem {
display: flex;
justify-content: space-between;
padding: 10px 0;
border-bottom: 1px solid #f0f0f0;
}
.statItem:last-child {
border-bottom: none;
}
.rankItem {
font-weight: bold;
color: #68543c;
margin-top: 10px;
padding-top: 10px;
border-top: 2px dashed #eee;
}
.statLabel {
color: #555;
}
.statValue {
font-weight: bold;
}
.collapsibleSection {
overflow: hidden;
}
.collapsibleButton {
width: 100%;
padding: 15px 20px;
text-align: left;
background-color: #f5f5f5;
border: none;
outline: none;
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 1rem;
font-weight: 600;
color: #333;
transition: background-color 0.2s;
}
.collapsibleButton:hover {
background-color: #e9e9e9;
}
.collapsibleTitle {
display: flex;
align-items: center;
}
.collapsibleIcon {
font-size: 0.8rem;
transition: transform 0.3s ease;
}
.cluesList {
padding: 0;
}
.clueItem {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px 20px;
border-bottom: 1px solid #f0f0f0;
}
.clueItem:last-child {
border-bottom: none;
}
.clueTitle {
flex: 1;
font-size: 0.95rem;
}
.clueTimestamp {
color: #888;
font-size: 0.85rem;
}
.emptyMessage {
padding: 20px;
text-align: center;
color: #888;
font-style: italic;
}
/* Loading state */
.loadingSpinner {
border: 4px solid rgba(0, 0, 0, 0.1);
border-radius: 50%;
border-top: 4px solid #68543c;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 50px auto 20px;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.loadingText {
text-align: center;
color: #555;
}
/* Error state */
.errorContainer {
margin: 40px 20px;
background-color: #fff3f3;
border: 1px solid #ffcdd2;
border-radius: 8px;
padding: 20px;
text-align: center;
}
.errorTitle {
color: #d32f2f;
margin-top: 0;
}
.buttonContainer {
display: flex;
justify-content: center;
gap: 10px;
margin-top: 20px;
}
.retryButton,
.teamButton {
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 0.9rem;
}
.retryButton {
background-color: #68543c;
color: white;
}
.teamButton {
background-color: #4caf50;
color: white;
}
.noData {
text-align: center;
padding: 40px 0;
color: #888;
}
/* Navigation Bar */
.navBar {
display: flex;
justify-content: space-around;
background-color: white;
border-top: 1px solid #ddd;
padding: 10px 0;
position: fixed;
bottom: 0;
left: 0;
width: 100%;
box-sizing: border-box;
z-index: 100;
}
.navItem {
display: flex;
flex-direction: column;
align-items: center;
text-decoration: none;
color: #666;
flex: 1;
padding: 8px 0;
}
.navIcon {
font-size: 22px;
margin-bottom: 3px;
}
.navLabel {
font-size: 12px;
}
.navItem.active {
color: #68543c;
}
+17 -13
View File
@@ -341,22 +341,26 @@ export default function TeamPage({ params }) {
)} )}
</div> </div>
<div className="nav-bar"> {/* Replace the outdated navbar with this consistent design */}av-bar"]}>
<Link href={`/${teamId}`} className="nav-item"> <div className="nav-bar">v-item"]}>
<div className="nav-icon">🏠</div> <Link href="/map" className="nav-item">>🗺️</div>
<div className="nav-label">Home</div> <div className="nav-icon">🗺️</div>>Map</div>
</Link> <div className="nav-label">Map</div>
<Link href="/leaderboard" className="nav-item"> </Link>v-item"]}>
<div className="nav-icon">📊</div> <Link href="/stats" className="nav-item">}>📊</div>
<div className="nav-icon">📊</div>tats</div>
<div className="nav-label">Stats</div> <div className="nav-label">Stats</div>
</Link> </Link>
<Link href="/team-selection" className="nav-item active"> <Link
<div className="nav-icon">👥</div> href={teamData ? `/${teamData.id}` : "/team-selection"} tem"]} ${styles["active"]}`}
className="nav-item active"
>}>👥</div>
<div className="nav-icon">👥</div>Team</div>
<div className="nav-label">Team</div> <div className="nav-label">Team</div>
</Link> </Link>v-item"]}>
<Link href="/profile" className="nav-item"> <Link href="/leaderboard" className="nav-item">}>🏆</div>
<div className="nav-icon">👤</div> <div className="nav-icon">🏆</div>oard</div>
<div className="nav-label">Profile</div> <div className="nav-label">Leaderboard</div>
</Link> </Link>
</div> </div>
+119
View File
@@ -0,0 +1,119 @@
import { query, queryOne } from "@/lib/db";
import { getToken } from "next-auth/jwt";
export const dynamic = "force-dynamic"; // Disable caching
export async function GET(request) {
try {
// Verify authentication
const token = await getToken({
req: request,
secret:
process.env.NEXTAUTH_SECRET ||
"your-fallback-secret-should-be-at-least-32-chars",
});
if (!token) {
return Response.json({ error: "Unauthorized" }, { status: 401 });
}
// Check if user has a team
if (!token.teamId) {
return Response.json(
{ error: "You are not part of a team" },
{ status: 404 }
);
}
// Get team information
const team = await queryOne(
"SELECT id, name, code FROM teams WHERE id = ?",
[token.teamId]
);
if (!team) {
return Response.json({ error: "Team not found" }, { status: 404 });
}
// Get total number of clues
const clueCountResult = await queryOne(
"SELECT COUNT(*) as total FROM clues"
);
const totalClues = clueCountResult?.total || 0;
// Get all found clues with timestamps, ordered by found time
const foundClues = await query(
`
SELECT c.id, c.title, tc.found_at
FROM clues c
JOIN team_clues tc ON c.id = tc.clue_id
WHERE tc.team_id = ?
ORDER BY tc.found_at ASC
`,
[token.teamId]
);
// We need to calculate skipped clues - these are clues that have higher IDs than the user's lowest unfound clue
// First, get all clue IDs
const allClueIds = await query("SELECT id FROM clues ORDER BY id ASC");
// Convert to a simple array of IDs
const allClueIdArray = allClueIds.map((c) => c.id);
// Create a set of found clue IDs for easy lookup
const foundClueIdSet = new Set(foundClues.map((c) => c.id));
// Find all unfound clue IDs
const unfoundClueIds = allClueIdArray.filter(
(id) => !foundClueIdSet.has(id)
);
// If there are unfound clues, the ones after the first unfound are "skipped"
let skippedClues = 0;
if (unfoundClueIds.length > 0) {
const lowestUnfoundId = Math.min(...unfoundClueIds);
// Skipped clues are found clues with IDs higher than the lowest unfound
skippedClues = foundClues.filter((c) => c.id > lowestUnfoundId).length;
}
// Get current team rank
const teamRankings = await query(`
SELECT
t.id,
COUNT(DISTINCT tc.clue_id) as cluesFound
FROM
teams t
LEFT JOIN
team_clues tc ON t.id = tc.team_id
GROUP BY
t.id
ORDER BY
cluesFound DESC
`);
// Find current team's position in the ranking
let currentRank = teamRankings.findIndex((t) => t.id === team.id) + 1;
if (currentRank === 0) currentRank = teamRankings.length + 1; // If not found (shouldn't happen)
// Construct response object
const teamStats = {
team,
totalClues,
foundClues,
remainingClues: totalClues - foundClues.length,
skippedClues,
currentRank,
progress:
totalClues > 0 ? Math.round((foundClues.length / totalClues) * 100) : 0,
};
return Response.json(teamStats);
} catch (error) {
console.error("Error fetching team stats:", error);
return Response.json(
{ error: "Failed to fetch team stats: " + error.message },
{ status: 500 }
);
}
}
BIN
View File
Binary file not shown.
View File
Whitespace-only changes.
View File
Whitespace-only changes.