mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-07 19:50:20 +00:00
fixed leaderboard, added feature to drop a team out of the teams table once it has hit 0 members, that check for members occurs when a user leaves a team. need to fix error with the timer in admin dashboard, make a separate page for it to be centrally run rather than be based on session instances.
Grey = cant click Red = current Green = complete blue = skipped? Need to add Clue page Need to fix Leaderboard.
This commit is contained in:
1 parent
c098ad40bf
commit
a762528494
5 files changed
+276
-108
No files matched your search
@@ -29,49 +29,13 @@ export default function AdminLeaderboardPage() {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
|
||||
// This is a placeholder - you'll need to implement the actual API
|
||||
// For now, we'll just set dummy data
|
||||
const dummyTeams = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Team Alpha",
|
||||
code: "ALPHA1",
|
||||
memberCount: 4,
|
||||
cluesFound: 5,
|
||||
totalClues: 10,
|
||||
lastActivity: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "Team Beta",
|
||||
code: "BETA12",
|
||||
memberCount: 3,
|
||||
cluesFound: 8,
|
||||
totalClues: 10,
|
||||
lastActivity: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: "Team Gamma",
|
||||
code: "GAMMA3",
|
||||
memberCount: 5,
|
||||
cluesFound: 2,
|
||||
totalClues: 10,
|
||||
lastActivity: new Date().toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
setTeams(dummyTeams);
|
||||
|
||||
// Uncomment this when API is ready
|
||||
/*
|
||||
const response = await fetch("/api/admin/leaderboard", {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate"
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
},
|
||||
credentials: "include"
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -80,7 +44,6 @@ export default function AdminLeaderboardPage() {
|
||||
|
||||
const data = await response.json();
|
||||
setTeams(data);
|
||||
*/
|
||||
} catch (err) {
|
||||
console.error("Error fetching leaderboard data:", err);
|
||||
setError(err.message);
|
||||
@@ -89,6 +52,54 @@ export default function AdminLeaderboardPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// Handle resetting a team's progress
|
||||
const handleResetTeamProgress = async (teamId, teamName) => {
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to reset progress for team "${teamName}"?`
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
const response = await fetch(
|
||||
`/api/admin/teams/${teamId}/reset-progress`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
credentials: "include",
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to reset team progress");
|
||||
}
|
||||
|
||||
// Refresh the data after successful reset
|
||||
fetchLeaderboardData();
|
||||
} catch (err) {
|
||||
console.error("Error resetting team progress:", err);
|
||||
setError(err.message);
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Auto refresh data every 30 seconds
|
||||
useEffect(() => {
|
||||
if (session?.user?.role === "admin") {
|
||||
const interval = setInterval(() => {
|
||||
fetchLeaderboardData();
|
||||
}, 30000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}
|
||||
}, [session]);
|
||||
|
||||
if (status === "loading" || loading) {
|
||||
return <div className="admin-page loading">Loading...</div>;
|
||||
}
|
||||
@@ -119,7 +130,7 @@ export default function AdminLeaderboardPage() {
|
||||
</button>
|
||||
|
||||
{teams.length === 0 ? (
|
||||
<p className="no-data">No team data available.</p>
|
||||
<p className="no-data">No teams currently participating.</p>
|
||||
) : (
|
||||
<div className="leaderboard-table-container">
|
||||
<table className="leaderboard-table">
|
||||
@@ -142,7 +153,16 @@ export default function AdminLeaderboardPage() {
|
||||
</td>
|
||||
<td>{team.memberCount}</td>
|
||||
<td>
|
||||
{team.cluesFound} / {team.totalClues}
|
||||
<div className="progress-container">
|
||||
<div
|
||||
className="progress-bar"
|
||||
style={{ width: `${team.progress}%` }}
|
||||
></div>
|
||||
<span className="progress-text">
|
||||
{team.cluesFound} / {team.totalClues} (
|
||||
{team.progress}%)
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
{team.lastActivity
|
||||
@@ -153,7 +173,7 @@ export default function AdminLeaderboardPage() {
|
||||
<button
|
||||
className="reset-button"
|
||||
onClick={() =>
|
||||
alert(`Reset team ${team.name} progress`)
|
||||
handleResetTeamProgress(team.id, team.name)
|
||||
}
|
||||
>
|
||||
Reset Progress
|
||||
@@ -354,6 +374,33 @@ export default function AdminLeaderboardPage() {
|
||||
.admin-nav-label {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.progress-container {
|
||||
width: 100%;
|
||||
background-color: #f0f0f0;
|
||||
border-radius: 4px;
|
||||
height: 20px;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
height: 100%;
|
||||
background-color: #4caf50;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.progress-text {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
text-align: center;
|
||||
line-height: 20px;
|
||||
color: #333;
|
||||
font-size: 0.8rem;
|
||||
text-shadow: 0 0 2px rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { query, queryOne, run } from "@/lib/db";
|
||||
import { getToken } from "next-auth/jwt";
|
||||
|
||||
export const dynamic = "force-dynamic"; // Disable caching
|
||||
|
||||
// Ensure the user is an admin
|
||||
async function verifyAdmin(request) {
|
||||
const token = await getToken({
|
||||
req: request,
|
||||
secret:
|
||||
process.env.NEXTAUTH_SECRET ||
|
||||
"your-fallback-secret-should-be-at-least-32-chars",
|
||||
});
|
||||
|
||||
if (!token) {
|
||||
return { authorized: false, error: "Unauthorized", status: 401 };
|
||||
}
|
||||
|
||||
if (token.role !== "admin") {
|
||||
return { authorized: false, error: "Admin access required", status: 403 };
|
||||
}
|
||||
|
||||
return { authorized: true, token };
|
||||
}
|
||||
|
||||
export async function GET(request) {
|
||||
try {
|
||||
// Verify admin access
|
||||
const { authorized, error, status } = await verifyAdmin(request);
|
||||
if (!authorized) {
|
||||
return Response.json({ error }, { status });
|
||||
}
|
||||
|
||||
// Get the total number of clues for calculating progress
|
||||
const clueCountResult = await queryOne(
|
||||
"SELECT COUNT(*) as total FROM clues"
|
||||
);
|
||||
const totalClues = clueCountResult?.total || 0;
|
||||
|
||||
// Get all teams with member count and clues found
|
||||
const teams = await query(`
|
||||
SELECT
|
||||
t.id,
|
||||
t.name,
|
||||
t.code,
|
||||
COUNT(DISTINCT u.id) as memberCount,
|
||||
COUNT(DISTINCT tc.clue_id) as cluesFound,
|
||||
MAX(tc.found_at) as lastActivity
|
||||
FROM
|
||||
teams t
|
||||
LEFT JOIN
|
||||
users u ON t.id = u.team_id
|
||||
LEFT JOIN
|
||||
team_clues tc ON t.id = tc.team_id
|
||||
GROUP BY
|
||||
t.id
|
||||
HAVING
|
||||
memberCount > 0
|
||||
ORDER BY
|
||||
cluesFound DESC,
|
||||
lastActivity ASC
|
||||
`);
|
||||
|
||||
// Enhance team data with total clues
|
||||
const teamsWithProgress = teams.map((team) => ({
|
||||
...team,
|
||||
totalClues,
|
||||
progress:
|
||||
totalClues > 0 ? Math.round((team.cluesFound / totalClues) * 100) : 0,
|
||||
}));
|
||||
|
||||
return Response.json(teamsWithProgress, {
|
||||
headers: {
|
||||
"Cache-Control": "no-store, no-cache, must-revalidate",
|
||||
Pragma: "no-cache",
|
||||
Expires: "0",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Admin leaderboard error:", error);
|
||||
return Response.json(
|
||||
{ error: "Failed to fetch leaderboard data: " + error.message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { getToken } from "next-auth/jwt";
|
||||
import { queryOne, run } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic"; // Disable caching
|
||||
|
||||
// Ensure the user is an admin
|
||||
async function verifyAdmin(request) {
|
||||
const token = await getToken({
|
||||
req: request,
|
||||
secret:
|
||||
process.env.NEXTAUTH_SECRET ||
|
||||
"your-fallback-secret-should-be-at-least-32-chars",
|
||||
});
|
||||
|
||||
if (!token) {
|
||||
return { authorized: false, error: "Unauthorized", status: 401 };
|
||||
}
|
||||
|
||||
if (token.role !== "admin") {
|
||||
return { authorized: false, error: "Admin access required", status: 403 };
|
||||
}
|
||||
|
||||
return { authorized: true, token };
|
||||
}
|
||||
|
||||
export async function POST(request, context) {
|
||||
try {
|
||||
// Verify admin access
|
||||
const { authorized, error, status } = await verifyAdmin(request);
|
||||
if (!authorized) {
|
||||
return Response.json({ error }, { status });
|
||||
}
|
||||
|
||||
const { teamId } = context.params;
|
||||
|
||||
// Validate teamId is a number
|
||||
if (isNaN(parseInt(teamId))) {
|
||||
return Response.json({ error: "Invalid team ID" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if team exists
|
||||
const team = await queryOne("SELECT id FROM teams WHERE id = ?", [teamId]);
|
||||
if (!team) {
|
||||
return Response.json({ error: "Team not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
// Delete all clue progress for the team
|
||||
await run("DELETE FROM team_clues WHERE team_id = ?", [teamId]);
|
||||
|
||||
return Response.json({
|
||||
success: true,
|
||||
message: "Team progress has been reset",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Admin reset team progress error:", error);
|
||||
return Response.json(
|
||||
{ error: "Failed to reset team progress: " + error.message },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,86 +1,60 @@
|
||||
import { run } from "@/lib/db";
|
||||
import { cookies } from "next/headers";
|
||||
import { verifyToken, createToken } from "@/app/api/auth/[...nextauth]/route";
|
||||
import { getToken } from "next-auth/jwt";
|
||||
import { query, queryOne, run } from "@/lib/db";
|
||||
|
||||
export async function POST(request, context) {
|
||||
try {
|
||||
// Verify user authentication
|
||||
const cookieStore = await cookies();
|
||||
const sessionToken = cookieStore.get("next-auth.session-token")?.value;
|
||||
const token = await getToken({
|
||||
req: request,
|
||||
secret:
|
||||
process.env.NEXTAUTH_SECRET ||
|
||||
"your-fallback-secret-should-be-at-least-32-chars",
|
||||
});
|
||||
|
||||
if (!sessionToken) {
|
||||
if (!token) {
|
||||
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const userData = verifyToken(sessionToken);
|
||||
if (!userData) {
|
||||
return Response.json({ error: "Invalid session" }, { status: 401 });
|
||||
}
|
||||
const { teamId } = context.params;
|
||||
|
||||
// Get teamId from URL params
|
||||
const params = await Promise.resolve(context.params);
|
||||
const teamId = params?.teamId;
|
||||
|
||||
// Validate teamId
|
||||
if (!teamId || isNaN(parseInt(teamId, 10))) {
|
||||
return Response.json({ error: "Invalid team ID" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if user is actually in this team
|
||||
if (userData.teamId != teamId) {
|
||||
// Validate that user belongs to this team
|
||||
if (!token.teamId || parseInt(token.teamId, 10) !== parseInt(teamId, 10)) {
|
||||
return Response.json(
|
||||
{ error: "You are not part of this team" },
|
||||
{ error: "You are not a member of this team" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Update the user record to remove team association
|
||||
await run("UPDATE users SET team_id = NULL WHERE id = ?", [userData.id]);
|
||||
// Update the user's team_id to null
|
||||
await run("UPDATE users SET team_id = NULL WHERE id = ?", [token.id]);
|
||||
|
||||
// Try to update the team's last_updated timestamp but don't fail if column doesn't exist
|
||||
try {
|
||||
await run("UPDATE teams SET last_updated = ? WHERE id = ?", [
|
||||
new Date().toISOString(),
|
||||
teamId,
|
||||
]);
|
||||
} catch (updateError) {
|
||||
// Log but don't fail if we can't update timestamp
|
||||
console.warn(
|
||||
"Failed to update last_updated timestamp:",
|
||||
updateError.message
|
||||
);
|
||||
// Check if the team is now empty
|
||||
const remainingMembers = await queryOne(
|
||||
"SELECT COUNT(*) as count FROM users WHERE team_id = ?",
|
||||
[teamId]
|
||||
);
|
||||
|
||||
// If no more members, delete the team and its associated data
|
||||
if (remainingMembers && remainingMembers.count === 0) {
|
||||
console.log(`Team ${teamId} is now empty, removing it...`);
|
||||
|
||||
// Delete team's clue progress
|
||||
await run("DELETE FROM team_clues WHERE team_id = ?", [teamId]);
|
||||
|
||||
// Delete team's hunt session if exists
|
||||
await run("DELETE FROM team_hunt_sessions WHERE team_id = ?", [teamId]);
|
||||
|
||||
// Finally delete the team itself
|
||||
await run("DELETE FROM teams WHERE id = ?", [teamId]);
|
||||
|
||||
console.log(`Team ${teamId} has been removed`);
|
||||
}
|
||||
|
||||
// Create a new token with updated user data (without teamId)
|
||||
const newUserData = {
|
||||
...userData,
|
||||
teamId: null, // Remove team association in token
|
||||
iat: Math.floor(Date.now() / 1000),
|
||||
exp: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60, // 30 days
|
||||
};
|
||||
|
||||
const newToken = createToken(newUserData);
|
||||
|
||||
// Calculate expiration date for cookie
|
||||
const expiryDate = new Date();
|
||||
expiryDate.setDate(expiryDate.getDate() + 30);
|
||||
|
||||
// Return success with updated session token
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
success: true,
|
||||
message: "Successfully left the team",
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Set-Cookie": `next-auth.session-token=${newToken}; Path=/; HttpOnly; SameSite=Lax; Expires=${expiryDate.toUTCString()}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
return Response.json({
|
||||
success: true,
|
||||
message: "You have left the team successfully",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Leave team error:", error);
|
||||
console.error("Team leave error:", error);
|
||||
return Response.json(
|
||||
{ error: "Failed to leave team: " + error.message },
|
||||
{ status: 500 }
|
||||
|
||||
Binary file not shown.
Reference in new issue
Block a user