mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-08 03:50:21 +00:00
cannot fix issue with elapsed timer on admin dashboard. fixing issues with QR code editing.
Grey = cant click Red = current Green = complete blue = skipped?
This commit is contained in:
1 parent
7d6b73ffb4
commit
0afa6817a8
12 files changed
+1441
-123
No files matched your search
+454
-18
@@ -1,5 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
import { useState, useEffect } from "react";
|
import { useState, useEffect, useRef } from "react";
|
||||||
import { useSession } from "next-auth/react";
|
import { useSession } from "next-auth/react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
@@ -9,12 +9,24 @@ export default function AdminCluesPage() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const [isEditMode, setIsEditMode] = useState(false);
|
||||||
|
const [editingClue, setEditingClue] = useState(null);
|
||||||
|
const [fixMessage, setFixMessage] = useState("");
|
||||||
|
// Add a lastRefresh timestamp to track when data was last fetched
|
||||||
|
const [lastRefresh, setLastRefresh] = useState(Date.now());
|
||||||
|
// Add next refresh countdown state
|
||||||
|
const [nextRefresh, setNextRefresh] = useState(10);
|
||||||
|
// Add auto-refresh enabled/disabled state
|
||||||
|
const [autoRefreshEnabled, setAutoRefreshEnabled] = useState(true);
|
||||||
|
// Ref to store interval ID for cleanup
|
||||||
|
const refreshIntervalRef = useRef(null);
|
||||||
|
|
||||||
// Form state for adding new clues - removed coordinates
|
// Form state for adding new clues - add qrCode field back
|
||||||
const [newClue, setNewClue] = useState({
|
const [newClue, setNewClue] = useState({
|
||||||
title: "",
|
title: "",
|
||||||
description: "",
|
description: "",
|
||||||
location: "",
|
location: "",
|
||||||
|
qr_code: "", // Add QR code field
|
||||||
});
|
});
|
||||||
|
|
||||||
// Check if user is admin
|
// Check if user is admin
|
||||||
@@ -30,15 +42,63 @@ export default function AdminCluesPage() {
|
|||||||
}
|
}
|
||||||
}, [session, status, router]);
|
}, [session, status, router]);
|
||||||
|
|
||||||
|
// Controlled auto-refresh effect
|
||||||
|
useEffect(() => {
|
||||||
|
// Only set up auto-refresh if enabled and not in edit mode
|
||||||
|
if (autoRefreshEnabled && !isEditMode && status === "authenticated") {
|
||||||
|
// Clear any existing interval
|
||||||
|
if (refreshIntervalRef.current) {
|
||||||
|
clearInterval(refreshIntervalRef.current);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set initial countdown value
|
||||||
|
setNextRefresh(10);
|
||||||
|
|
||||||
|
// Set up countdown interval
|
||||||
|
refreshIntervalRef.current = setInterval(() => {
|
||||||
|
setNextRefresh((prev) => {
|
||||||
|
// When countdown reaches 0, refresh the data and reset countdown
|
||||||
|
if (prev <= 1) {
|
||||||
|
fetchClues();
|
||||||
|
return 10;
|
||||||
|
}
|
||||||
|
return prev - 1;
|
||||||
|
});
|
||||||
|
}, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean up interval on unmount or when dependencies change
|
||||||
|
return () => {
|
||||||
|
if (refreshIntervalRef.current) {
|
||||||
|
clearInterval(refreshIntervalRef.current);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [autoRefreshEnabled, isEditMode, status]);
|
||||||
|
|
||||||
|
// Disable auto-refresh when entering edit mode
|
||||||
|
useEffect(() => {
|
||||||
|
if (isEditMode) {
|
||||||
|
setAutoRefreshEnabled(false);
|
||||||
|
}
|
||||||
|
}, [isEditMode]);
|
||||||
|
|
||||||
// Fetch all clues
|
// Fetch all clues
|
||||||
const fetchClues = async () => {
|
const fetchClues = async () => {
|
||||||
|
// Skip fetch if in edit mode to prevent data loss
|
||||||
|
if (isEditMode) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const response = await fetch("/api/admin/clues", {
|
// Add timestamp parameter to bust cache
|
||||||
|
const timestamp = Date.now();
|
||||||
|
const response = await fetch(`/api/admin/clues?t=${timestamp}`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||||
|
Pragma: "no-cache",
|
||||||
},
|
},
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
});
|
});
|
||||||
@@ -57,8 +117,13 @@ export default function AdminCluesPage() {
|
|||||||
throw new Error("Invalid response format from server");
|
throw new Error("Invalid response format from server");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log("Fetched clues:", data); // Debug log to see what's coming from API
|
||||||
setClues(data);
|
setClues(data);
|
||||||
setError("");
|
setError("");
|
||||||
|
// Update lastRefresh timestamp
|
||||||
|
setLastRefresh(Date.now());
|
||||||
|
// Reset countdown after manual refresh
|
||||||
|
setNextRefresh(10);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Error fetching clues:", err);
|
console.error("Error fetching clues:", err);
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
@@ -81,6 +146,8 @@ export default function AdminCluesPage() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
|
// Now include the QR code in the request
|
||||||
const response = await fetch("/api/admin/clues", {
|
const response = await fetch("/api/admin/clues", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -90,18 +157,23 @@ export default function AdminCluesPage() {
|
|||||||
credentials: "include",
|
credentials: "include",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error("Failed to add clue");
|
throw new Error(
|
||||||
|
data.error || `Failed to add clue (Status: ${response.status})`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Refresh the clue list
|
// Refresh the clue list with force refresh
|
||||||
fetchClues();
|
await fetchClues();
|
||||||
|
|
||||||
// Reset the form - removed coordinates
|
// Reset the form - now with qrCode
|
||||||
setNewClue({
|
setNewClue({
|
||||||
title: "",
|
title: "",
|
||||||
description: "",
|
description: "",
|
||||||
location: "",
|
location: "",
|
||||||
|
qr_code: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
setError("");
|
setError("");
|
||||||
@@ -113,12 +185,102 @@ export default function AdminCluesPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Handle deleting a clue
|
// Start editing a clue
|
||||||
const handleDeleteClue = async (clueId) => {
|
const handleEditStart = (clue) => {
|
||||||
if (!confirm("Are you sure you want to delete this clue?")) return;
|
// Disable auto-refresh when starting to edit
|
||||||
|
setAutoRefreshEnabled(false);
|
||||||
|
setEditingClue({
|
||||||
|
id: clue.id,
|
||||||
|
title: clue.title,
|
||||||
|
description: clue.description,
|
||||||
|
location: clue.location || "",
|
||||||
|
// Use the actual qr_code from the clue object if available
|
||||||
|
qr_code: clue.qr_code || `QR${clue.id}`,
|
||||||
|
});
|
||||||
|
setIsEditMode(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle input change for editing clue
|
||||||
|
const handleEditChange = (e) => {
|
||||||
|
const { name, value } = e.target;
|
||||||
|
setEditingClue((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[name]: value,
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle form submission to update clue
|
||||||
|
const handleUpdateClue = async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
|
const response = await fetch(`/api/admin/clues/${editingClue.id}`, {
|
||||||
|
method: "PUT",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
title: editingClue.title,
|
||||||
|
description: editingClue.description,
|
||||||
|
location: editingClue.location,
|
||||||
|
qr_code: editingClue.qr_code, // Add QR code to the update
|
||||||
|
}),
|
||||||
|
credentials: "include",
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(
|
||||||
|
data.error || `Failed to update clue (Status: ${response.status})`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refresh the clue list with force refresh
|
||||||
|
await fetchClues();
|
||||||
|
setIsEditMode(false);
|
||||||
|
setEditingClue(null);
|
||||||
|
setError("");
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error updating clue:", err);
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Cancel editing
|
||||||
|
const handleCancelEdit = () => {
|
||||||
|
setIsEditMode(false);
|
||||||
|
setEditingClue(null);
|
||||||
|
// Re-enable auto-refresh when canceling edit
|
||||||
|
setAutoRefreshEnabled(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Force refresh the clue list
|
||||||
|
const handleForceRefresh = () => {
|
||||||
|
fetchClues();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Toggle auto-refresh
|
||||||
|
const toggleAutoRefresh = () => {
|
||||||
|
setAutoRefreshEnabled((prev) => !prev);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle deleting a clue with automatic QR code renumbering
|
||||||
|
const handleDeleteClue = async (clueId, qrCode) => {
|
||||||
|
if (
|
||||||
|
!confirm(
|
||||||
|
"Are you sure you want to delete this clue?\n\nQR codes will be automatically renumbered to prevent gaps in the sequence."
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
|
// QR codes will always be renumbered - no need to pass this parameter anymore
|
||||||
const response = await fetch(`/api/admin/clues/${clueId}`, {
|
const response = await fetch(`/api/admin/clues/${clueId}`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -127,16 +289,23 @@ export default function AdminCluesPage() {
|
|||||||
credentials: "include",
|
credentials: "include",
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Parse the response data for detailed error messages
|
||||||
|
const data = await response.json().catch(() => ({}));
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error("Failed to delete clue");
|
throw new Error(
|
||||||
|
data.error || `Failed to delete clue (Status: ${response.status})`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Refresh the clue list
|
// Success message and refresh
|
||||||
|
console.log("Clue deleted successfully:", data.message || "Success");
|
||||||
|
// Refresh the clue list to show updated QR codes
|
||||||
fetchClues();
|
fetchClues();
|
||||||
setError("");
|
setError("");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Error deleting clue:", err);
|
console.error("Error deleting clue:", err);
|
||||||
setError(err.message);
|
setError(`Error deleting clue: ${err.message}`);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -154,13 +323,35 @@ export default function AdminCluesPage() {
|
|||||||
<div className="admin-page">
|
<div className="admin-page">
|
||||||
<div className="page-header">
|
<div className="page-header">
|
||||||
<div className="page-title">Manage Clues</div>
|
<div className="page-title">Manage Clues</div>
|
||||||
<div className="placeholder"></div>
|
<div className="header-controls">
|
||||||
|
<button
|
||||||
|
onClick={toggleAutoRefresh}
|
||||||
|
className={`auto-refresh-toggle ${
|
||||||
|
autoRefreshEnabled ? "active" : ""
|
||||||
|
}`}
|
||||||
|
title={autoRefreshEnabled ? "Auto-refresh on" : "Auto-refresh off"}
|
||||||
|
>
|
||||||
|
{autoRefreshEnabled ? "🔄 Auto" : "⏸️ Auto"}
|
||||||
|
{autoRefreshEnabled && (
|
||||||
|
<span className="refresh-countdown">{nextRefresh}s</span>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={handleForceRefresh}
|
||||||
|
className="refresh-button"
|
||||||
|
title="Force refresh"
|
||||||
|
>
|
||||||
|
🔄
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="admin-content">
|
<div className="admin-content">
|
||||||
{error && <p className="error-message">{error}</p>}
|
{error && <p className="error-message">{error}</p>}
|
||||||
|
{fixMessage && <p className="success-message">{fixMessage}</p>}
|
||||||
|
|
||||||
{/* Add New Clue Form - removed coordinate fields */}
|
{/* Add New Clue Form */}
|
||||||
|
{!isEditMode ? (
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h2>Add New Clue</h2>
|
<h2>Add New Clue</h2>
|
||||||
<form onSubmit={handleAddClue}>
|
<form onSubmit={handleAddClue}>
|
||||||
@@ -201,15 +392,117 @@ export default function AdminCluesPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Add QR code field with new label */}
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="qr_code">QR Answer Value</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="qr_code"
|
||||||
|
name="qr_code"
|
||||||
|
value={newClue.qr_code}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
className="admin-input"
|
||||||
|
placeholder="QR1, QR2, etc."
|
||||||
|
/>
|
||||||
|
<div className="help-text">
|
||||||
|
QR codes should follow the format QR[number] (e.g., QR1, QR2).
|
||||||
|
Leave blank to auto-generate.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<button type="submit" className="admin-button">
|
<button type="submit" className="admin-button">
|
||||||
Add Clue
|
Add Clue
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="admin-card">
|
||||||
|
<h2>Edit Clue</h2>
|
||||||
|
<form onSubmit={handleUpdateClue}>
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="edit-title">Title</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="edit-title"
|
||||||
|
name="title"
|
||||||
|
value={editingClue.title}
|
||||||
|
onChange={handleEditChange}
|
||||||
|
required
|
||||||
|
className="admin-input"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Existing Clues List - updated to remove coordinates */}
|
<div className="form-group">
|
||||||
|
<label htmlFor="edit-description">Description</label>
|
||||||
|
<textarea
|
||||||
|
id="edit-description"
|
||||||
|
name="description"
|
||||||
|
value={editingClue.description}
|
||||||
|
onChange={handleEditChange}
|
||||||
|
required
|
||||||
|
className="admin-textarea"
|
||||||
|
></textarea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="edit-location">Location Hint</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="edit-location"
|
||||||
|
name="location"
|
||||||
|
value={editingClue.location}
|
||||||
|
onChange={handleEditChange}
|
||||||
|
className="admin-input"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="edit-qrcode">QR Answer Value</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="edit-qrcode"
|
||||||
|
name="qr_code"
|
||||||
|
value={editingClue.qr_code}
|
||||||
|
onChange={handleEditChange}
|
||||||
|
className="admin-input"
|
||||||
|
/>
|
||||||
|
<div className="help-text">
|
||||||
|
QR codes should follow the format QR[number] (e.g., QR1, QR2).
|
||||||
|
The QR code value determines what users scan to find this
|
||||||
|
clue.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-actions">
|
||||||
|
<button type="submit" className="admin-button">
|
||||||
|
Update Clue
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="admin-button cancel-button"
|
||||||
|
onClick={handleCancelEdit}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Existing Clues List */}
|
||||||
<div className="admin-card">
|
<div className="admin-card">
|
||||||
<h2>Existing Clues</h2>
|
<h2>Existing Clues</h2>
|
||||||
|
<p className="info-text">
|
||||||
|
QR codes are the values that users scan to find each clue. You can
|
||||||
|
customize these values, but they should usually follow the format
|
||||||
|
QR[number].
|
||||||
|
</p>
|
||||||
|
<div className="last-updated">
|
||||||
|
Last updated: {new Date(lastRefresh).toLocaleTimeString()}
|
||||||
|
{autoRefreshEnabled && !isEditMode && (
|
||||||
|
<span> (next refresh in {nextRefresh}s)</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
{clues.length === 0 ? (
|
{clues.length === 0 ? (
|
||||||
<p className="no-clues">No clues found.</p>
|
<p className="no-clues">No clues found.</p>
|
||||||
) : (
|
) : (
|
||||||
@@ -218,13 +511,21 @@ export default function AdminCluesPage() {
|
|||||||
<div key={clue.id} className="clue-item">
|
<div key={clue.id} className="clue-item">
|
||||||
<div className="clue-header">
|
<div className="clue-header">
|
||||||
<h3>{clue.title}</h3>
|
<h3>{clue.title}</h3>
|
||||||
|
<div className="clue-actions">
|
||||||
|
<button
|
||||||
|
className="edit-button"
|
||||||
|
onClick={() => handleEditStart(clue)}
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
className="delete-button"
|
className="delete-button"
|
||||||
onClick={() => handleDeleteClue(clue.id)}
|
onClick={() => handleDeleteClue(clue.id, clue.qr_code)}
|
||||||
>
|
>
|
||||||
Delete
|
Delete
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
<p className="clue-description">{clue.description}</p>
|
<p className="clue-description">{clue.description}</p>
|
||||||
{clue.location && (
|
{clue.location && (
|
||||||
<p className="clue-location">
|
<p className="clue-location">
|
||||||
@@ -234,6 +535,9 @@ export default function AdminCluesPage() {
|
|||||||
<p className="clue-position">
|
<p className="clue-position">
|
||||||
<strong>Position:</strong> Clue #{clue.id} in sequence
|
<strong>Position:</strong> Clue #{clue.id} in sequence
|
||||||
</p>
|
</p>
|
||||||
|
<p className="clue-qr-code">
|
||||||
|
<strong>QR Code:</strong> {clue.qr_code || `QR${clue.id}`}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -276,7 +580,7 @@ export default function AdminCluesPage() {
|
|||||||
|
|
||||||
.page-header {
|
.page-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: space-between;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
background-color: #68543c;
|
background-color: #68543c;
|
||||||
@@ -288,6 +592,39 @@ export default function AdminCluesPage() {
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.header-controls {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auto-refresh-toggle {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
background-color: #5a4832;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 5px 10px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.auto-refresh-toggle.active {
|
||||||
|
background-color: #4caf50;
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.refresh-countdown {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
background-color: rgba(255, 255, 255, 0.25);
|
||||||
|
border-radius: 3px;
|
||||||
|
padding: 0 5px;
|
||||||
|
margin-left: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
.admin-content {
|
.admin-content {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
padding: 1rem;
|
padding: 1rem;
|
||||||
@@ -400,6 +737,11 @@ export default function AdminCluesPage() {
|
|||||||
margin-bottom: 0.4rem;
|
margin-bottom: 0.4rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.clue-qr-code {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
margin-bottom: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
.error-message {
|
.error-message {
|
||||||
color: red;
|
color: red;
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
@@ -462,6 +804,100 @@ export default function AdminCluesPage() {
|
|||||||
.admin-nav-label {
|
.admin-nav-label {
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.help-text {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: #666;
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cancel-button {
|
||||||
|
background-color: #757575;
|
||||||
|
}
|
||||||
|
|
||||||
|
.edit-button {
|
||||||
|
background-color: #2196f3;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 0.4rem 0.6rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
cursor: pointer;
|
||||||
|
margin-right: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.clue-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-input.disabled {
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-tools {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool-button,
|
||||||
|
.sequence-button,
|
||||||
|
.fix-button {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tool-description {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.success-message {
|
||||||
|
color: #4caf50;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
padding: 0.5rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
background-color: #e8f5e9;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 700px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.info-text {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: #666;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
padding: 0.5rem;
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
border-left: 3px solid #2196f3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.refresh-button {
|
||||||
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
font-size: 1.2rem;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0.5rem;
|
||||||
|
margin-left: 1rem;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.refresh-button:hover {
|
||||||
|
transform: rotate(90deg);
|
||||||
|
transition: transform 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.last-updated {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: #666;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
text-align: right;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
`}</style>
|
`}</style>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
+114
-13
@@ -21,6 +21,7 @@ export default function AdminDashboard() {
|
|||||||
const [presetSeconds, setPresetSeconds] = useState("");
|
const [presetSeconds, setPresetSeconds] = useState("");
|
||||||
const [timerEndTime, setTimerEndTime] = useState(null);
|
const [timerEndTime, setTimerEndTime] = useState(null);
|
||||||
const timerRef = useRef(null);
|
const timerRef = useRef(null);
|
||||||
|
const timerIntervalRef = useRef(null);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
// Load timer status on page load
|
// Load timer status on page load
|
||||||
@@ -28,33 +29,65 @@ export default function AdminDashboard() {
|
|||||||
async function loadTimerStatus() {
|
async function loadTimerStatus() {
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
|
// First, check if we already have timer data in localStorage
|
||||||
|
const existingTimer = getHuntTimer();
|
||||||
|
if (existingTimer && existingTimer.startTime) {
|
||||||
|
// If we have timer data, immediately set the display
|
||||||
|
setTimerActive(existingTimer.isActive);
|
||||||
|
if (existingTimer.endTime) {
|
||||||
|
setTimerEndTime(new Date(existingTimer.endTime).getTime());
|
||||||
|
}
|
||||||
|
setTimerDisplay(formatElapsedTime(existingTimer.startTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Then, fetch fresh data from the server to ensure we're in sync
|
||||||
const response = await fetch("/api/hunt/timer", {
|
const response = await fetch("/api/hunt/timer", {
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
headers: {
|
headers: {
|
||||||
"Cache-Control": "no-cache",
|
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||||
|
Pragma: "no-cache",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Server responded with status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (data.active) {
|
// Check both activity indicators to handle cases where they might be inconsistent
|
||||||
|
const isActive = data.active || data.timerActive;
|
||||||
|
|
||||||
|
if (isActive && data.startTime) {
|
||||||
setTimerActive(true);
|
setTimerActive(true);
|
||||||
|
|
||||||
// Calculate elapsed time
|
|
||||||
if (data.startTime) {
|
|
||||||
// Store the start time in the centralized service
|
// Store the start time in the centralized service
|
||||||
setHuntTimer(data.startTime, data.endTime);
|
setHuntTimer(data.startTime, data.endTime);
|
||||||
|
|
||||||
// If there's an end time, set it
|
// If there's an end time, set it
|
||||||
if (data.endTime) {
|
if (data.endTime) {
|
||||||
setTimerEndTime(new Date(data.endTime).getTime());
|
setTimerEndTime(new Date(data.endTime).getTime());
|
||||||
|
} else {
|
||||||
|
setTimerEndTime(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Immediately display the current elapsed time
|
||||||
|
setTimerDisplay(formatElapsedTime(data.startTime));
|
||||||
|
} else {
|
||||||
|
// Only clear local timer if server explicitly says timer is not active
|
||||||
|
// This prevents clearing a valid timer if the server response is ambiguous
|
||||||
|
if (data.active === false && data.timerActive === false) {
|
||||||
|
clearHuntTimer();
|
||||||
|
setTimerActive(false);
|
||||||
|
setTimerDisplay("--:--:--");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to load timer status:", err);
|
console.error("Failed to load timer status:", err);
|
||||||
setError("Failed to load timer status");
|
setError(`Failed to load timer status: ${err.message}`);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -62,6 +95,14 @@ export default function AdminDashboard() {
|
|||||||
if (status === "authenticated") {
|
if (status === "authenticated") {
|
||||||
loadTimerStatus();
|
loadTimerStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clear interval when component unmounts
|
||||||
|
return () => {
|
||||||
|
if (timerIntervalRef.current) {
|
||||||
|
clearInterval(timerIntervalRef.current);
|
||||||
|
timerIntervalRef.current = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
}, [status]);
|
}, [status]);
|
||||||
|
|
||||||
// Check if user is admin
|
// Check if user is admin
|
||||||
@@ -77,11 +118,15 @@ export default function AdminDashboard() {
|
|||||||
|
|
||||||
// Timer update effect - use the centralized timer service
|
// Timer update effect - use the centralized timer service
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let intervalId;
|
// Clear any existing interval first to prevent multiple intervals
|
||||||
|
if (timerIntervalRef.current) {
|
||||||
|
clearInterval(timerIntervalRef.current);
|
||||||
|
timerIntervalRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
if (timerActive) {
|
if (timerActive) {
|
||||||
// Use the existing timer data from the centralized service
|
// Start a new interval for timer updates
|
||||||
intervalId = setInterval(() => {
|
timerIntervalRef.current = setInterval(() => {
|
||||||
const timerData = getHuntTimer();
|
const timerData = getHuntTimer();
|
||||||
|
|
||||||
if (timerData && timerData.startTime) {
|
if (timerData && timerData.startTime) {
|
||||||
@@ -94,7 +139,8 @@ export default function AdminDashboard() {
|
|||||||
stopTimer();
|
stopTimer();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
setTimerDisplay("--:--:--");
|
// If timer data is suddenly gone, try to reload from server
|
||||||
|
fetchTimerStatusFromServer();
|
||||||
}
|
}
|
||||||
}, 1000);
|
}, 1000);
|
||||||
} else {
|
} else {
|
||||||
@@ -102,12 +148,56 @@ export default function AdminDashboard() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
if (intervalId) {
|
if (timerIntervalRef.current) {
|
||||||
clearInterval(intervalId);
|
clearInterval(timerIntervalRef.current);
|
||||||
|
timerIntervalRef.current = null;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}, [timerActive, timerEndTime]);
|
}, [timerActive, timerEndTime]);
|
||||||
|
|
||||||
|
// Add a function to fetch timer status directly from the server
|
||||||
|
const fetchTimerStatusFromServer = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/hunt/timer", {
|
||||||
|
credentials: "include",
|
||||||
|
headers: {
|
||||||
|
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||||
|
Pragma: "no-cache",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
console.error("Server responded with status:", response.status);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
// Check both activity indicators for consistency
|
||||||
|
const isActive = data.active || data.timerActive;
|
||||||
|
|
||||||
|
if (isActive && data.startTime) {
|
||||||
|
setTimerActive(true);
|
||||||
|
setHuntTimer(data.startTime, data.endTime);
|
||||||
|
|
||||||
|
if (data.endTime) {
|
||||||
|
setTimerEndTime(new Date(data.endTime).getTime());
|
||||||
|
} else {
|
||||||
|
setTimerEndTime(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimerDisplay(formatElapsedTime(data.startTime));
|
||||||
|
} else if (data.active === false && data.timerActive === false) {
|
||||||
|
// Only clear timer if server explicitly says timer is inactive
|
||||||
|
setTimerActive(false);
|
||||||
|
clearHuntTimer();
|
||||||
|
setTimerDisplay("--:--:--");
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error fetching timer status:", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const startTimer = async (preset = false) => {
|
const startTimer = async (preset = false) => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
@@ -152,6 +242,10 @@ export default function AdminDashboard() {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Server responded with status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
@@ -166,13 +260,16 @@ export default function AdminDashboard() {
|
|||||||
// Update global timer data for all clients
|
// Update global timer data for all clients
|
||||||
setHuntTimer(data.startTime, data.endTime);
|
setHuntTimer(data.startTime, data.endTime);
|
||||||
|
|
||||||
|
// Immediately display the current elapsed time
|
||||||
|
setTimerDisplay(formatElapsedTime(data.startTime));
|
||||||
|
|
||||||
setError("");
|
setError("");
|
||||||
} else {
|
} else {
|
||||||
setError(data.error || "Failed to start timer");
|
setError(data.error || "Failed to start timer");
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to start timer:", err);
|
console.error("Failed to start timer:", err);
|
||||||
setError("Failed to start timer");
|
setError(`Failed to start timer: ${err.message}`);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -189,6 +286,10 @@ export default function AdminDashboard() {
|
|||||||
body: JSON.stringify({ action: "stop" }),
|
body: JSON.stringify({ action: "stop" }),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Server responded with status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
@@ -203,7 +304,7 @@ export default function AdminDashboard() {
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to stop timer:", err);
|
console.error("Failed to stop timer:", err);
|
||||||
setError("Failed to stop timer");
|
setError(`Failed to stop timer: ${err.message}`);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,11 +20,27 @@ export default function CluePage({ params }) {
|
|||||||
const [showScanner, setShowScanner] = useState(false);
|
const [showScanner, setShowScanner] = useState(false);
|
||||||
const [scanResult, setScanResult] = useState(null);
|
const [scanResult, setScanResult] = useState(null);
|
||||||
const [scanMessage, setScanMessage] = useState(null);
|
const [scanMessage, setScanMessage] = useState(null);
|
||||||
|
const [lastRefresh, setLastRefresh] = useState(0); // Track last refresh time
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { status } = useSession();
|
const { data: session, status } = useSession(); // Get session to check if user is admin
|
||||||
const { clueId } = params;
|
const { clueId } = params;
|
||||||
|
|
||||||
|
// Check if user is admin
|
||||||
|
const isAdmin = session?.user?.role === "admin";
|
||||||
|
|
||||||
|
// This effect handles authentication and initial clue data fetch
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
let isMounted = true; // Flag to prevent state updates after unmount
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
// Only allow refreshes every 10 seconds (more for admins)
|
||||||
|
const minRefreshInterval = isAdmin ? 30000 : 10000; // 30 seconds for admins, 10 seconds for regular users
|
||||||
|
|
||||||
|
// Skip if we refreshed too recently and this isn't the first load
|
||||||
|
if (loading === false && now - lastRefresh < minRefreshInterval) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (status === "unauthenticated") {
|
if (status === "unauthenticated") {
|
||||||
router.push("/login");
|
router.push("/login");
|
||||||
return;
|
return;
|
||||||
@@ -34,11 +50,14 @@ export default function CluePage({ params }) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch clue data
|
// One-time fetch clue data with debouncing
|
||||||
async function fetchClue() {
|
async function fetchClue() {
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const response = await fetch(`/api/clues/${clueId}`, {
|
|
||||||
|
// Add timestamp to avoid browser caching
|
||||||
|
const timestamp = Date.now();
|
||||||
|
const response = await fetch(`/api/clues/${clueId}?t=${timestamp}`, {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -57,49 +76,76 @@ export default function CluePage({ params }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
|
// Only update state if the component is still mounted
|
||||||
|
if (isMounted) {
|
||||||
setClue(data);
|
setClue(data);
|
||||||
|
// Only set foundNow on initial load or if it's actually newly found
|
||||||
|
if (loading === true) {
|
||||||
setFoundNow(data.foundNow);
|
setFoundNow(data.foundNow);
|
||||||
|
}
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
setLastRefresh(Date.now()); // Update last refresh timestamp
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Error fetching clue:", err);
|
console.error("Error fetching clue:", err);
|
||||||
|
if (isMounted) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fetchClue();
|
fetchClue();
|
||||||
}, [clueId, router, status]);
|
|
||||||
|
|
||||||
// Update timer display
|
// Cleanup function to prevent state updates after unmount
|
||||||
|
return () => {
|
||||||
|
isMounted = false;
|
||||||
|
};
|
||||||
|
}, [clueId, router, status, lastRefresh, loading, isAdmin]); // Add isAdmin and lastRefresh to dependencies
|
||||||
|
|
||||||
|
// Separate effect to handle timer updates - doesn't re-fetch data
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
let timerId;
|
||||||
|
|
||||||
// Set up timer display updates
|
// Set up timer display updates
|
||||||
const timerData = getHuntTimer();
|
const timerData = getHuntTimer();
|
||||||
if (!timerData || !timerData.isActive) {
|
if (!timerData || !timerData.isActive) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const timer = setInterval(() => {
|
|
||||||
setElapsedTime(formatElapsedTime(timerData.startTime));
|
|
||||||
}, 1000);
|
|
||||||
|
|
||||||
// Initial set
|
// Initial set
|
||||||
setElapsedTime(formatElapsedTime(timerData.startTime));
|
setElapsedTime(formatElapsedTime(timerData.startTime));
|
||||||
|
|
||||||
return () => clearInterval(timer);
|
// Update timer every second
|
||||||
}, []);
|
timerId = setInterval(() => {
|
||||||
|
setElapsedTime(formatElapsedTime(timerData.startTime));
|
||||||
|
}, 1000);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
if (timerId) clearInterval(timerId);
|
||||||
|
};
|
||||||
|
}, []); // Empty dependency array so it only runs once
|
||||||
|
|
||||||
// Handle QR scan result
|
// Handle QR scan result
|
||||||
const handleScan = (data) => {
|
const handleScan = (data) => {
|
||||||
setScanResult(data);
|
setScanResult(data);
|
||||||
setScanMessage(`QR Code scanned: ${data}`);
|
setScanMessage(`QR Code scanned: ${data}`);
|
||||||
|
|
||||||
// Here you would typically verify the QR code matches expected value
|
|
||||||
// and then mark the clue as found via API
|
|
||||||
|
|
||||||
// For now, just simulate successful scan and move to the next clue
|
|
||||||
try {
|
try {
|
||||||
const scannedClueId = parseInt(data);
|
// Handle both "QR123" format and just "123" format
|
||||||
if (scannedClueId === parseInt(clueId)) {
|
let scannedClueId;
|
||||||
|
const match = data.match(/^QR(\d+)$/i);
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
// Extract the number from QR[number]
|
||||||
|
scannedClueId = parseInt(match[1], 10);
|
||||||
|
} else {
|
||||||
|
// Try to parse the raw value
|
||||||
|
scannedClueId = parseInt(data, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isNaN(scannedClueId) && scannedClueId === parseInt(clueId)) {
|
||||||
// Correct QR code scanned, mark as found and move to next clue
|
// Correct QR code scanned, mark as found and move to next clue
|
||||||
markClueAsFound(clueId);
|
markClueAsFound(clueId);
|
||||||
} else {
|
} else {
|
||||||
@@ -178,6 +224,12 @@ export default function CluePage({ params }) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Function for manual refresh - for admins to test without waiting
|
||||||
|
const handleManualRefresh = () => {
|
||||||
|
// Force a refresh by setting lastRefresh to 0
|
||||||
|
setLastRefresh(0);
|
||||||
|
};
|
||||||
|
|
||||||
if (loading) {
|
if (loading) {
|
||||||
return (
|
return (
|
||||||
<div className="clue-container">
|
<div className="clue-container">
|
||||||
@@ -226,6 +278,19 @@ export default function CluePage({ params }) {
|
|||||||
<div className="timer-display">{elapsedTime}</div>
|
<div className="timer-display">{elapsedTime}</div>
|
||||||
|
|
||||||
<div className="clue-content-wrapper">
|
<div className="clue-content-wrapper">
|
||||||
|
{/* Admin tools section - only visible to admins */}
|
||||||
|
{isAdmin && (
|
||||||
|
<div className="admin-tools">
|
||||||
|
<div className="admin-badge">Admin View</div>
|
||||||
|
<button
|
||||||
|
onClick={handleManualRefresh}
|
||||||
|
className="admin-refresh-button"
|
||||||
|
>
|
||||||
|
Refresh Clue Data
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* QR Scanner Section */}
|
{/* QR Scanner Section */}
|
||||||
<div className="scanner-section">
|
<div className="scanner-section">
|
||||||
<h2>Scan QR Code</h2>
|
<h2>Scan QR Code</h2>
|
||||||
@@ -517,6 +582,37 @@ export default function CluePage({ params }) {
|
|||||||
.nav-label {
|
.nav-label {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Admin tools styling */
|
||||||
|
.admin-tools {
|
||||||
|
background-color: #f8d7da;
|
||||||
|
border: 2px dashed #d9534f;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 12px;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
text-align: center;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-badge {
|
||||||
|
font-weight: bold;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
color: #d9534f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-refresh-button {
|
||||||
|
background-color: #d9534f;
|
||||||
|
color: white;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 8px 16px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-refresh-button:hover {
|
||||||
|
background-color: #c9302c;
|
||||||
|
}
|
||||||
`}</style>
|
`}</style>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { getToken } from "next-auth/jwt";
|
import { getToken } from "next-auth/jwt";
|
||||||
import { queryOne, run } from "@/lib/db";
|
import { queryOne, query, run } from "@/lib/db";
|
||||||
|
|
||||||
export const dynamic = "force-dynamic"; // Disable caching
|
export const dynamic = "force-dynamic"; // Disable caching
|
||||||
|
|
||||||
@@ -32,39 +32,120 @@ export async function DELETE(request, context) {
|
|||||||
return Response.json({ error }, { status });
|
return Response.json({ error }, { status });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { clueId } = context.params;
|
// Get clueId parameter - properly awaited
|
||||||
|
const { clueId } = await context.params;
|
||||||
|
|
||||||
// Validate clueId is a number
|
// Validate clueId is a number
|
||||||
if (isNaN(parseInt(clueId))) {
|
if (isNaN(parseInt(clueId))) {
|
||||||
return Response.json({ error: "Invalid clue ID" }, { status: 400 });
|
return Response.json({ error: "Invalid clue ID" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if clue exists
|
// Always set shouldRenumber to true - no longer read from request body
|
||||||
const clue = await queryOne("SELECT id FROM clues WHERE id = ?", [clueId]);
|
const shouldRenumber = true;
|
||||||
|
|
||||||
|
// Check if clue exists and get its QR code value
|
||||||
|
const clue = await queryOne("SELECT id, qr_code FROM clues WHERE id = ?", [
|
||||||
|
clueId,
|
||||||
|
]);
|
||||||
if (!clue) {
|
if (!clue) {
|
||||||
return Response.json({ error: "Clue not found" }, { status: 404 });
|
return Response.json({ error: "Clue not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete clue record
|
console.log(
|
||||||
await run("DELETE FROM clues WHERE id = ?", [clueId]);
|
`Starting deletion of clue ${clueId} with QR code ${clue.qr_code}`
|
||||||
|
);
|
||||||
|
|
||||||
// Also delete any references in team_clues table
|
// Start a transaction for atomicity
|
||||||
|
try {
|
||||||
|
await run("BEGIN TRANSACTION");
|
||||||
|
|
||||||
|
console.log("Transaction started");
|
||||||
|
|
||||||
|
// First, make sure the team_clues table exists and clear any references
|
||||||
await run(`
|
await run(`
|
||||||
CREATE TABLE IF NOT EXISTS team_clues (
|
CREATE TABLE IF NOT EXISTS team_clues (
|
||||||
team_id INTEGER NOT NULL,
|
team_id INTEGER NOT NULL,
|
||||||
clue_id INTEGER NOT NULL,
|
clue_id INTEGER NOT NULL,
|
||||||
found_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
found_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
PRIMARY KEY (team_id, clue_id),
|
PRIMARY KEY (team_id, clue_id),
|
||||||
FOREIGN KEY (team_id) REFERENCES teams(id),
|
FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE,
|
||||||
FOREIGN KEY (clue_id) REFERENCES clues(id)
|
FOREIGN KEY (clue_id) REFERENCES clues(id) ON DELETE CASCADE
|
||||||
)
|
)
|
||||||
`);
|
`);
|
||||||
await run("DELETE FROM team_clues WHERE clue_id = ?", [clueId]);
|
|
||||||
|
// Delete any references in team_clues table
|
||||||
|
const deleteTeamClues = await run(
|
||||||
|
"DELETE FROM team_clues WHERE clue_id = ?",
|
||||||
|
[clueId]
|
||||||
|
);
|
||||||
|
console.log(
|
||||||
|
`Deleted team clues result: ${deleteTeamClues.changes} references cleared`
|
||||||
|
);
|
||||||
|
|
||||||
|
// Delete clue record
|
||||||
|
const deleteResult = await run("DELETE FROM clues WHERE id = ?", [
|
||||||
|
clueId,
|
||||||
|
]);
|
||||||
|
console.log(`Deleted clue result: ${deleteResult.changes} rows affected`);
|
||||||
|
|
||||||
|
if (deleteResult.changes === 0) {
|
||||||
|
throw new Error(`Clue ${clueId} was not deleted`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If renumbering is enabled (which is always true now)
|
||||||
|
if (shouldRenumber) {
|
||||||
|
// Always use the sequential renumbering approach
|
||||||
|
// This ensures QR codes are sequential regardless of DB IDs
|
||||||
|
console.log("Renumbering all QR codes sequentially");
|
||||||
|
|
||||||
|
// Get all remaining clues ordered by ID
|
||||||
|
const allClues = await query("SELECT id FROM clues ORDER BY id ASC");
|
||||||
|
console.log(`Found ${allClues.length} clues to renumber`);
|
||||||
|
|
||||||
|
// Update each clue to have sequential QR[index+1] format
|
||||||
|
for (let i = 0; i < allClues.length; i++) {
|
||||||
|
const clue = allClues[i];
|
||||||
|
const sequentialQrCode = `QR${i + 1}`;
|
||||||
|
|
||||||
|
const updateResult = await run(
|
||||||
|
"UPDATE clues SET qr_code = ? WHERE id = ?",
|
||||||
|
[sequentialQrCode, clue.id]
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Updated clue ${clue.id} to ${sequentialQrCode}: ${updateResult.changes} rows affected`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit the transaction
|
||||||
|
await run("COMMIT");
|
||||||
|
console.log("Transaction committed successfully");
|
||||||
|
|
||||||
return Response.json({
|
return Response.json({
|
||||||
success: true,
|
success: true,
|
||||||
message: "Clue deleted successfully",
|
message: "Clue deleted successfully",
|
||||||
|
renumbered: shouldRenumber,
|
||||||
});
|
});
|
||||||
|
} catch (transactionError) {
|
||||||
|
// If any error occurs, roll back the transaction
|
||||||
|
console.error("Error during deletion transaction:", transactionError);
|
||||||
|
try {
|
||||||
|
await run("ROLLBACK");
|
||||||
|
console.log("Transaction rolled back");
|
||||||
|
} catch (rollbackError) {
|
||||||
|
console.error("Error while rolling back transaction:", rollbackError);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Provide more specific error message based on the error type
|
||||||
|
let errorMessage = "Failed to delete clue: " + transactionError.message;
|
||||||
|
if (transactionError.message.includes("SQLITE_CONSTRAINT")) {
|
||||||
|
errorMessage =
|
||||||
|
"Database constraint violation. The clue may be referenced by other records.";
|
||||||
|
}
|
||||||
|
|
||||||
|
return Response.json({ error: errorMessage }, { status: 500 });
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Admin clue deletion error:", error);
|
console.error("Admin clue deletion error:", error);
|
||||||
return Response.json(
|
return Response.json(
|
||||||
@@ -83,16 +164,17 @@ export async function GET(request, context) {
|
|||||||
return Response.json({ error }, { status });
|
return Response.json({ error }, { status });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { clueId } = context.params;
|
// Get clueId parameter - properly awaited
|
||||||
|
const { clueId } = await context.params;
|
||||||
|
|
||||||
// Validate clueId is a number
|
// Validate clueId is a number
|
||||||
if (isNaN(parseInt(clueId))) {
|
if (isNaN(parseInt(clueId))) {
|
||||||
return Response.json({ error: "Invalid clue ID" }, { status: 400 });
|
return Response.json({ error: "Invalid clue ID" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the specific clue - removed coordinates
|
// Get the specific clue - now including qr_code
|
||||||
const clue = await queryOne(
|
const clue = await queryOne(
|
||||||
"SELECT id, title, description, location FROM clues WHERE id = ?",
|
"SELECT id, title, description, location, qr_code FROM clues WHERE id = ?",
|
||||||
[clueId]
|
[clueId]
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -119,15 +201,16 @@ export async function PUT(request, context) {
|
|||||||
return Response.json({ error }, { status });
|
return Response.json({ error }, { status });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { clueId } = context.params;
|
// Get clueId parameter - properly awaited
|
||||||
|
const { clueId } = await context.params;
|
||||||
|
|
||||||
// Validate clueId is a number
|
// Validate clueId is a number
|
||||||
if (isNaN(parseInt(clueId))) {
|
if (isNaN(parseInt(clueId))) {
|
||||||
return Response.json({ error: "Invalid clue ID" }, { status: 400 });
|
return Response.json({ error: "Invalid clue ID" }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the request body - removed coordinates
|
// Parse the request body
|
||||||
const { title, description, location } = await request.json();
|
const { title, description, location, qr_code } = await request.json();
|
||||||
|
|
||||||
// Validate required fields
|
// Validate required fields
|
||||||
if (!title || !description) {
|
if (!title || !description) {
|
||||||
@@ -137,20 +220,33 @@ export async function PUT(request, context) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate QR code format if provided
|
||||||
|
if (qr_code && !qr_code.match(/^QR\d+$/i)) {
|
||||||
|
return Response.json(
|
||||||
|
{ error: "QR code must follow the format QR[number], e.g. QR1, QR2" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Check if clue exists
|
// Check if clue exists
|
||||||
const clue = await queryOne("SELECT id FROM clues WHERE id = ?", [clueId]);
|
const clue = await queryOne("SELECT id, qr_code FROM clues WHERE id = ?", [
|
||||||
|
clueId,
|
||||||
|
]);
|
||||||
if (!clue) {
|
if (!clue) {
|
||||||
return Response.json({ error: "Clue not found" }, { status: 404 });
|
return Response.json({ error: "Clue not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the clue - removed coordinates
|
// Allow custom QR code - no longer enforcing QR{id} format
|
||||||
|
const finalQrCode = qr_code || `QR${clueId}`;
|
||||||
|
|
||||||
|
// Update the clue with the provided or default QR code
|
||||||
await run(
|
await run(
|
||||||
`
|
`
|
||||||
UPDATE clues
|
UPDATE clues
|
||||||
SET title = ?, description = ?, location = ?
|
SET title = ?, description = ?, location = ?, qr_code = ?
|
||||||
WHERE id = ?
|
WHERE id = ?
|
||||||
`,
|
`,
|
||||||
[title, description, location || "", clueId]
|
[title, description, location || "", finalQrCode, clueId]
|
||||||
);
|
);
|
||||||
|
|
||||||
return Response.json({
|
return Response.json({
|
||||||
|
|||||||
+120
-17
@@ -39,13 +39,14 @@ export async function GET(request) {
|
|||||||
title TEXT NOT NULL,
|
title TEXT NOT NULL,
|
||||||
description TEXT NOT NULL,
|
description TEXT NOT NULL,
|
||||||
location TEXT,
|
location TEXT,
|
||||||
|
qr_code TEXT DEFAULT '',
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
)
|
)
|
||||||
`);
|
`);
|
||||||
|
|
||||||
// Fetch all clues with sequential ordering
|
// Fetch all clues with sequential ordering - IMPORTANT: explicitly include qr_code field
|
||||||
const clues = await query(`
|
const clues = await query(`
|
||||||
SELECT id, title, description, location, created_at
|
SELECT id, title, description, location, qr_code, created_at
|
||||||
FROM clues
|
FROM clues
|
||||||
ORDER BY id ASC
|
ORDER BY id ASC
|
||||||
`);
|
`);
|
||||||
@@ -77,34 +78,136 @@ export async function POST(request) {
|
|||||||
return Response.json({ error }, { status });
|
return Response.json({ error }, { status });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the request body - simplified without coordinates
|
// Parse the request body - now accepting qr_code
|
||||||
const { title, description, location = "" } = await request.json();
|
let bodyData;
|
||||||
|
try {
|
||||||
// Validate required fields
|
bodyData = await request.json();
|
||||||
if (!title || !description) {
|
} catch (parseError) {
|
||||||
|
console.error("Error parsing JSON request body:", parseError);
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{ error: "Title and description are required" },
|
{ error: "Invalid JSON in request body" },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Insert the new clue - simplified without coordinates
|
const { title, description, location = "", qr_code = "" } = bodyData;
|
||||||
await run(
|
|
||||||
`
|
// Add more detailed validation
|
||||||
INSERT INTO clues (title, description, location)
|
if (!title) {
|
||||||
VALUES (?, ?, ?)
|
return Response.json({ error: "Title is required" }, { status: 400 });
|
||||||
`,
|
}
|
||||||
[title, description, location]
|
|
||||||
|
if (!description) {
|
||||||
|
return Response.json(
|
||||||
|
{ error: "Description is required" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate QR code format if provided
|
||||||
|
if (qr_code && !qr_code.match(/^QR\d+$/i)) {
|
||||||
|
return Response.json(
|
||||||
|
{ error: "QR code must follow the format QR[number], e.g. QR1, QR2" },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure the clues table exists before inserting
|
||||||
|
try {
|
||||||
|
await run(`
|
||||||
|
CREATE TABLE IF NOT EXISTS clues (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
location TEXT,
|
||||||
|
qr_code TEXT DEFAULT '',
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Check if we need to add the qr_code column (for existing tables that don't have it)
|
||||||
|
try {
|
||||||
|
// First check if the column exists
|
||||||
|
const tableInfo = await query(`PRAGMA table_info(clues)`);
|
||||||
|
const qrCodeColumnExists = tableInfo.some(
|
||||||
|
(col) => col.name === "qr_code"
|
||||||
);
|
);
|
||||||
|
|
||||||
// Get the inserted clue ID
|
if (!qrCodeColumnExists) {
|
||||||
|
// If the column doesn't exist, add it with a default value
|
||||||
|
await run(`ALTER TABLE clues ADD COLUMN qr_code TEXT DEFAULT ''`);
|
||||||
|
console.log("Added qr_code column to clues table");
|
||||||
|
}
|
||||||
|
} catch (alterTableError) {
|
||||||
|
console.error(
|
||||||
|
"Error checking/modifying table structure:",
|
||||||
|
alterTableError
|
||||||
|
);
|
||||||
|
// Continue anyway - the insertion will either work or fail
|
||||||
|
}
|
||||||
|
} catch (tableError) {
|
||||||
|
console.error("Error ensuring table exists:", tableError);
|
||||||
|
return Response.json(
|
||||||
|
{ error: "Database error: Could not ensure clues table exists" },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert the new clue with QR code if provided
|
||||||
|
let result;
|
||||||
|
try {
|
||||||
|
if (qr_code) {
|
||||||
|
// If QR code is provided, use it
|
||||||
|
result = await run(
|
||||||
|
`INSERT INTO clues (title, description, location, qr_code) VALUES (?, ?, ?, ?)`,
|
||||||
|
[title, description, location, qr_code]
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Otherwise, just insert without QR code (will be set later)
|
||||||
|
result = await run(
|
||||||
|
`INSERT INTO clues (title, description, location) VALUES (?, ?, ?)`,
|
||||||
|
[title, description, location]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (insertError) {
|
||||||
|
console.error("Database insert error:", insertError);
|
||||||
|
return Response.json(
|
||||||
|
{ error: `Database error: ${insertError.message}` },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the inserted clue ID and update QR codes
|
||||||
|
let newClueId;
|
||||||
|
try {
|
||||||
const newClue = await queryOne("SELECT last_insert_rowid() as id");
|
const newClue = await queryOne("SELECT last_insert_rowid() as id");
|
||||||
|
newClueId = newClue?.id;
|
||||||
|
|
||||||
|
// If no QR code was provided, update all QR codes to ensure sequential order
|
||||||
|
if (!qr_code && newClueId) {
|
||||||
|
// Update all clues to have sequential QR codes
|
||||||
|
const allClues = await query("SELECT id FROM clues ORDER BY id ASC");
|
||||||
|
|
||||||
|
// Update each clue to have QR[index+1] format (sequential without gaps)
|
||||||
|
for (let i = 0; i < allClues.length; i++) {
|
||||||
|
const clue = allClues[i];
|
||||||
|
const sequentialQrCode = `QR${i + 1}`;
|
||||||
|
await run("UPDATE clues SET qr_code = ? WHERE id = ?", [
|
||||||
|
sequentialQrCode,
|
||||||
|
clue.id,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (updateError) {
|
||||||
|
console.error("Error updating QR codes:", updateError);
|
||||||
|
// Continue anyway, the clue was inserted successfully
|
||||||
|
}
|
||||||
|
|
||||||
return Response.json(
|
return Response.json(
|
||||||
{
|
{
|
||||||
success: true,
|
success: true,
|
||||||
message: "Clue added successfully",
|
message: "Clue added successfully",
|
||||||
clueId: newClue.id,
|
clueId: newClueId || null,
|
||||||
},
|
},
|
||||||
{ status: 201 }
|
{ status: 201 }
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,200 @@
|
|||||||
|
import { getToken } from "next-auth/jwt";
|
||||||
|
import { query, 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 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST endpoint to fix database schema issues
|
||||||
|
export async function POST(request) {
|
||||||
|
try {
|
||||||
|
// Verify admin access
|
||||||
|
const { authorized, error, status } = await verifyAdmin(request);
|
||||||
|
if (!authorized) {
|
||||||
|
return Response.json({ error }, { status });
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = {
|
||||||
|
success: true,
|
||||||
|
operations: [],
|
||||||
|
errors: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get current table structure
|
||||||
|
const tableInfo = await query("PRAGMA table_info(clues)");
|
||||||
|
console.log("Current clues table schema:", tableInfo);
|
||||||
|
|
||||||
|
// Check if qr_code column exists and its constraints
|
||||||
|
const qrCodeColumn = tableInfo.find((col) => col.name === "qr_code");
|
||||||
|
|
||||||
|
if (!qrCodeColumn) {
|
||||||
|
// QR code column doesn't exist, add it with default empty string
|
||||||
|
try {
|
||||||
|
await run("ALTER TABLE clues ADD COLUMN qr_code TEXT DEFAULT ''");
|
||||||
|
result.operations.push(
|
||||||
|
"Added qr_code column with TEXT type and empty default"
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error adding qr_code column:", err);
|
||||||
|
result.errors.push(`Failed to add qr_code column: ${err.message}`);
|
||||||
|
}
|
||||||
|
} else if (qrCodeColumn.notnull === 1 && !qrCodeColumn.dflt_value) {
|
||||||
|
// Column exists but has NOT NULL constraint with no default
|
||||||
|
// We need to recreate the table to modify constraints
|
||||||
|
try {
|
||||||
|
// Start transaction
|
||||||
|
await run("BEGIN TRANSACTION");
|
||||||
|
|
||||||
|
// Create new table with correct schema
|
||||||
|
await run(`
|
||||||
|
CREATE TABLE clues_new (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
description TEXT NOT NULL,
|
||||||
|
location TEXT,
|
||||||
|
qr_code TEXT DEFAULT '',
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Copy data
|
||||||
|
await run(`
|
||||||
|
INSERT INTO clues_new (id, title, description, location, qr_code, created_at)
|
||||||
|
SELECT id, title, description, location, COALESCE(qr_code, 'QR' || id) as qr_code, created_at
|
||||||
|
FROM clues
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Drop old table
|
||||||
|
await run("DROP TABLE clues");
|
||||||
|
|
||||||
|
// Rename new table to original name
|
||||||
|
await run("ALTER TABLE clues_new RENAME TO clues");
|
||||||
|
|
||||||
|
// Commit transaction
|
||||||
|
await run("COMMIT");
|
||||||
|
|
||||||
|
result.operations.push("Recreated clues table with proper schema");
|
||||||
|
} catch (err) {
|
||||||
|
// Rollback on error
|
||||||
|
try {
|
||||||
|
await run("ROLLBACK");
|
||||||
|
} catch (rollbackErr) {
|
||||||
|
console.error("Error during rollback:", rollbackErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.error("Error fixing table schema:", err);
|
||||||
|
result.errors.push(`Failed to fix table schema: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure all clues have proper QR codes
|
||||||
|
try {
|
||||||
|
// Update any NULL QR codes to match their ID
|
||||||
|
await run(
|
||||||
|
"UPDATE clues SET qr_code = 'QR' || id WHERE qr_code IS NULL OR qr_code = ''"
|
||||||
|
);
|
||||||
|
result.operations.push("Updated any missing QR codes to match their IDs");
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error updating QR codes:", err);
|
||||||
|
result.errors.push(`Failed to update QR codes: ${err.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure all clues have proper sequential QR codes
|
||||||
|
try {
|
||||||
|
// Get all clues ordered by ID
|
||||||
|
const clues = await query("SELECT id FROM clues ORDER BY id ASC");
|
||||||
|
|
||||||
|
// Update each clue to have QR[index+1] format (sequential without gaps)
|
||||||
|
for (let i = 0; i < clues.length; i++) {
|
||||||
|
const clue = clues[i];
|
||||||
|
const sequentialQrCode = `QR${i + 1}`;
|
||||||
|
await run("UPDATE clues SET qr_code = ? WHERE id = ?", [
|
||||||
|
sequentialQrCode,
|
||||||
|
clue.id,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
result.operations.push(
|
||||||
|
"Updated all QR codes to be sequential (QR1, QR2, etc.)"
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error updating sequential QR codes:", err);
|
||||||
|
result.errors.push(
|
||||||
|
`Failed to update sequential QR codes: ${err.message}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add foreign key support for team_clues table
|
||||||
|
try {
|
||||||
|
await run(`
|
||||||
|
CREATE TABLE IF NOT EXISTS team_clues_new (
|
||||||
|
team_id INTEGER NOT NULL,
|
||||||
|
clue_id INTEGER NOT NULL,
|
||||||
|
found_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (team_id, clue_id),
|
||||||
|
FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY (clue_id) REFERENCES clues(id) ON DELETE CASCADE
|
||||||
|
)
|
||||||
|
`);
|
||||||
|
|
||||||
|
// Copy existing data if the table already exists
|
||||||
|
try {
|
||||||
|
await run(`
|
||||||
|
INSERT OR IGNORE INTO team_clues_new (team_id, clue_id, found_at)
|
||||||
|
SELECT team_id, clue_id, found_at FROM team_clues
|
||||||
|
`);
|
||||||
|
} catch (copyErr) {
|
||||||
|
// If the old table doesn't exist, this is fine
|
||||||
|
console.log("Note: No existing team_clues data to copy");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drop the old table if it exists
|
||||||
|
try {
|
||||||
|
await run("DROP TABLE IF EXISTS team_clues");
|
||||||
|
} catch (dropErr) {
|
||||||
|
console.error("Error dropping old team_clues table:", dropErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rename new table
|
||||||
|
await run("ALTER TABLE team_clues_new RENAME TO team_clues");
|
||||||
|
|
||||||
|
result.operations.push("Updated team_clues table with ON DELETE CASCADE");
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error fixing team_clues table:", err);
|
||||||
|
result.errors.push(`Failed to fix team_clues table: ${err.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return result summary
|
||||||
|
return Response.json({
|
||||||
|
...result,
|
||||||
|
message:
|
||||||
|
result.errors.length === 0
|
||||||
|
? "Database schema fixed successfully"
|
||||||
|
: "Database fix completed with some errors",
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Database fix error:", error);
|
||||||
|
return Response.json(
|
||||||
|
{ error: "Failed to fix database: " + error.message },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { getToken } from "next-auth/jwt";
|
||||||
|
import { query, 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 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// POST - Fix all QR codes in the database to follow the QR[id] format
|
||||||
|
export async function POST(request) {
|
||||||
|
try {
|
||||||
|
// Verify admin access
|
||||||
|
const { authorized, error, status } = await verifyAdmin(request);
|
||||||
|
if (!authorized) {
|
||||||
|
return Response.json({ error }, { status });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get all clues ordered by ID to maintain sequence
|
||||||
|
const clues = await query("SELECT id FROM clues ORDER BY id ASC");
|
||||||
|
|
||||||
|
// Count of fixed clues
|
||||||
|
let fixedCount = 0;
|
||||||
|
|
||||||
|
// Start a transaction
|
||||||
|
await run("BEGIN TRANSACTION");
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Assign sequential QR codes (QR1, QR2, QR3, etc.) based on array index
|
||||||
|
// This ensures no gaps in the QR sequence regardless of DB IDs
|
||||||
|
for (let i = 0; i < clues.length; i++) {
|
||||||
|
const sequentialQrCode = `QR${i + 1}`;
|
||||||
|
|
||||||
|
// Update the clue with the sequential QR code
|
||||||
|
await run("UPDATE clues SET qr_code = ? WHERE id = ?", [
|
||||||
|
sequentialQrCode,
|
||||||
|
clues[i].id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
fixedCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit changes
|
||||||
|
await run("COMMIT");
|
||||||
|
|
||||||
|
return Response.json({
|
||||||
|
success: true,
|
||||||
|
message: `QR codes fixed successfully. Set ${fixedCount} clues to sequential QR codes without gaps.`,
|
||||||
|
totalClues: clues.length,
|
||||||
|
fixedClues: fixedCount,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
// Roll back on error
|
||||||
|
await run("ROLLBACK");
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Fix QR codes error:", error);
|
||||||
|
return Response.json(
|
||||||
|
{ error: "Failed to fix QR codes: " + error.message },
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,14 +41,23 @@ export async function GET(request, context) {
|
|||||||
return Response.json({ error: "Clue not found" }, { status: 404 });
|
return Response.json({ error: "Clue not found" }, { status: 404 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get timestamp parameter to determine if this is a refresh call
|
||||||
|
const timestamp = request.nextUrl?.searchParams?.get("t");
|
||||||
|
const isRefresh = timestamp && !isNaN(parseInt(timestamp));
|
||||||
|
|
||||||
// Check if this team has found this clue before
|
// Check if this team has found this clue before
|
||||||
const found = await queryOne(
|
const found = await queryOne(
|
||||||
"SELECT * FROM team_clues WHERE team_id = ? AND clue_id = ?",
|
"SELECT * FROM team_clues WHERE team_id = ? AND clue_id = ?",
|
||||||
[token.teamId, clueId]
|
[token.teamId, clueId]
|
||||||
);
|
);
|
||||||
|
|
||||||
// If not found yet, mark it as found now
|
// Only mark as "foundNow" if:
|
||||||
if (!found) {
|
// 1. The clue was not found before
|
||||||
|
// 2. This is not a refresh request (or we can't determine)
|
||||||
|
// 3. The user is not an admin (admins don't need "foundNow" animations)
|
||||||
|
let foundNow = false;
|
||||||
|
|
||||||
|
if (!found && (!isRefresh || token.role !== "admin")) {
|
||||||
try {
|
try {
|
||||||
// First ensure the team_clues table exists
|
// First ensure the team_clues table exists
|
||||||
await queryOne(`
|
await queryOne(`
|
||||||
@@ -67,25 +76,41 @@ export async function GET(request, context) {
|
|||||||
"INSERT INTO team_clues (team_id, clue_id) VALUES (?, ?)",
|
"INSERT INTO team_clues (team_id, clue_id) VALUES (?, ?)",
|
||||||
[token.teamId, clueId]
|
[token.teamId, clueId]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Set foundNow flag for non-admin users only
|
||||||
|
foundNow = token.role !== "admin";
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Clue ${clueId} marked as found for team ${token.teamId}, foundNow=${foundNow}`
|
||||||
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Error marking clue as found:", err);
|
console.error("Error marking clue as found:", err);
|
||||||
// Continue even if there's an error recording the find
|
// Continue even if there's an error recording the find
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Response.json(
|
// Add different cache headers for admins vs regular users
|
||||||
{
|
const cacheHeaders =
|
||||||
...clue,
|
token.role === "admin"
|
||||||
found: !!found,
|
? {
|
||||||
foundNow: !found,
|
"Cache-Control": "private, max-age=10", // Allow 10 seconds of caching for admins
|
||||||
},
|
Pragma: "no-cache",
|
||||||
{
|
Expires: "0",
|
||||||
headers: {
|
}
|
||||||
|
: {
|
||||||
"Cache-Control": "no-store, no-cache, must-revalidate",
|
"Cache-Control": "no-store, no-cache, must-revalidate",
|
||||||
Pragma: "no-cache",
|
Pragma: "no-cache",
|
||||||
Expires: "0",
|
Expires: "0",
|
||||||
|
};
|
||||||
|
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
...clue,
|
||||||
|
found: true, // Always return as found since the user is viewing it
|
||||||
|
foundNow, // Only true during initial discovery for non-admins
|
||||||
|
isAdmin: token.role === "admin", // Add flag so client knows user is admin
|
||||||
},
|
},
|
||||||
}
|
{ headers: cacheHeaders }
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching clue:", error);
|
console.error("Error fetching clue:", error);
|
||||||
|
|||||||
@@ -218,19 +218,41 @@ export async function GET(request) {
|
|||||||
? huntActiveSetting.value === "true"
|
? huntActiveSetting.value === "true"
|
||||||
: false;
|
: false;
|
||||||
|
|
||||||
|
// Use the actual timer status as the source of truth if it exists
|
||||||
|
const isTimerActive = timerStatus ? !!timerStatus.active : false;
|
||||||
|
|
||||||
|
// Determine the actual active state by checking both sources
|
||||||
|
// This ensures we don't miss an active timer due to inconsistent settings
|
||||||
|
const isActuallyActive = huntActive || isTimerActive;
|
||||||
|
|
||||||
if (!timerStatus) {
|
if (!timerStatus) {
|
||||||
return Response.json({
|
return Response.json({
|
||||||
active: huntActive, // Use settings value if timer not found
|
active: isActuallyActive,
|
||||||
|
timerActive: false,
|
||||||
startTime: null,
|
startTime: null,
|
||||||
endTime: null,
|
endTime: null,
|
||||||
|
serverTime: new Date().toISOString(),
|
||||||
|
timestamp: Date.now(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return Response.json({
|
// Add cache-busting timestamp to ensure fresh data
|
||||||
active: huntActive, // Return settings value for consistency
|
const responseData = {
|
||||||
timerActive: !!timerStatus.active, // Also return timer status for admin panel
|
// Return consistent activity status from both sources
|
||||||
|
active: isActuallyActive,
|
||||||
|
timerActive: isTimerActive,
|
||||||
startTime: timerStatus.start_time,
|
startTime: timerStatus.start_time,
|
||||||
endTime: timerStatus.end_time,
|
endTime: timerStatus.end_time,
|
||||||
|
serverTime: new Date().toISOString(),
|
||||||
|
timestamp: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
return Response.json(responseData, {
|
||||||
|
headers: {
|
||||||
|
"Cache-Control": "no-store, no-cache, must-revalidate",
|
||||||
|
Pragma: "no-cache",
|
||||||
|
Expires: "0",
|
||||||
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error getting timer status:", error);
|
console.error("Error getting timer status:", error);
|
||||||
|
|||||||
Binary file not shown.
@@ -17,36 +17,113 @@ export function getDb() {
|
|||||||
|
|
||||||
export function queryOne(sql, params = []) {
|
export function queryOne(sql, params = []) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
getDb().get(sql, params, (err, row) => {
|
const db = getDb();
|
||||||
if (err) {
|
if (!db) {
|
||||||
reject(err);
|
reject(new Error("Database connection not available"));
|
||||||
} else {
|
return;
|
||||||
resolve(row);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
db.get(sql, params, function (err, row) {
|
||||||
|
if (err) {
|
||||||
|
console.error("SQL Error in queryOne():", err.message);
|
||||||
|
console.error("SQL Statement:", sql);
|
||||||
|
console.error("Parameters:", JSON.stringify(params));
|
||||||
|
reject(err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve(row);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function query(sql, params = []) {
|
export function query(sql, params = []) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
getDb().all(sql, params, (err, rows) => {
|
const db = getDb();
|
||||||
if (err) {
|
if (!db) {
|
||||||
reject(err);
|
reject(new Error("Database connection not available"));
|
||||||
} else {
|
return;
|
||||||
resolve(rows);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
db.all(sql, params, function (err, rows) {
|
||||||
|
if (err) {
|
||||||
|
console.error("SQL Error in query():", err.message);
|
||||||
|
console.error("SQL Statement:", sql);
|
||||||
|
console.error("Parameters:", JSON.stringify(params));
|
||||||
|
reject(err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve(rows || []);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function run(sql, params = []) {
|
export function run(sql, params = []) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
getDb().run(sql, params, function (err) {
|
const db = getDb();
|
||||||
|
if (!db) {
|
||||||
|
const error = new Error("Database connection not available");
|
||||||
|
console.error(error);
|
||||||
|
reject(error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add better logging
|
||||||
|
if (
|
||||||
|
sql.toLowerCase().includes("begin") ||
|
||||||
|
sql.toLowerCase().includes("commit") ||
|
||||||
|
sql.toLowerCase().includes("rollback")
|
||||||
|
) {
|
||||||
|
console.log(`Transaction operation: ${sql}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
db.run(sql, params, function (err) {
|
||||||
if (err) {
|
if (err) {
|
||||||
|
console.error("SQL Error in run():", err.message);
|
||||||
|
console.error("SQL Statement:", sql);
|
||||||
|
console.error("Parameters:", JSON.stringify(params));
|
||||||
reject(err);
|
reject(err);
|
||||||
} else {
|
return;
|
||||||
resolve({ lastID: this.lastID, changes: this.changes });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
resolve({
|
||||||
|
lastID: this.lastID,
|
||||||
|
changes: this.changes,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// New function to explicitly enable foreign keys
|
||||||
|
export function enableForeignKeys() {
|
||||||
|
return run("PRAGMA foreign_keys = ON;")
|
||||||
|
.then(() => console.log("Foreign key constraints enabled"))
|
||||||
|
.catch((err) => console.error("Error enabling foreign keys:", err));
|
||||||
|
}
|
||||||
|
|
||||||
|
// New function to run multiple statements as a transaction
|
||||||
|
export async function runTransaction(statements) {
|
||||||
|
try {
|
||||||
|
// Begin transaction
|
||||||
|
await run("BEGIN TRANSACTION");
|
||||||
|
|
||||||
|
// Execute all statements in order
|
||||||
|
for (const [sql, params] of statements) {
|
||||||
|
await run(sql, params);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit on success
|
||||||
|
await run("COMMIT");
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
// Rollback on any error
|
||||||
|
try {
|
||||||
|
await run("ROLLBACK");
|
||||||
|
console.log("Transaction rolled back due to error");
|
||||||
|
} catch (rollbackError) {
|
||||||
|
console.error("Error during rollback:", rollbackError);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
+92
-10
@@ -4,26 +4,41 @@
|
|||||||
|
|
||||||
// Store the hunt timer information in localStorage for persistence
|
// Store the hunt timer information in localStorage for persistence
|
||||||
export const setHuntTimer = (startTime, endTime = null, isActive = true) => {
|
export const setHuntTimer = (startTime, endTime = null, isActive = true) => {
|
||||||
|
if (!startTime) {
|
||||||
|
console.error("Cannot set timer without a start time");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
const timerData = {
|
const timerData = {
|
||||||
startTime,
|
startTime,
|
||||||
endTime,
|
endTime,
|
||||||
isActive,
|
isActive,
|
||||||
lastUpdated: new Date().toISOString(),
|
lastUpdated: new Date().toISOString(),
|
||||||
};
|
};
|
||||||
localStorage.setItem("huntTimerData", JSON.stringify(timerData));
|
|
||||||
};
|
|
||||||
|
|
||||||
// Clear the hunt timer completely
|
localStorage.setItem("huntTimerData", JSON.stringify(timerData));
|
||||||
export const clearHuntTimer = () => {
|
|
||||||
localStorage.removeItem("huntTimerData");
|
// Also save to sessionStorage as a fallback
|
||||||
localStorage.removeItem("teamHuntStartTime"); // Remove legacy timer as well
|
// This can survive page refreshes even if localStorage is cleared
|
||||||
|
sessionStorage.setItem("huntTimerData", JSON.stringify(timerData));
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error setting hunt timer data:", error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get the current hunt timer data with improved error handling
|
// Get the current hunt timer data with improved error handling
|
||||||
export const getHuntTimer = () => {
|
export const getHuntTimer = () => {
|
||||||
try {
|
try {
|
||||||
// First try to get timer data from localStorage
|
// First try to get timer data from localStorage
|
||||||
const timerData = localStorage.getItem("huntTimerData");
|
let timerData = localStorage.getItem("huntTimerData");
|
||||||
|
|
||||||
|
// If not in localStorage, try sessionStorage as fallback
|
||||||
|
if (!timerData) {
|
||||||
|
timerData = sessionStorage.getItem("huntTimerData");
|
||||||
|
}
|
||||||
|
|
||||||
if (!timerData) {
|
if (!timerData) {
|
||||||
// Try to migrate from old format if exists
|
// Try to migrate from old format if exists
|
||||||
@@ -39,9 +54,9 @@ export const getHuntTimer = () => {
|
|||||||
|
|
||||||
// Save the migrated data for future use
|
// Save the migrated data for future use
|
||||||
localStorage.setItem("huntTimerData", JSON.stringify(migratedData));
|
localStorage.setItem("huntTimerData", JSON.stringify(migratedData));
|
||||||
|
sessionStorage.setItem("huntTimerData", JSON.stringify(migratedData));
|
||||||
return migratedData;
|
return migratedData;
|
||||||
}
|
}
|
||||||
console.log("No hunt timer data found");
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,6 +76,7 @@ export const getHuntTimer = () => {
|
|||||||
// Try to recover by clearing corrupt data
|
// Try to recover by clearing corrupt data
|
||||||
try {
|
try {
|
||||||
localStorage.removeItem("huntTimerData");
|
localStorage.removeItem("huntTimerData");
|
||||||
|
sessionStorage.removeItem("huntTimerData");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// Ignore errors when trying to clean up
|
// Ignore errors when trying to clean up
|
||||||
}
|
}
|
||||||
@@ -69,16 +85,40 @@ export const getHuntTimer = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Calculate and format elapsed time from a given start time
|
// Clear the hunt timer completely
|
||||||
|
export const clearHuntTimer = () => {
|
||||||
|
try {
|
||||||
|
localStorage.removeItem("huntTimerData");
|
||||||
|
sessionStorage.removeItem("huntTimerData");
|
||||||
|
localStorage.removeItem("teamHuntStartTime"); // Remove legacy timer as well
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error clearing hunt timer data:", error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Calculate and format elapsed time from a given start time with high accuracy
|
||||||
export const formatElapsedTime = (startTimeStr) => {
|
export const formatElapsedTime = (startTimeStr) => {
|
||||||
if (!startTimeStr) return "00:00:00";
|
if (!startTimeStr) return "00:00:00";
|
||||||
|
|
||||||
|
try {
|
||||||
const startTime = new Date(startTimeStr).getTime();
|
const startTime = new Date(startTimeStr).getTime();
|
||||||
|
|
||||||
|
// Validate that we have a valid timestamp
|
||||||
|
if (isNaN(startTime)) {
|
||||||
|
console.error("Invalid start time:", startTimeStr);
|
||||||
|
return "00:00:00";
|
||||||
|
}
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const elapsed = Math.floor((now - startTime) / 1000);
|
const elapsed = Math.floor((now - startTime) / 1000);
|
||||||
|
|
||||||
// Handle negative time (shouldn't happen in normal usage)
|
// Handle negative time (shouldn't happen in normal usage)
|
||||||
if (elapsed < 0) return "00:00:00";
|
if (elapsed < 0) {
|
||||||
|
console.warn("Negative elapsed time detected:", elapsed);
|
||||||
|
return "00:00:00";
|
||||||
|
}
|
||||||
|
|
||||||
const hours = Math.floor(elapsed / 3600)
|
const hours = Math.floor(elapsed / 3600)
|
||||||
.toString()
|
.toString()
|
||||||
@@ -91,6 +131,48 @@ export const formatElapsedTime = (startTimeStr) => {
|
|||||||
.padStart(2, "0");
|
.padStart(2, "0");
|
||||||
|
|
||||||
return `${hours}:${minutes}:${seconds}`;
|
return `${hours}:${minutes}:${seconds}`;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error formatting elapsed time:", error);
|
||||||
|
return "00:00:00";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Function to fetch current timer state from server and update local storage
|
||||||
|
export const syncTimerWithServer = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/hunt/timer", {
|
||||||
|
credentials: "include",
|
||||||
|
headers: {
|
||||||
|
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||||
|
Pragma: "no-cache",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
console.error("Server responded with status:", response.status);
|
||||||
|
return { success: false, error: `Server error: ${response.status}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.active && data.startTime) {
|
||||||
|
setHuntTimer(data.startTime, data.endTime);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
startTime: data.startTime,
|
||||||
|
endTime: data.endTime,
|
||||||
|
active: data.active,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
clearHuntTimer();
|
||||||
|
return { success: true, data: null };
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error syncing timer with server:", error);
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Hook function to use in components to get formatted elapsed time
|
// Hook function to use in components to get formatted elapsed time
|
||||||
|
|||||||
Reference in new issue
Block a user