Added settings for user data deletion

This commit is contained in:
Brian McGonagill 2026-03-21 12:23:20 -05:00
parent 59e15cfde8
commit f49490042a
35 changed files with 2758 additions and 499 deletions

View file

@ -32,6 +32,7 @@ function closeNav() {
<ul v-if="authStore.isLoggedIn">
<li><RouterLink to="/dashboard" @click="closeNav">Dashboard</RouterLink></li>
<li><RouterLink to="/settings" @click="closeNav">Settings</RouterLink></li>
</ul>
<ul class="nav-actions">
@ -61,6 +62,7 @@ function closeNav() {
<li><RouterLink to="/" @click="closeNav">Home</RouterLink></li>
<template v-if="authStore.isLoggedIn">
<li><RouterLink to="/dashboard" @click="closeNav">Dashboard</RouterLink></li>
<li><RouterLink to="/settings" @click="closeNav">Settings</RouterLink></li>
<li><button @click="authStore.logout(); closeNav()" class="secondary">Logout</button></li>
</template>
<template v-else>

View file

@ -11,6 +11,7 @@ const name = ref('');
const description = ref('');
const prizeDetails = ref('');
const visibility = ref<'PUBLIC' | 'PRIVATE'>('PUBLIC');
const randomizeRoutes = ref(false);
const startDate = ref('');
const locationLat = ref<number | null>(null);
const locationLng = ref<number | null>(null);
@ -80,7 +81,8 @@ async function handleSubmit() {
locationLat: locationLat.value || undefined,
locationLng: locationLng.value || undefined,
searchRadius: searchRadius.value,
rules: filteredRules.length > 0 ? filteredRules : undefined
rules: filteredRules.length > 0 ? filteredRules : undefined,
randomizeRoutes: randomizeRoutes.value
});
router.push(`/games/${response.data.id}/edit`);
@ -127,6 +129,12 @@ onUnmounted(() => {
<option value="PUBLIC">Public</option>
<option value="PRIVATE">Private (Invite Only)</option>
</select>
<label for="randomizeRoutes">
<input id="randomizeRoutes" v-model="randomizeRoutes" type="checkbox" role="switch" />
Randomize Team Routes
</label>
<p><small>When enabled, teams will be randomly assigned routes when the game starts</small></p>
<label for="startDate">Start Date & Time</label>
<input id="startDate" v-model="startDate" type="datetime-local" />
@ -154,7 +162,7 @@ onUnmounted(() => {
<h2>Game Rules</h2>
<p><small>Add rules for participants to follow during the game</small></p>
<div v-for="(rule, index) in rules" :key="index" class="grid" style="grid-template-columns: 1fr auto;">
<div v-for="(_, index) in rules" :key="index" class="grid" style="grid-template-columns: 1fr auto;">
<label :for="`rule-${index}`">
Rule {{ index + 1 }}
<input

View file

@ -1,11 +1,9 @@
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { RouterLink } from 'vue-router';
import { useAuthStore } from '../stores/auth';
import type { Game } from '../types';
import { gameService } from '../services/api';
const authStore = useAuthStore();
const games = ref<Game[]>([]);
const loading = ref(false);
const showArchived = ref(false);
@ -88,7 +86,7 @@ onMounted(() => {
<footer>
<small>
<span :class="['status', game.status.toLowerCase()]">{{ game.status }}</span>
· {{ game._count?.legs || 0 }} legs
· {{ game._count?.routes || 0 }} routes
· {{ game._count?.teams || 0 }} teams
</small>
</footer>

View file

@ -1,24 +1,41 @@
<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import type { Game, Leg } from '../types';
import { gameService, legService } from '../services/api';
import type { Game, Route } from '../types';
import { gameService, routeService } from '../services/api';
const route = useRoute();
const router = useRouter();
const game = ref<Game | null>(null);
const legs = ref<Leg[]>([]);
const routes = ref<Route[]>([]);
const selectedRouteId = ref<string | null>(null);
const loading = ref(true);
const saving = ref(false);
const gameId = computed(() => route.params.id as string);
const selectedRoute = computed(() =>
routes.value.find(r => r.id === selectedRouteId.value) || null
);
const mapContainer = ref<HTMLDivElement | null>(null);
let map: L.Map | null = null;
let markers: L.Marker[] = [];
let routeMarkers: { [routeId: string]: L.Marker[] } = {};
let mapInitialized = false;
const newRoute = ref({
name: '',
description: '',
color: '#3498db'
});
const editRoute = ref({
name: '',
description: '',
color: ''
});
const newLeg = ref({
description: '',
@ -29,12 +46,52 @@ const newLeg = ref({
timeLimit: 30
});
function startEditRoute() {
if (selectedRoute.value) {
editRoute.value = {
name: selectedRoute.value.name,
description: selectedRoute.value.description || '',
color: selectedRoute.value.color
};
}
}
async function saveRoute() {
if (!selectedRouteId.value) return;
saving.value = true;
try {
const response = await routeService.update(selectedRouteId.value, {
name: editRoute.value.name,
description: editRoute.value.description || undefined,
color: editRoute.value.color
});
const idx = routes.value.findIndex(r => r.id === selectedRouteId.value);
if (idx >= 0) {
routes.value[idx].name = response.data.name;
routes.value[idx].description = response.data.description;
routes.value[idx].color = response.data.color;
}
updateMapMarkers();
} catch (err) {
alert('Failed to update route');
} finally {
saving.value = false;
}
}
async function loadGame() {
loading.value = true;
try {
const response = await gameService.get(gameId.value);
game.value = response.data;
legs.value = response.data.legs || [];
routes.value = response.data.routes || [];
if (routes.value.length > 0 && !selectedRouteId.value) {
selectedRouteId.value = routes.value[0].id;
}
} catch (err) {
console.error('Failed to load game:', err);
} finally {
@ -43,7 +100,7 @@ async function loadGame() {
}
function initMap() {
if (!mapContainer.value) return;
if (!mapContainer.value || map) return;
const center = game.value?.locationLat && game.value?.locationLng
? [game.value.locationLat, game.value.locationLng] as [number, number]
@ -64,30 +121,109 @@ function initMap() {
}).addTo(map);
}
legs.value.forEach((leg, index) => {
if (leg.locationLat && leg.locationLng) {
const marker = L.marker([leg.locationLat, leg.locationLng])
.addTo(map!)
.bindPopup(`Leg ${index + 1}`);
markers.push(marker);
}
});
map.on('click', (e: L.LeafletMouseEvent) => {
newLeg.value.locationLat = e.latlng.lat;
newLeg.value.locationLng = e.latlng.lng;
});
updateMapMarkers();
}
function updateMapMarkers() {
if (!map) return;
Object.values(routeMarkers).forEach(markers => {
markers.forEach(m => m.remove());
});
routeMarkers = {};
routes.value.forEach((route) => {
const color = route.color || '#3498db';
routeMarkers[route.id] = [];
route.routeLegs?.forEach((leg, legIndex) => {
if (leg.locationLat && leg.locationLng) {
const marker = L.marker([leg.locationLat, leg.locationLng], {
icon: L.divIcon({
className: `route-marker-${route.id}`,
html: `<div style="background: ${color}; width: 20px; height: 20px; border-radius: 50%; border: 2px solid white; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 12px;">${legIndex + 1}</div>`,
iconSize: [20, 20]
})
})
.addTo(map!)
.bindPopup(`${route.name} - Leg ${legIndex + 1}`);
routeMarkers[route.id].push(marker);
}
});
});
setTimeout(() => map?.invalidateSize(), 100);
}
async function createRoute() {
if (!newRoute.value.name.trim()) {
alert('Please enter a route name');
return;
}
saving.value = true;
try {
const response = await routeService.create({
gameId: gameId.value,
name: newRoute.value.name,
description: newRoute.value.description || undefined,
color: newRoute.value.color
});
routes.value.push(response.data);
selectedRouteId.value = response.data.id;
newRoute.value = { name: '', description: '', color: '#3498db' };
updateMapMarkers();
} catch (err) {
alert('Failed to create route');
} finally {
saving.value = false;
}
}
async function copyRoute(routeId: string) {
try {
const response = await routeService.copy(routeId);
routes.value.push(response.data);
selectedRouteId.value = response.data.id;
updateMapMarkers();
} catch (err) {
alert('Failed to copy route');
}
}
async function deleteRoute(routeId: string) {
if (!confirm('Are you sure you want to delete this route and all its legs?')) return;
try {
await routeService.delete(routeId);
routes.value = routes.value.filter(r => r.id !== routeId);
if (selectedRouteId.value === routeId) {
selectedRouteId.value = routes.value[0]?.id || null;
}
updateMapMarkers();
} catch (err) {
alert('Failed to delete route');
}
}
async function addLeg() {
if (!newLeg.value.description) {
if (!selectedRouteId.value || !newLeg.value.description) {
alert('Please enter a description');
return;
}
saving.value = true;
try {
const response = await legService.create(gameId.value, {
const response = await routeService.addLeg(selectedRouteId.value, {
description: newLeg.value.description,
conditionType: newLeg.value.conditionType,
conditionDetails: newLeg.value.conditionDetails || undefined,
@ -96,7 +232,11 @@ async function addLeg() {
timeLimit: newLeg.value.timeLimit
});
legs.value.push(response.data);
const route = routes.value.find(r => r.id === selectedRouteId.value);
if (route) {
if (!route.routeLegs) route.routeLegs = [];
route.routeLegs.push(response.data);
}
newLeg.value = {
description: '',
@ -107,18 +247,7 @@ async function addLeg() {
timeLimit: 30
};
if (map) {
markers.forEach(m => m.remove());
markers = [];
legs.value.forEach((leg, index) => {
if (leg.locationLat && leg.locationLng) {
const marker = L.marker([leg.locationLat, leg.locationLng])
.addTo(map!)
.bindPopup(`Leg ${index + 1}`);
markers.push(marker);
}
});
}
updateMapMarkers();
} catch (err) {
alert('Failed to add leg');
} finally {
@ -130,8 +259,14 @@ async function deleteLeg(legId: string) {
if (!confirm('Are you sure you want to delete this leg?')) return;
try {
await legService.delete(legId);
legs.value = legs.value.filter(l => l.id !== legId);
await routeService.deleteLeg(selectedRouteId.value!, legId);
const route = routes.value.find(r => r.id === selectedRouteId.value);
if (route && route.routeLegs) {
route.routeLegs = route.routeLegs.filter(l => l.id !== legId);
}
updateMapMarkers();
} catch (err) {
alert('Failed to delete leg');
}
@ -148,14 +283,14 @@ function calculateDistance(lat1: number, lon1: number, lat2: number, lon2: numbe
return R * c;
}
function getTotalDistance(): number {
if (!game.value?.locationLat || !game.value?.locationLng || legs.value.length === 0) return 0;
function getRouteDistance(route: Route): number {
if (!game.value?.locationLat || !game.value?.locationLng || !route.routeLegs?.length) return 0;
let total = 0;
let prevLat = game.value.locationLat;
let prevLng = game.value.locationLng;
for (const leg of legs.value) {
for (const leg of route.routeLegs) {
if (leg.locationLat && leg.locationLng) {
total += calculateDistance(prevLat, prevLng, leg.locationLat, leg.locationLng);
prevLat = leg.locationLat;
@ -166,9 +301,35 @@ function getTotalDistance(): number {
return total;
}
function getTotalLegs(): number {
return routes.value.reduce((sum, r) => sum + (r.routeLegs?.length || 0), 0);
}
watch(selectedRouteId, async (newId) => {
if (newId) {
startEditRoute();
if (!mapInitialized) {
await nextTick();
if (mapContainer.value) {
initMap();
mapInitialized = true;
}
} else {
updateMapMarkers();
}
}
});
onMounted(() => {
loadGame().then(() => {
setTimeout(initMap, 100);
if (selectedRouteId.value) {
setTimeout(() => {
if (mapContainer.value && !mapInitialized) {
initMap();
mapInitialized = true;
}
}, 100);
}
});
});
@ -192,31 +353,113 @@ onUnmounted(() => {
<div class="grid">
<article>
<h2>Legs ({{ legs.length }})</h2>
<p><small>Total route distance: {{ getTotalDistance().toFixed(2) }} km</small></p>
<h2>Routes ({{ routes.length }})</h2>
<p><small>Total legs: {{ getTotalLegs() }}</small></p>
<article v-if="legs.length" v-for="(leg, index) in legs" :key="leg.id">
<div v-for="routeItem in routes" :key="routeItem.id"
class="route-card"
:class="{ selected: selectedRouteId === routeItem.id }"
@click="selectedRouteId = routeItem.id">
<div class="route-header">
<svg width="16" height="18" viewBox="0 0 16 18" :style="{ flexShrink: 0 }">
<path d="M0 0h16v10c0 4-4 6-8 8-4-2-8-4-8-8V0z" :fill="routeItem.color" stroke="white" stroke-width="1"/>
</svg>
<h3>{{ routeItem.name }}</h3>
<div class="route-actions">
<button @click.stop="copyRoute(routeItem.id)" class="secondary outline">Copy</button>
<button @click.stop="deleteRoute(routeItem.id)" class="contrast outline">Delete</button>
</div>
</div>
<p v-if="routeItem.description">{{ routeItem.description }}</p>
<footer>
<small>
{{ routeItem.routeLegs?.length || 0 }} legs
· {{ getRouteDistance(routeItem).toFixed(2) }} km
</small>
</footer>
</div>
<details class="add-route" open>
<summary>Add New Route</summary>
<form @submit.prevent="createRoute">
<label>
Route Name
<input v-model="newRoute.name" type="text" placeholder="e.g., Route A" required />
</label>
<label>
Description (optional)
<input v-model="newRoute.description" type="text" placeholder="e.g., Via downtown" />
</label>
<label class="color-label">
Color
<div style="display: flex; align-items: center; gap: 0.5rem;">
<input v-model="newRoute.color" type="color" style="width: 40px; height: 40px; padding: 2px;" />
<span :style="{ color: newRoute.color, fontWeight: 'bold' }">{{ newRoute.color }}</span>
</div>
</label>
<button type="submit" :disabled="saving">
{{ saving ? 'Creating...' : 'Create Route' }}
</button>
</form>
</details>
</article>
<article v-if="selectedRoute">
<div class="route-header">
<svg width="20" height="22" viewBox="0 0 16 18" :style="{ flexShrink: 0 }">
<path d="M0 0h16v10c0 4-4 6-8 8-4-2-8-4-8-8V0z" :fill="selectedRoute.color" stroke="white" stroke-width="1"/>
</svg>
<h2>{{ selectedRoute.name }}</h2>
<select v-model="selectedRouteId" style="max-width: 200px;">
<option v-for="r in routes" :key="r.id" :value="r.id">
{{ r.name }}
</option>
</select>
</div>
<details>
<summary>Edit Route</summary>
<form @submit.prevent="saveRoute">
<label>
Route Name
<input v-model="editRoute.name" type="text" required />
</label>
<label>
Description
<input v-model="editRoute.description" type="text" />
</label>
<label class="color-label">
Color
<div style="display: flex; align-items: center; gap: 0.5rem;">
<input v-model="editRoute.color" type="color" style="width: 40px; height: 40px; padding: 2px;" />
<span :style="{ color: editRoute.color, fontWeight: 'bold' }">{{ editRoute.color }}</span>
</div>
</label>
<button type="submit" :disabled="saving">
{{ saving ? 'Saving...' : 'Save Changes' }}
</button>
</form>
</details>
<div v-if="selectedRoute.routeLegs?.length" v-for="(leg, index) in selectedRoute.routeLegs" :key="leg.id" class="leg-card">
<div class="leg-header">
<h3>Leg {{ index + 1 }}</h3>
<button @click="deleteLeg(leg.id)" class="secondary">Delete</button>
<button @click="deleteLeg(leg.id)" class="secondary outline">Delete</button>
</div>
<p>{{ leg.description }}</p>
<footer>
<small>
Type: {{ leg.conditionType }}
{{ leg.conditionType }}
<span v-if="leg.timeLimit"> · {{ leg.timeLimit }} min</span>
<span v-if="leg.locationLat && leg.locationLng">
· {{ leg.locationLat.toFixed(4) }}, {{ leg.locationLng.toFixed(4) }}
</span>
</small>
</footer>
</article>
<p v-else>No legs added yet</p>
</article>
</div>
<p v-else>No legs in this route yet.</p>
<article>
<h2>Add New Leg</h2>
<h3>Add Leg</h3>
<div ref="mapContainer" class="map-container"></div>
<p><small>Click on map to set location</small></p>
@ -256,6 +499,10 @@ onUnmounted(() => {
</button>
</form>
</article>
<article v-else>
<p>Select a route or create a new one to start adding legs.</p>
</article>
</div>
</template>
</main>
@ -268,14 +515,56 @@ onUnmounted(() => {
margin-bottom: 0.5rem;
}
.leg-header {
.route-card, .leg-card {
margin-bottom: 1rem;
cursor: pointer;
}
.route-card.selected {
border-color: var(--pico-primary-focus);
}
.route-header, .leg-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
gap: 1rem;
}
.leg-header h3 {
.route-header h3, .leg-header h3 {
margin: 0;
}
.route-actions {
display: flex;
gap: 0.5rem;
}
.add-route {
margin-top: 1rem;
}
.add-route summary {
cursor: pointer;
padding: 0.5rem;
background: var(--pico-muted-border-color);
border-radius: var(--pico-border-radius);
}
.add-route form {
padding-top: 1rem;
}
input[type="color"] {
width: 100%;
height: 40px;
padding: 2px;
border-radius: var(--pico-border-radius);
cursor: pointer;
}
.color-label {
display: flex;
flex-direction: column;
}
</style>

View file

@ -5,14 +5,15 @@ import { io, Socket } from 'socket.io-client';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { useAuthStore } from '../stores/auth';
import type { Game, Team, ChatMessage } from '../types';
import { gameService, teamService } from '../services/api';
import type { Game, Team, ChatMessage, Route } from '../types';
import { gameService, teamService, routeService } from '../services/api';
const route = useRoute();
const authStore = useAuthStore();
const game = ref<Game | null>(null);
const teams = ref<Team[]>([]);
const routes = ref<Route[]>([]);
const chatMessages = ref<ChatMessage[]>([]);
const loading = ref(true);
@ -28,12 +29,14 @@ const selectedTeam = ref<Team | null>(null);
async function loadGame() {
loading.value = true;
try {
const [gameRes, teamsRes] = await Promise.all([
const [gameRes, teamsRes, routesRes] = await Promise.all([
gameService.get(gameId.value),
teamService.getByGame(gameId.value)
teamService.getByGame(gameId.value),
routeService.getByGame(gameId.value)
]);
game.value = gameRes.data;
teams.value = teamsRes.data;
routes.value = routesRes.data;
} catch (err) {
console.error('Failed to load game:', err);
} finally {
@ -57,9 +60,35 @@ function initMap() {
fillOpacity: 0.1
}).addTo(map);
routes.value.forEach((route) => {
const color = route.color || '#3498db';
route.routeLegs?.forEach((leg, legIndex) => {
if (leg.locationLat && leg.locationLng) {
const legIcon = L.divIcon({
className: 'route-leg-marker',
html: `<div style="background:${color}; width:24px; height:24px; border-radius:50%; border:2px solid white; display:flex; align-items:center; justify-content:center; color:white; font-weight:bold; font-size:12px;">${legIndex + 1}</div>`,
iconSize: [24, 24],
iconAnchor: [12, 12]
});
L.marker([leg.locationLat, leg.locationLng], { icon: legIcon })
.addTo(map!)
.bindPopup(`${route.name} - Leg ${legIndex + 1}: ${leg.description}`);
}
});
});
teams.value.forEach(team => {
if (team.lat && team.lng) {
const marker = L.marker([team.lat, team.lng])
const teamRoute = team.teamRoutes?.[0];
const teamRouteData = routes.value.find(r => r.id === teamRoute?.routeId);
const color = teamRouteData?.color || '#666';
const teamIcon = L.divIcon({
className: 'team-marker',
html: `<div style="background:${color}; width:20px; height:20px; border-radius:50%; border:2px solid white; box-shadow:0 2px 4px rgba(0,0,0,0.3);"></div>`,
iconSize: [20, 20],
iconAnchor: [10, 10]
});
const marker = L.marker([team.lat, team.lng], { icon: teamIcon })
.addTo(map!)
.bindPopup(team.name);
teamMarkers[team.id] = marker;
@ -196,7 +225,8 @@ onUnmounted(() => {
<footer>
<small>
{{ team.members?.length || 0 }} members ·
Leg {{ game.legs?.findIndex(l => l.id === team.currentLegId) + 1 || 0 }} / {{ game.legs?.length || 0 }}
Route: {{ team.teamRoutes?.[0]?.route?.name || 'Not assigned' }} ·
Leg {{ team.currentLegIndex + 1 }}
<span v-if="team.totalTimeDeduction"> · -{{ team.totalTimeDeduction }}s</span>
</small>
</footer>

View file

@ -155,26 +155,13 @@ onMounted(() => {
</ul>
</section>
<section v-if="game.legs?.length">
<h2>Legs ({{ game.legs.length }})</h2>
<table>
<thead>
<tr>
<th>#</th>
<th>Description</th>
<th>Type</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr v-for="leg in game.legs" :key="leg.id">
<td>{{ leg.sequenceNumber }}</td>
<td>{{ leg.description }}</td>
<td>{{ leg.conditionType }}</td>
<td>{{ leg.timeLimit ? `${leg.timeLimit} min` : '-' }}</td>
</tr>
</tbody>
</table>
<section v-if="game.routes?.length">
<h2>Routes ({{ game.routes.length }})</h2>
<div v-for="route in game.routes" :key="route.id" class="route-info">
<h3>{{ route.name }}</h3>
<p v-if="route.description">{{ route.description }}</p>
<p><small>{{ route.routeLegs?.length || 0 }} legs</small></p>
</div>
</section>
<section v-if="game.teams?.length">
@ -183,6 +170,7 @@ onMounted(() => {
<thead>
<tr>
<th>Name</th>
<th>Route</th>
<th>Status</th>
<th>Members</th>
</tr>
@ -190,6 +178,7 @@ onMounted(() => {
<tbody>
<tr v-for="team in game.teams" :key="team.id">
<td>{{ team.name }}</td>
<td>{{ team.teamRoutes?.[0]?.route?.name || 'Not assigned' }}</td>
<td><span :class="['status', team.status.toLowerCase()]">{{ team.status }}</span></td>
<td>{{ team.members?.length || 0 }}</td>
</tr>

View file

@ -68,7 +68,7 @@ onMounted(() => {
<h3>{{ game.name }}</h3>
<p v-if="game.description">{{ game.description.slice(0, 100) }}...</p>
<footer>
<small>{{ game._count?.legs || 0 }} legs · {{ game._count?.teams || 0 }} teams</small>
<small>{{ game._count?.routes || 0 }} routes · {{ game._count?.teams || 0 }} teams</small>
<small v-if="game.startDate">{{ new Date(game.startDate).toLocaleDateString() }}</small>
</footer>
</RouterLink>

View file

@ -5,7 +5,7 @@ import { io, Socket } from 'socket.io-client';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { useAuthStore } from '../stores/auth';
import type { Game, Team, ChatMessage } from '../types';
import type { Game, Team, ChatMessage, Route, RouteLeg } from '../types';
import { teamService, uploadService } from '../services/api';
const route = useRoute();
@ -28,22 +28,27 @@ const showPhotoUpload = ref(false);
const photoFile = ref<File | null>(null);
const uploading = ref(false);
const currentLegIndex = computed(() => {
if (!team.value?.currentLegId || !game.value?.legs) return -1;
return game.value.legs.findIndex(l => l.id === team.value!.currentLegId);
const currentRoute = computed<Route | null>(() => {
return team.value?.teamRoutes?.[0]?.route || null;
});
const currentLeg = computed(() => {
if (currentLegIndex.value < 0 || !game.value?.legs) return null;
return game.value.legs[currentLegIndex.value];
const currentLegIndex = computed(() => team.value?.currentLegIndex ?? -1);
const currentLeg = computed<RouteLeg | null>(() => {
if (currentRoute.value && currentLegIndex.value >= 0) {
return currentRoute.value.routeLegs?.[currentLegIndex.value] || null;
}
return null;
});
const totalLegs = computed(() => currentRoute.value?.routeLegs?.length || 0);
async function loadTeam() {
loading.value = true;
try {
const response = await teamService.get(gameId.value);
team.value = response.data;
game.value = response.data.game;
game.value = response.data.game || null;
if (team.value?.lat && team.value?.lng && map) {
teamMarker = L.marker([team.value.lat, team.value.lng]).addTo(map);
@ -166,7 +171,7 @@ async function submitPhoto() {
uploading.value = true;
try {
const uploadRes = await uploadService.upload(photoFile.value);
await fetch(`http://localhost:3001/api/legs/${currentLeg.value.id}/photo`, {
await fetch(`http://localhost:3001/api/routes/${currentRoute.value?.id}/legs/${currentLeg.value.id}/photo`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -191,14 +196,6 @@ async function submitPhoto() {
function handleVisibilityChange() {
if (document.hidden) {
alert('Warning: Leaving the game tab may result in time penalties!');
if (game.value?.timeDeductionPenalty && socket) {
socket.emit('chat-message', {
gameId: gameId.value,
message: `Warning: ${authStore.user?.name} navigated away from the game`,
userId: authStore.user?.id || '',
userName: authStore.user?.name || ''
});
}
}
}
@ -237,6 +234,7 @@ onUnmounted(() => {
<p>{{ currentLeg.description }}</p>
<footer>
<small>
Route: {{ currentRoute?.name }} ·
Type: {{ currentLeg.conditionType }}
<span v-if="currentLeg.timeLimit"> · Time limit: {{ currentLeg.timeLimit }} min</span>
</small>
@ -251,6 +249,7 @@ onUnmounted(() => {
<article v-else>
<p v-if="team.status === 'FINISHED'">🎉 Congratulations! You've completed the hunt!</p>
<p v-else-if="!currentRoute">Waiting for route assignment...</p>
<p v-else>Waiting for the game to start...</p>
</article>
@ -258,9 +257,9 @@ onUnmounted(() => {
<h3>Progress</h3>
<progress
:value="currentLegIndex + 1"
:max="game.legs?.length || 1"
:max="totalLegs || 1"
></progress>
<p><small>Leg {{ currentLegIndex + 1 }} of {{ game.legs?.length || 0 }}</small></p>
<p><small>Leg {{ currentLegIndex + 1 }} of {{ totalLegs }}</small></p>
<p v-if="team.totalTimeDeduction" class="error">
<small>Time penalty: {{ team.totalTimeDeduction }} seconds</small>
</p>

View file

@ -0,0 +1,477 @@
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../stores/auth';
import { userService, uploadService } from '../services/api';
import type { User, UserGameHistory, LocationHistory } from '../types';
const router = useRouter();
const authStore = useAuthStore();
const user = ref<User | null>(null);
const loading = ref(true);
const saving = ref(false);
const activeTab = ref<'profile' | 'locations' | 'games'>('profile');
const name = ref('');
const screenName = ref('');
const avatarUrl = ref('');
const avatarPreview = ref('');
const uploadingAvatar = ref(false);
const locationHistory = ref<{ totalLocations: number; byGame: { game: { id: string; name: string }; locations: LocationHistory[]; locationCount: number }[] }>({ totalLocations: 0, byGame: [] });
const gamesHistory = ref<UserGameHistory[]>([]);
async function loadProfile() {
loading.value = true;
try {
const response = await userService.getProfile();
user.value = response.data;
name.value = response.data.name || '';
screenName.value = response.data.screenName || '';
avatarUrl.value = response.data.avatarUrl || '';
avatarPreview.value = response.data.avatarUrl || '';
} catch (err) {
console.error('Failed to load profile:', err);
} finally {
loading.value = false;
}
}
async function loadLocationHistory() {
try {
const response = await userService.getLocationHistory();
locationHistory.value = response.data;
} catch (err) {
console.error('Failed to load location history:', err);
}
}
async function loadGamesHistory() {
try {
const response = await userService.getGamesHistory();
gamesHistory.value = response.data;
} catch (err) {
console.error('Failed to load games history:', err);
}
}
async function handleAvatarSelect(event: Event) {
const input = event.target as HTMLInputElement;
if (input.files?.[0]) {
uploadingAvatar.value = true;
try {
const uploadRes = await uploadService.upload(input.files[0]);
avatarUrl.value = uploadRes.data.url;
avatarPreview.value = uploadRes.data.url;
} catch (err) {
alert('Failed to upload avatar');
} finally {
uploadingAvatar.value = false;
}
}
}
async function saveProfile() {
saving.value = true;
try {
const response = await userService.updateProfile({
name: name.value,
screenName: screenName.value || undefined,
avatarUrl: avatarUrl.value || undefined
});
user.value = response.data;
authStore.user = response.data;
alert('Profile updated successfully!');
} catch (err) {
alert('Failed to update profile');
} finally {
saving.value = false;
}
}
async function deleteLocationData() {
if (!confirm('Are you sure you want to delete all your location data? This cannot be undone.')) return;
try {
await userService.deleteLocationData();
alert('Location data deleted.');
loadLocationHistory();
} catch (err) {
alert('Failed to delete location data');
}
}
async function deleteAccount() {
if (!confirm('Are you sure you want to delete your account? This will remove all your data and cannot be undone.')) return;
if (!confirm('This is your final warning. Type "DELETE" to confirm.')) return;
try {
await userService.deleteAccount();
authStore.logout();
router.push('/');
} catch (err) {
alert('Failed to delete account');
}
}
onMounted(() => {
loadProfile();
loadLocationHistory();
loadGamesHistory();
});
</script>
<template>
<main class="container">
<h1>Settings</h1>
<nav class="grid" style="grid-template-columns: auto 1fr 1fr 1fr; gap: 1rem;">
<button
@click="activeTab = 'profile'"
:class="{ '': activeTab !== 'profile', 'primary': activeTab === 'profile' }"
>
Profile
</button>
<button
@click="activeTab = 'locations'"
:class="{ '': activeTab !== 'locations', 'primary': activeTab === 'locations' }"
>
Location History
</button>
<button
@click="activeTab = 'games'"
:class="{ '': activeTab !== 'games', 'primary': activeTab === 'games' }"
>
My Games
</button>
</nav>
<article v-if="loading">Loading...</article>
<template v-else-if="user">
<article v-if="activeTab === 'profile'">
<h2>Profile Settings</h2>
<div class="grid" style="grid-template-columns: 200px 1fr;">
<div>
<div v-if="avatarPreview" class="avatar-preview">
<img :src="avatarPreview" alt="Avatar" />
</div>
<div v-else class="avatar-placeholder">
{{ user.name.charAt(0).toUpperCase() }}
</div>
<label class="upload-btn">
<input type="file" accept="image/*" @change="handleAvatarSelect" hidden :disabled="uploadingAvatar" />
{{ uploadingAvatar ? 'Uploading...' : 'Upload Avatar' }}
</label>
</div>
<div>
<label>
Display Name
<input v-model="name" type="text" placeholder="Your name" />
</label>
<label>
Screen Name (shown to other players)
<input v-model="screenName" type="text" placeholder="Optional alias" />
</label>
<button @click="saveProfile" :disabled="saving">
{{ saving ? 'Saving...' : 'Save Profile' }}
</button>
</div>
</div>
<hr />
<article class="danger-zone">
<h3>Danger Zone</h3>
<p><small>These actions are irreversible. Proceed with caution.</small></p>
<div class="danger-action">
<div>
<strong>Delete All Location Data</strong>
<p><small>Remove all your recorded location history from the server.</small></p>
</div>
<button @click="deleteLocationData" class="contrast">Delete Location Data</button>
</div>
<div class="danger-action">
<div>
<strong>Delete Account</strong>
<p><small>Permanently delete your account and all associated data.</small></p>
</div>
<button @click="deleteAccount" class="secondary" style="background: var(--pico-del-color); border-color: var(--pico-del-color);">Delete Account</button>
</div>
</article>
</article>
<article v-if="activeTab === 'locations'">
<h2>Location History</h2>
<p><small>Total recorded locations: {{ locationHistory.totalLocations }}</small></p>
<div v-if="locationHistory.byGame.length === 0">
<p>No location data recorded yet.</p>
</div>
<div v-for="gameData in locationHistory.byGame" :key="gameData.game.id" class="location-game">
<h3>{{ gameData.game.name }}</h3>
<p><small>{{ gameData.locationCount }} locations recorded</small></p>
<details>
<summary>View Locations</summary>
<table>
<thead>
<tr>
<th>Time</th>
<th>Latitude</th>
<th>Longitude</th>
<th>Accuracy</th>
</tr>
</thead>
<tbody>
<tr v-for="loc in gameData.locations" :key="loc.id">
<td>{{ new Date(loc.recordedAt).toLocaleString() }}</td>
<td>{{ loc.lat.toFixed(6) }}</td>
<td>{{ loc.lng.toFixed(6) }}</td>
<td>{{ loc.accuracy ? loc.accuracy.toFixed(0) + 'm' : 'N/A' }}</td>
</tr>
</tbody>
</table>
</details>
</div>
</article>
<article v-if="activeTab === 'games'">
<h2>My Game History</h2>
<div v-if="gamesHistory.length === 0">
<p>You haven't participated in any games yet.</p>
</div>
<div v-for="game in gamesHistory" :key="game.gameId + game.teamId" class="game-history-card">
<div class="game-history-header">
<div>
<h3>{{ game.gameName }}</h3>
<small>
<span :class="['status', game.gameStatus.toLowerCase()]">{{ game.gameStatus }}</span>
· Team: {{ game.teamName }}
<span v-if="game.routeName">
· Route:
<span class="route-badge" :style="{ backgroundColor: game.routeColor || '#3498db' }">
{{ game.routeName }}
</span>
</span>
</small>
</div>
</div>
<div class="game-stats">
<div class="stat">
<strong>{{ game.totalLegs }}</strong>
<small>Legs</small>
</div>
<div class="stat">
<strong>{{ game.totalDistance }} km</strong>
<small>Distance</small>
</div>
<div class="stat">
<strong>{{ game.proofLocations.filter(p => p.hasPhotoProof).length }}</strong>
<small>Photo Proofs</small>
</div>
</div>
<details v-if="game.proofLocations.length > 0">
<summary>Proof Locations ({{ game.proofLocations.filter(p => p.hasPhotoProof).length }}/{{ game.proofLocations.length }})</summary>
<div class="proof-locations">
<div
v-for="loc in game.proofLocations"
:key="loc.legNumber"
class="proof-location"
:class="{ 'has-proof': loc.hasPhotoProof }"
>
<span class="leg-number">{{ loc.legNumber }}</span>
<span class="leg-desc">{{ loc.description }}</span>
<span v-if="loc.hasPhotoProof" class="proof-badge">Photo</span>
<span v-else class="no-proof">No proof</span>
</div>
</div>
</details>
</div>
</article>
</template>
</main>
</template>
<style scoped>
.avatar-preview {
width: 150px;
height: 150px;
border-radius: 50%;
overflow: hidden;
margin-bottom: 1rem;
}
.avatar-preview img {
width: 100%;
height: 100%;
object-fit: cover;
}
.avatar-placeholder {
width: 150px;
height: 150px;
border-radius: 50%;
background: var(--pico-primary-background-color);
color: var(--pico-primary-inverse);
display: flex;
align-items: center;
justify-content: center;
font-size: 4rem;
font-weight: bold;
margin-bottom: 1rem;
}
.upload-btn {
display: inline-block;
padding: 0.5rem 1rem;
background: var(--pico-secondary-background-color);
border: var(--pico-border-width) solid var(--pico-secondary-border-color);
border-radius: var(--pico-border-radius);
cursor: pointer;
text-align: center;
width: 100%;
}
.upload-btn:hover {
background: var(--pico-secondary-hover-background-color);
}
.danger-zone {
border-color: var(--pico-del-color);
background: var(--pico-del-background-color);
}
.danger-zone h3 {
color: var(--pico-del-color);
}
.danger-action {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 0;
border-top: 1px solid var(--pico-del-color);
}
.location-game {
margin-bottom: 2rem;
padding: 1rem;
border: 1px solid var(--pico-muted-border-color);
border-radius: var(--pico-border-radius);
}
.game-history-card {
margin-bottom: 1.5rem;
padding: 1rem;
border: 1px solid var(--pico-muted-border-color);
border-radius: var(--pico-border-radius);
}
.game-history-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 1rem;
}
.game-stats {
display: flex;
gap: 2rem;
margin-bottom: 1rem;
}
.stat {
text-align: center;
}
.stat strong {
display: block;
font-size: 1.5rem;
}
.stat small {
color: var(--pico-muted-color);
}
.status {
padding: 0.2rem 0.5rem;
border-radius: 4px;
font-size: 0.75rem;
}
.status.live { background: var(--pico-ins-background-color); }
.status.ended { background: var(--pico-muted-color); color: white; }
.status.archived { background: var(--pico-muted-border-color); }
.status.draft { background: var(--pico-mark-background-color); }
.route-badge {
display: inline-block;
padding: 0.1rem 0.4rem;
border-radius: 4px;
color: white;
font-size: 0.7rem;
}
.proof-locations {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.proof-location {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
background: var(--pico-muted-border-color);
border-radius: var(--pico-border-radius);
}
.proof-location.has-proof {
background: var(--pico-ins-background-color);
}
.leg-number {
width: 24px;
height: 24px;
border-radius: 50%;
background: var(--pico-primary-background-color);
color: white;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.75rem;
flex-shrink: 0;
}
.leg-desc {
flex: 1;
font-size: 0.9rem;
}
.proof-badge {
padding: 0.1rem 0.4rem;
background: var(--pico-ins-color);
color: white;
border-radius: 4px;
font-size: 0.7rem;
}
.no-proof {
color: var(--pico-muted-color);
font-size: 0.7rem;
}
</style>

View file

@ -4,13 +4,14 @@ import { useRoute } from 'vue-router';
import { io, Socket } from 'socket.io-client';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import type { Game, Team } from '../types';
import { gameService, teamService } from '../services/api';
import type { Game, Team, Route } from '../types';
import { gameService, teamService, routeService } from '../services/api';
const route = useRoute();
const game = ref<Game | null>(null);
const teams = ref<Team[]>([]);
const routes = ref<Route[]>([]);
const loading = ref(true);
const gameId = computed(() => route.params.id as string);
@ -23,9 +24,9 @@ const leaderboard = computed(() => {
return [...teams.value]
.filter(t => t.status === 'ACTIVE' || t.status === 'FINISHED')
.sort((a, b) => {
const aLegIndex = game.value?.legs?.findIndex(l => l.id === a.currentLegId) || 0;
const bLegIndex = game.value?.legs?.findIndex(l => l.id === b.currentLegId) || 0;
if (aLegIndex !== bLegIndex) return bLegIndex - aLegIndex;
if (a.status === 'FINISHED' && b.status !== 'FINISHED') return -1;
if (b.status === 'FINISHED' && a.status !== 'FINISHED') return 1;
if (a.currentLegIndex !== b.currentLegIndex) return b.currentLegIndex - a.currentLegIndex;
return a.totalTimeDeduction - b.totalTimeDeduction;
});
});
@ -33,12 +34,14 @@ const leaderboard = computed(() => {
async function loadGame() {
loading.value = true;
try {
const [gameRes, teamsRes] = await Promise.all([
const [gameRes, teamsRes, routesRes] = await Promise.all([
gameService.get(gameId.value),
teamService.getByGame(gameId.value)
teamService.getByGame(gameId.value),
routeService.getByGame(gameId.value)
]);
game.value = gameRes.data;
teams.value = teamsRes.data;
routes.value = routesRes.data;
} catch (err) {
console.error('Failed to load game:', err);
} finally {
@ -62,9 +65,35 @@ function initMap() {
fillOpacity: 0.1
}).addTo(map);
routes.value.forEach((route) => {
const color = route.color || '#3498db';
route.routeLegs?.forEach((leg, legIndex) => {
if (leg.locationLat && leg.locationLng) {
const legIcon = L.divIcon({
className: 'route-leg-marker',
html: `<div style="background:${color}; width:20px; height:20px; border-radius:50%; border:2px solid white; display:flex; align-items:center; justify-content:center; color:white; font-weight:bold; font-size:10px;">${legIndex + 1}</div>`,
iconSize: [20, 20],
iconAnchor: [10, 10]
});
L.marker([leg.locationLat, leg.locationLng], { icon: legIcon })
.addTo(map!)
.bindPopup(`${route.name} - Leg ${legIndex + 1}`);
}
});
});
teams.value.forEach(team => {
if (team.lat && team.lng) {
const marker = L.marker([team.lat, team.lng])
const teamRoute = team.teamRoutes?.[0];
const teamRouteData = routes.value.find(r => r.id === teamRoute?.routeId);
const color = teamRouteData?.color || '#666';
const teamIcon = L.divIcon({
className: 'team-marker',
html: `<div style="background:${color}; width:16px; height:16px; border-radius:50%; border:2px solid white; box-shadow:0 2px 4px rgba(0,0,0,0.3);"></div>`,
iconSize: [16, 16],
iconAnchor: [8, 8]
});
const marker = L.marker([team.lat, team.lng], { icon: teamIcon })
.addTo(map!)
.bindPopup(team.name);
teamMarkers[team.id] = marker;
@ -145,7 +174,8 @@ onUnmounted(() => {
</div>
<footer>
<small>
Leg {{ game.legs?.findIndex(l => l.id === team.currentLegId) + 1 || 0 }}/{{ game.legs?.length || 0 }}
{{ team.teamRoutes?.[0]?.route?.name || 'No route' }} ·
Leg {{ team.currentLegIndex + 1 }}
<span v-if="team.totalTimeDeduction" class="error"> · -{{ team.totalTimeDeduction }}s</span>
</small>
</footer>

View file

@ -67,6 +67,12 @@ const router = createRouter({
name: 'invite',
component: () => import('../pages/InvitePage.vue'),
},
{
path: '/settings',
name: 'settings',
component: () => import('../pages/SettingsPage.vue'),
meta: { requiresAuth: true },
},
],
});

View file

@ -1,5 +1,5 @@
import axios from 'axios';
import type { Game, Leg, Team, User, AuthResponse } from '../types';
import type { Game, Route, RouteLeg, Team, User, AuthResponse, LocationHistory, UserGameHistory } from '../types';
const api = axios.create({
baseURL: 'http://localhost:3001/api',
@ -37,13 +37,21 @@ export const gameService = {
getInvite: (id: string) => api.get<{ inviteCode: string }>(`/games/${id}/invite`),
};
export const legService = {
getByGame: (gameId: string) => api.get<Leg[]>(`/legs/game/${gameId}`),
create: (gameId: string, data: Partial<Leg>) => api.post<Leg>(`/legs/game/${gameId}`, data),
update: (legId: string, data: Partial<Leg>) => api.put<Leg>(`/legs/${legId}`, data),
delete: (legId: string) => api.delete(`/legs/${legId}`),
submitPhoto: (legId: string, data: { teamId: string; photoUrl: string }) =>
api.post(`/legs/${legId}/photo`, data),
export const routeService = {
getByGame: (gameId: string) => api.get<Route[]>(`/routes/game/${gameId}`),
get: (routeId: string) => api.get<Route>(`/routes/${routeId}`),
create: (data: { gameId: string; name: string; description?: string; color?: string }) =>
api.post<Route>('/routes', data),
update: (routeId: string, data: Partial<Route>) =>
api.put<Route>(`/routes/${routeId}`, data),
delete: (routeId: string) => api.delete(`/routes/${routeId}`),
copy: (routeId: string) => api.post<Route>(`/routes/${routeId}/copy`),
addLeg: (routeId: string, data: Partial<RouteLeg>) =>
api.post<RouteLeg>(`/routes/${routeId}/legs`, data),
updateLeg: (routeId: string, legId: string, data: Partial<RouteLeg>) =>
api.put<RouteLeg>(`/routes/${routeId}/legs/${legId}`, data),
deleteLeg: (routeId: string, legId: string) =>
api.delete(`/routes/${routeId}/legs/${legId}`),
};
export const teamService = {
@ -52,6 +60,8 @@ export const teamService = {
get: (teamId: string) => api.get<Team>(`/teams/${teamId}`),
join: (teamId: string) => api.post(`/teams/${teamId}/join`),
leave: (teamId: string) => api.post(`/teams/${teamId}/leave`),
assignRoute: (teamId: string, routeId: string) =>
api.post(`/teams/${teamId}/assign-route`, { routeId }),
advance: (teamId: string) => api.post<Team>(`/teams/${teamId}/advance`),
deduct: (teamId: string, seconds: number) => api.post<Team>(`/teams/${teamId}/deduct`, { seconds }),
disqualify: (teamId: string) => api.post<Team>(`/teams/${teamId}/disqualify`),
@ -69,4 +79,14 @@ export const uploadService = {
},
};
export const userService = {
getProfile: () => api.get<User>('/users/me'),
updateProfile: (data: { name?: string; screenName?: string; avatarUrl?: string }) =>
api.put<User>('/users/me', data),
getLocationHistory: () => api.get<{ totalLocations: number; byGame: { game: { id: string; name: string }; locations: LocationHistory[]; locationCount: number }[] }>('/users/me/location-history'),
getGamesHistory: () => api.get<UserGameHistory[]>('/users/me/games'),
deleteLocationData: () => api.delete('/users/me/location-data'),
deleteAccount: () => api.delete('/users/me/account'),
};
export default api;

View file

@ -2,9 +2,48 @@ export interface User {
id: string;
email: string;
name: string;
screenName?: string;
avatarUrl?: string;
createdAt?: string;
}
export interface LocationHistory {
id: string;
userId: string;
gameId: string;
teamId: string;
lat: number;
lng: number;
accuracy?: number;
recordedAt: string;
game?: { id: string; name: string };
}
export interface UserGameHistory {
gameId: string;
gameName: string;
gameStatus: string;
gameMaster: string;
startDate?: string;
teamId: string;
teamName: string;
teamStatus: string;
routeId?: string;
routeName?: string;
routeColor?: string;
totalLegs: number;
totalDistance: number;
proofLocations: ProofLocation[];
}
export interface ProofLocation {
legNumber: number;
description: string;
locationLat?: number;
locationLng?: number;
hasPhotoProof: boolean;
}
export interface Game {
id: string;
name: string;
@ -16,20 +55,33 @@ export interface Game {
locationLng?: number;
searchRadius?: number;
rules?: string[];
randomizeRoutes?: boolean;
status: 'DRAFT' | 'LIVE' | 'ENDED' | 'ARCHIVED';
inviteCode?: string;
createdAt: string;
updatedAt: string;
gameMasterId: string;
gameMaster?: User;
legs?: Leg[];
routes?: Route[];
teams?: Team[];
_count?: { teams: number; legs: number };
_count?: { teams: number; routes: number };
}
export interface Leg {
export interface Route {
id: string;
gameId: string;
name: string;
description?: string;
color: string;
createdAt: string;
updatedAt: string;
routeLegs?: RouteLeg[];
_count?: { teamRoutes: number };
}
export interface RouteLeg {
id: string;
routeId: string;
sequenceNumber: number;
description: string;
conditionType: string;
@ -45,8 +97,7 @@ export interface Team {
name: string;
captainId?: string;
captain?: User;
currentLegId?: string;
currentLeg?: Leg;
currentLegIndex: number;
status: 'ACTIVE' | 'DISQUALIFIED' | 'FINISHED';
totalTimeDeduction: number;
lat?: number;
@ -54,6 +105,16 @@ export interface Team {
rank?: number;
createdAt: string;
members?: TeamMember[];
teamRoutes?: TeamRoute[];
game?: Game;
}
export interface TeamRoute {
id: string;
teamId: string;
routeId: string;
assignedAt: string;
route?: Route;
}
export interface TeamMember {
@ -67,7 +128,7 @@ export interface TeamMember {
export interface PhotoSubmission {
id: string;
teamId: string;
legId: string;
routeLegId: string;
photoUrl: string;
approved: boolean;
submittedAt: string;