From ea836179d62d8a2128a911fc710f3d6ea748015c Mon Sep 17 00:00:00 2001 From: mudabbir-ahmad Date: Sun, 16 Mar 2025 20:52:51 +0000 Subject: [PATCH] just need to fix the map to clue function. --- app/(main)/create-team/page.js | 102 +++++++++++++++++++++++---------- app/(main)/leaderboard/page.js | 17 ++++-- app/(main)/map/page.js | 18 ++++-- app/api/team-stats/route.js | 7 ++- app/api/teams/create/route.js | 23 +++++++- clue_hunt.db | Bin 86016 -> 86016 bytes 6 files changed, 124 insertions(+), 43 deletions(-) diff --git a/app/(main)/create-team/page.js b/app/(main)/create-team/page.js index c0bafcc..202ff90 100644 --- a/app/(main)/create-team/page.js +++ b/app/(main)/create-team/page.js @@ -4,13 +4,12 @@ import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import Link from "next/link"; -// Removed the styles object for navbar - export default function CreateTeam() { - const { data: session, status } = useSession(); + const { data: session, status, update: updateSession } = useSession(); const [teamName, setTeamName] = useState(""); const [error, setError] = useState(""); const [isLoading, setIsLoading] = useState(true); + const [success, setSuccess] = useState(false); const router = useRouter(); useEffect(() => { @@ -31,6 +30,11 @@ export default function CreateTeam() { setError(""); try { + // Validate team name + if (!teamName || teamName.trim() === "") { + throw new Error("Team name is required"); + } + // Check session status before proceeding if (status !== "authenticated") { throw new Error("You must be logged in to create a team"); @@ -42,7 +46,7 @@ export default function CreateTeam() { "Content-Type": "application/json", }, credentials: "include", // Important: include credentials with the request - body: JSON.stringify({ name: teamName }), + body: JSON.stringify({ name: teamName.trim() }), }); const data = await response.json(); @@ -52,23 +56,33 @@ export default function CreateTeam() { } console.log("Team created successfully with ID:", data.teamId); + setSuccess(true); - // Force a session refresh to update the session with the new teamId - await fetch("/api/auth/session", { - method: "GET", - credentials: "include", - }); + // Try to update the session with the new team ID + try { + // Wait briefly to ensure DB changes are reflected + await new Promise((resolve) => setTimeout(resolve, 500)); + await updateSession(); // Update the NextAuth session if possible + } catch (sessionErr) { + console.warn( + "Session update failed, using redirect instead:", + sessionErr + ); + } // Use window.location for a hard navigation to ensure session is fully updated - window.location.href = `/${data.teamId}`; + setTimeout(() => { + window.location.href = `/${data.teamId}`; + }, 1000); } catch (err) { console.error("Team creation error:", err); setError(err.message); + } finally { setIsLoading(false); } }; - if (isLoading) { + if (isLoading && !success) { return
Loading...
; } @@ -82,33 +96,48 @@ export default function CreateTeam() {
-

Create a New Team

-
-
- setTeamName(e.target.value)} - required - className="auth-input" - /> + {success ? ( +
+
βœ…
+

Team Created Successfully!

+

Redirecting to your new team page...

- - - {error &&

{error}

} + ) : ( + <> +

Create a New Team

+
+
+ setTeamName(e.target.value)} + required + className="auth-input" + maxLength={50} + /> +
+ +
+ {error &&

{error}

} + + )}
- +
- {/* Navbar removed from here */} -
); diff --git a/app/(main)/leaderboard/page.js b/app/(main)/leaderboard/page.js index c7870a1..c07a06f 100644 --- a/app/(main)/leaderboard/page.js +++ b/app/(main)/leaderboard/page.js @@ -162,17 +162,24 @@ export default function LeaderboardPage() {
πŸ—ΊοΈ
Map
- +
πŸ“Š
Stats
- + 0 && session?.user?.teamId + ? `/${session.user.teamId}` + : "/team-selection" + } + className="nav-item" + >
πŸ‘₯
Team
- -
πŸ‘€
-
Profile
+ +
πŸ†
+
Leaderboard
diff --git a/app/(main)/map/page.js b/app/(main)/map/page.js index 9118e28..b9133c1 100644 --- a/app/(main)/map/page.js +++ b/app/(main)/map/page.js @@ -43,7 +43,7 @@ export default function MapPage() { window.location.href = url; }, []); - // Fetch team data for the current user + // Enhanced fetchTeamData function const fetchTeamData = useCallback(async () => { try { const response = await fetch("/api/user/team", { @@ -71,6 +71,7 @@ export default function MapPage() { } const data = await response.json(); + console.log("Team data loaded:", data); setTeamData(data); return data; } catch (err) { @@ -573,6 +574,13 @@ export default function MapPage() { }); }, [mapSvg, clues, enhanceSvgMap]); + // Add useEffect to load team data + useEffect(() => { + if (status === "authenticated") { + fetchTeamData(); + } + }, [status, fetchTeamData]); + if (status === "loading" || loading) { return (
@@ -620,7 +628,7 @@ export default function MapPage() { {/* Map Banner with team info and timer */}
- {teamData?.team?.name || "Your Team"} + {teamData?.team?.name || "Loading..."}
{elapsedTime} @@ -667,9 +675,9 @@ export default function MapPage() {
πŸ‘₯
Team
- -
πŸ”™
-
Back
+ +
πŸ†
+
Leaderboard
diff --git a/app/api/team-stats/route.js b/app/api/team-stats/route.js index 3722c1d..41f5eeb 100644 --- a/app/api/team-stats/route.js +++ b/app/api/team-stats/route.js @@ -81,13 +81,18 @@ export async function GET(request) { const teamRankings = await query(` SELECT t.id, - COUNT(DISTINCT tc.clue_id) as cluesFound + COUNT(DISTINCT tc.clue_id) as cluesFound, + COUNT(DISTINCT u.id) as memberCount FROM teams t LEFT JOIN team_clues tc ON t.id = tc.team_id + LEFT JOIN + users u ON t.id = u.team_id GROUP BY t.id + HAVING + memberCount > 0 ORDER BY cluesFound DESC `); diff --git a/app/api/teams/create/route.js b/app/api/teams/create/route.js index 3539ebb..7e50a9f 100644 --- a/app/api/teams/create/route.js +++ b/app/api/teams/create/route.js @@ -46,6 +46,17 @@ export async function POST(request) { ) `); + // Check if team name already exists + const existingTeam = await queryOne("SELECT id FROM teams WHERE name = ?", [ + name, + ]); + if (existingTeam) { + return Response.json( + { error: "Team name already exists" }, + { status: 409 } + ); + } + // Insert team without created_by field const result = await run("INSERT INTO teams (name, code) VALUES (?, ?)", [ name, @@ -53,11 +64,21 @@ export async function POST(request) { ]); const teamId = result.lastID; + if (!teamId) { + throw new Error("Failed to create team - no ID returned"); + } // Update the user's team_id await run("UPDATE users SET team_id = ? WHERE id = ?", [teamId, userId]); - return Response.json({ success: true, teamId, code }); + // Return a more complete response with all needed data + return Response.json({ + success: true, + teamId, + teamName: name, + code, + message: "Team created successfully", + }); } catch (error) { console.error("Create team error:", error); return Response.json( diff --git a/clue_hunt.db b/clue_hunt.db index ca14ad3a0e21a2b5fbc40406e74315f681f1d72d..de2cf4799e4abca7f509146e64932d0945ad24d5 100644 GIT binary patch delta 1042 zcmZozz}m2Yb%Hcw=0q81#>|Zg3;7lK%^7%kuQTvp;a|mH#~;Zr!uOu<6yHL=3O;{6 zZQlR9*EbsqY~|HZ<7Z`%l{8MuPtq+(P0V#R_Hzx0GBPkS)ip5IH8fK&GO#i+wK6i@ z{9o3Bk%fVQL20tJ{58R&{C)ft{OkE|^XKv};lIGYYqO$(H~-{Z{TOzL5&WAk=wIe% z{4sfny*nfS<~R1Od_bzmZ;~Rj7Q4h`_5xD{_7_|noL4v(aOQAYaI$b*;F!aa!C}H> z!@h;Rf!&8)0_ea!Z1skX6>JO~whYDyM}+_#Wo&6>Y^Y~uZiePqu()AkISxHWrh4Y4 z7MOaBObr{$u<3~e8VJ&4WP)8&DH{VPHpdxS=$V>XV(Kxp@NCQkS!6rerAnCx>J>wC zJu`#J{Z-=i#n>DHbOTU@sf7U+^UMt!i*V^N(K9eK#G=Q3XTwCa41-sqq`0$4h*_%bWMcx7*FP?GBYZ{stp*kpp=3wW-T@sR27Kw uLJ~Vjm8D74&45Bzx$O3W;`zu{*TaR314>+SLY delta 213 zcmV;`04o20pap=S1&|v7P>~!%0Z_4Ep${Pd000dQ{{Rov52_D-4_OZs4(|@i4xtWs z4o?m%4gU`}voRpu4YU6pH~|D84g~;{J0I2&jt_VbuMgV~Z4aam&=0x~#j_zWOAnK6 zFI)#%Oh;EZOb)ZqFVhbJ>XW2DM*$AA>_3GL0S>crPLd%590~}N2XHk63Oou3voR3J z36ltVHU?=100}(+lkj&VlPh=&vvPWF6_fmT3IjGdT9d&a6S9!)9|38z?ynIL0co