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

26
backend/dist/index.js vendored
View file

@ -9,12 +9,13 @@ const cors_1 = __importDefault(require("cors"));
const http_1 = require("http"); const http_1 = require("http");
const socket_io_1 = require("socket.io"); const socket_io_1 = require("socket.io");
const client_1 = require("@prisma/client"); const client_1 = require("@prisma/client");
const auth_js_1 = __importDefault(require("./routes/auth.js")); const auth_1 = __importDefault(require("./routes/auth"));
const games_js_1 = __importDefault(require("./routes/games.js")); const games_1 = __importDefault(require("./routes/games"));
const teams_js_1 = __importDefault(require("./routes/teams.js")); const teams_1 = __importDefault(require("./routes/teams"));
const legs_js_1 = __importDefault(require("./routes/legs.js")); const routes_1 = __importDefault(require("./routes/routes"));
const upload_js_1 = __importDefault(require("./routes/upload.js")); const users_1 = __importDefault(require("./routes/users"));
const index_js_1 = __importDefault(require("./socket/index.js")); const upload_1 = __importDefault(require("./routes/upload"));
const index_1 = __importDefault(require("./socket/index"));
const app = (0, express_1.default)(); const app = (0, express_1.default)();
const httpServer = (0, http_1.createServer)(app); const httpServer = (0, http_1.createServer)(app);
const io = new socket_io_1.Server(httpServer, { const io = new socket_io_1.Server(httpServer, {
@ -27,15 +28,16 @@ exports.prisma = new client_1.PrismaClient();
app.use((0, cors_1.default)()); app.use((0, cors_1.default)());
app.use(express_1.default.json()); app.use(express_1.default.json());
app.use('/uploads', express_1.default.static('uploads')); app.use('/uploads', express_1.default.static('uploads'));
app.use('/api/auth', auth_js_1.default); app.use('/api/auth', auth_1.default);
app.use('/api/games', games_js_1.default); app.use('/api/games', games_1.default);
app.use('/api/teams', teams_js_1.default); app.use('/api/teams', teams_1.default);
app.use('/api/legs', legs_js_1.default); app.use('/api/routes', routes_1.default);
app.use('/api/upload', upload_js_1.default); app.use('/api/users', users_1.default);
app.use('/api/upload', upload_1.default);
app.get('/api/health', (req, res) => { app.get('/api/health', (req, res) => {
res.json({ status: 'ok' }); res.json({ status: 'ok' });
}); });
(0, index_js_1.default)(io); (0, index_1.default)(io);
const PORT = process.env.PORT || 3001; const PORT = process.env.PORT || 3001;
httpServer.listen(PORT, () => { httpServer.listen(PORT, () => {
console.log(`Server running on port ${PORT}`); console.log(`Server running on port ${PORT}`);

View file

@ -5,7 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.optionalAuth = exports.authenticate = void 0; exports.optionalAuth = exports.authenticate = void 0;
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const index_js_1 = require("../index.js"); const index_1 = require("../index");
const JWT_SECRET = process.env.JWT_SECRET || 'treasure-trails-secret-key'; const JWT_SECRET = process.env.JWT_SECRET || 'treasure-trails-secret-key';
const authenticate = async (req, res, next) => { const authenticate = async (req, res, next) => {
try { try {
@ -15,7 +15,7 @@ const authenticate = async (req, res, next) => {
} }
const token = authHeader.split(' ')[1]; const token = authHeader.split(' ')[1];
const decoded = jsonwebtoken_1.default.verify(token, JWT_SECRET); const decoded = jsonwebtoken_1.default.verify(token, JWT_SECRET);
const user = await index_js_1.prisma.user.findUnique({ const user = await index_1.prisma.user.findUnique({
where: { id: decoded.userId }, where: { id: decoded.userId },
select: { id: true, email: true, name: true } select: { id: true, email: true, name: true }
}); });
@ -38,7 +38,7 @@ const optionalAuth = async (req, res, next) => {
} }
const token = authHeader.split(' ')[1]; const token = authHeader.split(' ')[1];
const decoded = jsonwebtoken_1.default.verify(token, JWT_SECRET); const decoded = jsonwebtoken_1.default.verify(token, JWT_SECRET);
const user = await index_js_1.prisma.user.findUnique({ const user = await index_1.prisma.user.findUnique({
where: { id: decoded.userId }, where: { id: decoded.userId },
select: { id: true, email: true, name: true } select: { id: true, email: true, name: true }
}); });

View file

@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express"); const express_1 = require("express");
const bcryptjs_1 = __importDefault(require("bcryptjs")); const bcryptjs_1 = __importDefault(require("bcryptjs"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const index_js_1 = require("../index.js"); const index_1 = require("../index");
const router = (0, express_1.Router)(); const router = (0, express_1.Router)();
const JWT_SECRET = process.env.JWT_SECRET || 'treasure-trails-secret-key'; const JWT_SECRET = process.env.JWT_SECRET || 'treasure-trails-secret-key';
router.post('/register', async (req, res) => { router.post('/register', async (req, res) => {
@ -15,12 +15,12 @@ router.post('/register', async (req, res) => {
if (!email || !password || !name) { if (!email || !password || !name) {
return res.status(400).json({ error: 'Email, password, and name are required' }); return res.status(400).json({ error: 'Email, password, and name are required' });
} }
const existingUser = await index_js_1.prisma.user.findUnique({ where: { email } }); const existingUser = await index_1.prisma.user.findUnique({ where: { email } });
if (existingUser) { if (existingUser) {
return res.status(400).json({ error: 'Email already registered' }); return res.status(400).json({ error: 'Email already registered' });
} }
const passwordHash = await bcryptjs_1.default.hash(password, 10); const passwordHash = await bcryptjs_1.default.hash(password, 10);
const user = await index_js_1.prisma.user.create({ const user = await index_1.prisma.user.create({
data: { email, passwordHash, name } data: { email, passwordHash, name }
}); });
const token = jsonwebtoken_1.default.sign({ userId: user.id }, JWT_SECRET, { expiresIn: '7d' }); const token = jsonwebtoken_1.default.sign({ userId: user.id }, JWT_SECRET, { expiresIn: '7d' });
@ -40,7 +40,7 @@ router.post('/login', async (req, res) => {
if (!email || !password) { if (!email || !password) {
return res.status(400).json({ error: 'Email and password are required' }); return res.status(400).json({ error: 'Email and password are required' });
} }
const user = await index_js_1.prisma.user.findUnique({ where: { email } }); const user = await index_1.prisma.user.findUnique({ where: { email } });
if (!user) { if (!user) {
return res.status(401).json({ error: 'Invalid credentials' }); return res.status(401).json({ error: 'Invalid credentials' });
} }
@ -67,7 +67,7 @@ router.get('/me', async (req, res) => {
} }
const token = authHeader.split(' ')[1]; const token = authHeader.split(' ')[1];
const decoded = jsonwebtoken_1.default.verify(token, JWT_SECRET); const decoded = jsonwebtoken_1.default.verify(token, JWT_SECRET);
const user = await index_js_1.prisma.user.findUnique({ const user = await index_1.prisma.user.findUnique({
where: { id: decoded.userId }, where: { id: decoded.userId },
select: { id: true, email: true, name: true, createdAt: true } select: { id: true, email: true, name: true, createdAt: true }
}); });

View file

@ -1,8 +1,8 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express"); const express_1 = require("express");
const index_js_1 = require("../index.js"); const index_1 = require("../index");
const auth_js_1 = require("../middleware/auth.js"); const auth_1 = require("../middleware/auth");
const uuid_1 = require("uuid"); const uuid_1 = require("uuid");
const router = (0, express_1.Router)(); const router = (0, express_1.Router)();
router.get('/', async (req, res) => { router.get('/', async (req, res) => {
@ -17,11 +17,11 @@ router.get('/', async (req, res) => {
if (search) { if (search) {
where.name = { contains: search, mode: 'insensitive' }; where.name = { contains: search, mode: 'insensitive' };
} }
const games = await index_js_1.prisma.game.findMany({ const games = await index_1.prisma.game.findMany({
where, where,
include: { include: {
gameMaster: { select: { id: true, name: true } }, gameMaster: { select: { id: true, name: true } },
_count: { select: { teams: true, legs: true } } _count: { select: { teams: true, routes: true } }
}, },
orderBy: { createdAt: 'desc' } orderBy: { createdAt: 'desc' }
}); });
@ -32,12 +32,12 @@ router.get('/', async (req, res) => {
res.status(500).json({ error: 'Failed to list games' }); res.status(500).json({ error: 'Failed to list games' });
} }
}); });
router.get('/my-games', auth_js_1.authenticate, async (req, res) => { router.get('/my-games', auth_1.authenticate, async (req, res) => {
try { try {
const games = await index_js_1.prisma.game.findMany({ const games = await index_1.prisma.game.findMany({
where: { gameMasterId: req.user.id }, where: { gameMasterId: req.user.id },
include: { include: {
_count: { select: { teams: true, legs: true } } _count: { select: { teams: true, routes: true } }
}, },
orderBy: { createdAt: 'desc' } orderBy: { createdAt: 'desc' }
}); });
@ -51,15 +51,27 @@ router.get('/my-games', auth_js_1.authenticate, async (req, res) => {
router.get('/:id', async (req, res) => { router.get('/:id', async (req, res) => {
try { try {
const { id } = req.params; const { id } = req.params;
const game = await index_js_1.prisma.game.findUnique({ const game = await index_1.prisma.game.findUnique({
where: { id }, where: { id: id },
include: { include: {
gameMaster: { select: { id: true, name: true } }, gameMaster: { select: { id: true, name: true } },
legs: { orderBy: { sequenceNumber: 'asc' } }, routes: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
},
teams: { teams: {
include: { include: {
members: { include: { user: { select: { id: true, name: true, email: true } } } }, members: { include: { user: { select: { id: true, name: true, email: true } } } },
currentLeg: true teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
} }
} }
} }
@ -71,16 +83,20 @@ router.get('/:id', async (req, res) => {
if (game.visibility === 'PRIVATE' && !isOwner) { if (game.visibility === 'PRIVATE' && !isOwner) {
return res.status(403).json({ error: 'Access denied' }); return res.status(403).json({ error: 'Access denied' });
} }
res.json(game); const result = {
...game,
rules: game.rules ? JSON.parse(game.rules) : []
};
res.json(result);
} }
catch (error) { catch (error) {
console.error('Get game error:', error); console.error('Get game error:', error);
res.status(500).json({ error: 'Failed to get game' }); res.status(500).json({ error: 'Failed to get game' });
} }
}); });
router.post('/', auth_js_1.authenticate, async (req, res) => { router.post('/', auth_1.authenticate, async (req, res) => {
try { try {
const { name, description, prizeDetails, visibility, startDate, locationLat, locationLng, searchRadius, timeLimitPerLeg, timeDeductionPenalty } = req.body; const { name, description, prizeDetails, visibility, startDate, locationLat, locationLng, searchRadius, rules, randomizeRoutes } = req.body;
if (!name) { if (!name) {
return res.status(400).json({ error: 'Name is required' }); return res.status(400).json({ error: 'Name is required' });
} }
@ -88,7 +104,7 @@ router.post('/', auth_js_1.authenticate, async (req, res) => {
return res.status(400).json({ error: 'Start date must be in the future' }); return res.status(400).json({ error: 'Start date must be in the future' });
} }
const inviteCode = (0, uuid_1.v4)().slice(0, 8); const inviteCode = (0, uuid_1.v4)().slice(0, 8);
const game = await index_js_1.prisma.game.create({ const game = await index_1.prisma.game.create({
data: { data: {
name, name,
description, description,
@ -98,8 +114,8 @@ router.post('/', auth_js_1.authenticate, async (req, res) => {
locationLat, locationLat,
locationLng, locationLng,
searchRadius, searchRadius,
timeLimitPerLeg, rules: rules ? JSON.stringify(rules) : null,
timeDeductionPenalty, randomizeRoutes: randomizeRoutes || false,
gameMasterId: req.user.id, gameMasterId: req.user.id,
inviteCode inviteCode
} }
@ -111,19 +127,19 @@ router.post('/', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to create game' }); res.status(500).json({ error: 'Failed to create game' });
} }
}); });
router.put('/:id', auth_js_1.authenticate, async (req, res) => { router.put('/:id', auth_1.authenticate, async (req, res) => {
try { try {
const { id } = req.params; const id = req.params.id;
const { name, description, prizeDetails, visibility, startDate, locationLat, locationLng, searchRadius, timeLimitPerLeg, timeDeductionPenalty, status } = req.body; const { name, description, prizeDetails, visibility, startDate, locationLat, locationLng, searchRadius, rules, status, randomizeRoutes } = req.body;
const game = await index_js_1.prisma.game.findUnique({ where: { id } }); const game = await index_1.prisma.game.findUnique({ where: { id } });
if (!game) { if (!game) {
return res.status(404).json({ error: 'Game not found' }); return res.status(404).json({ error: 'Game not found' });
} }
if (game.gameMasterId !== req.user.id) { if (game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
const updated = await index_js_1.prisma.game.update({ const updated = await index_1.prisma.game.update({
where: { id }, where: { id: id },
data: { data: {
name, name,
description, description,
@ -133,8 +149,8 @@ router.put('/:id', auth_js_1.authenticate, async (req, res) => {
locationLat, locationLat,
locationLng, locationLng,
searchRadius, searchRadius,
timeLimitPerLeg, rules: rules ? JSON.stringify(rules) : undefined,
timeDeductionPenalty, randomizeRoutes,
status status
} }
}); });
@ -145,17 +161,17 @@ router.put('/:id', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to update game' }); res.status(500).json({ error: 'Failed to update game' });
} }
}); });
router.delete('/:id', auth_js_1.authenticate, async (req, res) => { router.delete('/:id', auth_1.authenticate, async (req, res) => {
try { try {
const { id } = req.params; const id = req.params.id;
const game = await index_js_1.prisma.game.findUnique({ where: { id } }); const game = await index_1.prisma.game.findUnique({ where: { id } });
if (!game) { if (!game) {
return res.status(404).json({ error: 'Game not found' }); return res.status(404).json({ error: 'Game not found' });
} }
if (game.gameMasterId !== req.user.id) { if (game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
await index_js_1.prisma.game.delete({ where: { id } }); await index_1.prisma.game.delete({ where: { id } });
res.json({ message: 'Game deleted' }); res.json({ message: 'Game deleted' });
} }
catch (error) { catch (error) {
@ -163,12 +179,12 @@ router.delete('/:id', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to delete game' }); res.status(500).json({ error: 'Failed to delete game' });
} }
}); });
router.post('/:id/publish', auth_js_1.authenticate, async (req, res) => { router.post('/:id/publish', auth_1.authenticate, async (req, res) => {
try { try {
const { id } = req.params; const { id } = req.params;
const game = await index_js_1.prisma.game.findUnique({ const game = await index_1.prisma.game.findUnique({
where: { id }, where: { id: id },
include: { legs: true } include: { routes: { include: { routeLegs: true } } }
}); });
if (!game) { if (!game) {
return res.status(404).json({ error: 'Game not found' }); return res.status(404).json({ error: 'Game not found' });
@ -176,11 +192,34 @@ router.post('/:id/publish', auth_js_1.authenticate, async (req, res) => {
if (game.gameMasterId !== req.user.id) { if (game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
if (game.legs.length === 0) { if (!game.routes || game.routes.length === 0) {
return res.status(400).json({ error: 'Game must have at least one leg' }); return res.status(400).json({ error: 'Game must have at least one route' });
} }
const updated = await index_js_1.prisma.game.update({ const hasValidRoute = game.routes.some(route => route.routeLegs.length > 0);
where: { id }, if (!hasValidRoute) {
return res.status(400).json({ error: 'At least one route must have legs' });
}
if (game.randomizeRoutes) {
const teams = await index_1.prisma.team.findMany({
where: { gameId: id }
});
const shuffledRoutes = [...game.routes].sort(() => Math.random() - 0.5);
for (let i = 0; i < teams.length; i++) {
const routeIndex = i % game.routes.length;
await index_1.prisma.teamRoute.upsert({
where: { teamId: teams[i].id },
create: {
teamId: teams[i].id,
routeId: shuffledRoutes[routeIndex].id
},
update: {
routeId: shuffledRoutes[routeIndex].id
}
});
}
}
const updated = await index_1.prisma.game.update({
where: { id: id },
data: { status: 'LIVE' } data: { status: 'LIVE' }
}); });
res.json(updated); res.json(updated);
@ -190,17 +229,17 @@ router.post('/:id/publish', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to publish game' }); res.status(500).json({ error: 'Failed to publish game' });
} }
}); });
router.post('/:id/end', auth_js_1.authenticate, async (req, res) => { router.post('/:id/end', auth_1.authenticate, async (req, res) => {
try { try {
const { id } = req.params; const id = req.params.id;
const game = await index_js_1.prisma.game.findUnique({ where: { id } }); const game = await index_1.prisma.game.findUnique({ where: { id } });
if (!game) { if (!game) {
return res.status(404).json({ error: 'Game not found' }); return res.status(404).json({ error: 'Game not found' });
} }
if (game.gameMasterId !== req.user.id) { if (game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
const updated = await index_js_1.prisma.game.update({ const updated = await index_1.prisma.game.update({
where: { id }, where: { id },
data: { status: 'ENDED' } data: { status: 'ENDED' }
}); });
@ -211,10 +250,52 @@ router.post('/:id/end', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to end game' }); res.status(500).json({ error: 'Failed to end game' });
} }
}); });
router.post('/:id/archive', auth_1.authenticate, async (req, res) => {
try {
const id = req.params.id;
const game = await index_1.prisma.game.findUnique({ where: { id } });
if (!game) {
return res.status(404).json({ error: 'Game not found' });
}
if (game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const updated = await index_1.prisma.game.update({
where: { id },
data: { status: 'ARCHIVED' }
});
res.json(updated);
}
catch (error) {
console.error('Archive game error:', error);
res.status(500).json({ error: 'Failed to archive game' });
}
});
router.post('/:id/unarchive', auth_1.authenticate, async (req, res) => {
try {
const id = req.params.id;
const game = await index_1.prisma.game.findUnique({ where: { id } });
if (!game) {
return res.status(404).json({ error: 'Game not found' });
}
if (game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const updated = await index_1.prisma.game.update({
where: { id },
data: { status: 'ENDED' }
});
res.json(updated);
}
catch (error) {
console.error('Unarchive game error:', error);
res.status(500).json({ error: 'Failed to unarchive game' });
}
});
router.get('/:id/invite', async (req, res) => { router.get('/:id/invite', async (req, res) => {
try { try {
const { id } = req.params; const id = req.params.id;
const game = await index_js_1.prisma.game.findUnique({ where: { id } }); const game = await index_1.prisma.game.findUnique({ where: { id } });
if (!game) { if (!game) {
return res.status(404).json({ error: 'Game not found' }); return res.status(404).json({ error: 'Game not found' });
} }
@ -230,8 +311,8 @@ router.get('/:id/invite', async (req, res) => {
}); });
router.get('/invite/:code', async (req, res) => { router.get('/invite/:code', async (req, res) => {
try { try {
const { code } = req.params; const code = req.params.code;
const game = await index_js_1.prisma.game.findUnique({ const game = await index_1.prisma.game.findUnique({
where: { inviteCode: code }, where: { inviteCode: code },
include: { gameMaster: { select: { id: true, name: true } } } include: { gameMaster: { select: { id: true, name: true } } }
}); });

2
backend/dist/routes/routes.d.ts vendored Normal file
View file

@ -0,0 +1,2 @@
declare const router: import("express-serve-static-core").Router;
export default router;

338
backend/dist/routes/routes.js vendored Normal file
View file

@ -0,0 +1,338 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const index_1 = require("../index");
const auth_1 = require("../middleware/auth");
const router = (0, express_1.Router)();
router.get('/game/:gameId', async (req, res) => {
try {
const { gameId } = req.params;
const routes = await index_1.prisma.route.findMany({
where: { gameId: gameId },
include: {
routeLegs: {
orderBy: { sequenceNumber: 'asc' }
},
_count: { select: { teamRoutes: true } }
},
orderBy: { createdAt: 'asc' }
});
res.json(routes);
}
catch (error) {
console.error('List routes error:', error);
res.status(500).json({ error: 'Failed to list routes' });
}
});
router.get('/:id', async (req, res) => {
try {
const { id } = req.params;
const route = await index_1.prisma.route.findUnique({
where: { id: id },
include: {
routeLegs: {
orderBy: { sequenceNumber: 'asc' }
},
teamRoutes: {
include: {
team: {
include: {
members: { include: { user: { select: { id: true, name: true } } } }
}
}
}
}
}
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
res.json(route);
}
catch (error) {
console.error('Get route error:', error);
res.status(500).json({ error: 'Failed to get route' });
}
});
router.post('/', auth_1.authenticate, async (req, res) => {
try {
const { gameId, name, description, color } = req.body;
if (!gameId || !name) {
return res.status(400).json({ error: 'Game ID and name are required' });
}
const game = await index_1.prisma.game.findUnique({ where: { id: gameId } });
if (!game) {
return res.status(404).json({ error: 'Game not found' });
}
if (game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const route = await index_1.prisma.route.create({
data: {
gameId,
name,
description,
color: color || '#3498db'
},
include: {
routeLegs: true
}
});
res.json(route);
}
catch (error) {
console.error('Create route error:', error);
res.status(500).json({ error: 'Failed to create route' });
}
});
router.put('/:id', auth_1.authenticate, async (req, res) => {
try {
const { id } = req.params;
const { name, description, color } = req.body;
const route = await index_1.prisma.route.findUnique({
where: { id: id },
include: { game: true }
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
if (route.game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const updated = await index_1.prisma.route.update({
where: { id: id },
data: {
name: name || route.name,
description: description !== undefined ? description : route.description,
color: color || route.color
},
include: {
routeLegs: {
orderBy: { sequenceNumber: 'asc' }
}
}
});
res.json(updated);
}
catch (error) {
console.error('Update route error:', error);
res.status(500).json({ error: 'Failed to update route' });
}
});
router.delete('/:id', auth_1.authenticate, async (req, res) => {
try {
const { id } = req.params;
const route = await index_1.prisma.route.findUnique({
where: { id: id },
include: { game: true }
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
if (route.game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
await index_1.prisma.route.delete({ where: { id: id } });
res.json({ message: 'Route deleted' });
}
catch (error) {
console.error('Delete route error:', error);
res.status(500).json({ error: 'Failed to delete route' });
}
});
router.post('/:id/legs', auth_1.authenticate, async (req, res) => {
try {
const { id } = req.params;
const { description, conditionType, conditionDetails, locationLat, locationLng, timeLimit } = req.body;
const route = await index_1.prisma.route.findUnique({
where: { id: id },
include: {
game: true,
routeLegs: true
}
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
if (route.game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const maxSequence = route.routeLegs.length > 0
? Math.max(...route.routeLegs.map(l => l.sequenceNumber))
: 0;
const routeLeg = await index_1.prisma.routeLeg.create({
data: {
routeId: id,
sequenceNumber: maxSequence + 1,
description: description || '',
conditionType: conditionType || 'photo',
conditionDetails,
locationLat,
locationLng,
timeLimit
}
});
res.json(routeLeg);
}
catch (error) {
console.error('Add route leg error:', error);
res.status(500).json({ error: 'Failed to add leg to route' });
}
});
router.put('/:id/legs/:legId', auth_1.authenticate, async (req, res) => {
try {
const { id, legId } = req.params;
const { description, conditionType, conditionDetails, locationLat, locationLng, timeLimit, sequenceNumber } = req.body;
const route = await index_1.prisma.route.findUnique({
where: { id: id },
include: { game: true }
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
if (route.game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const routeLeg = await index_1.prisma.routeLeg.update({
where: { id: legId },
data: {
description: description !== undefined ? description : undefined,
conditionType: conditionType !== undefined ? conditionType : undefined,
conditionDetails: conditionDetails !== undefined ? conditionDetails : undefined,
locationLat: locationLat !== undefined ? locationLat : undefined,
locationLng: locationLng !== undefined ? locationLng : undefined,
timeLimit: timeLimit !== undefined ? timeLimit : undefined,
sequenceNumber: sequenceNumber !== undefined ? sequenceNumber : undefined
}
});
res.json(routeLeg);
}
catch (error) {
console.error('Update route leg error:', error);
res.status(500).json({ error: 'Failed to update route leg' });
}
});
router.delete('/:id/legs/:legId', auth_1.authenticate, async (req, res) => {
try {
const { id, legId } = req.params;
const route = await index_1.prisma.route.findUnique({
where: { id: id },
include: { game: true }
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
if (route.game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
await index_1.prisma.routeLeg.delete({ where: { id: legId } });
const remainingLegs = await index_1.prisma.routeLeg.findMany({
where: { routeId: id },
orderBy: { sequenceNumber: 'asc' }
});
for (let i = 0; i < remainingLegs.length; i++) {
if (remainingLegs[i].sequenceNumber !== i + 1) {
await index_1.prisma.routeLeg.update({
where: { id: remainingLegs[i].id },
data: { sequenceNumber: i + 1 }
});
}
}
res.json({ message: 'Leg deleted' });
}
catch (error) {
console.error('Delete route leg error:', error);
res.status(500).json({ error: 'Failed to delete route leg' });
}
});
router.post('/:id/legs/:legId/photo', auth_1.authenticate, async (req, res) => {
try {
const { id, legId } = req.params;
const { teamId, photoUrl } = req.body;
const route = await index_1.prisma.route.findUnique({
where: { id: id },
include: { game: true }
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
const routeLeg = await index_1.prisma.routeLeg.findFirst({
where: { id: legId, routeId: id }
});
if (!routeLeg) {
return res.status(404).json({ error: 'Route leg not found' });
}
const member = await index_1.prisma.teamMember.findFirst({
where: { teamId, userId: req.user.id }
});
const team = await index_1.prisma.team.findUnique({ where: { id: teamId } });
if (!member && team?.captainId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const submission = await index_1.prisma.photoSubmission.create({
data: {
teamId,
routeId: id,
routeLegId: legId,
photoUrl
}
});
res.json(submission);
}
catch (error) {
console.error('Photo submission error:', error);
res.status(500).json({ error: 'Failed to submit photo' });
}
});
router.post('/:id/copy', auth_1.authenticate, async (req, res) => {
try {
const { id } = req.params;
const originalRoute = await index_1.prisma.route.findUnique({
where: { id: id },
include: {
game: true,
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
});
if (!originalRoute) {
return res.status(404).json({ error: 'Route not found' });
}
if (originalRoute.game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const newRoute = await index_1.prisma.route.create({
data: {
gameId: originalRoute.gameId,
name: `${originalRoute.name} (Copy)`,
description: originalRoute.description,
color: originalRoute.color
}
});
for (const leg of originalRoute.routeLegs) {
await index_1.prisma.routeLeg.create({
data: {
routeId: newRoute.id,
sequenceNumber: leg.sequenceNumber,
description: leg.description,
conditionType: leg.conditionType,
conditionDetails: leg.conditionDetails,
locationLat: leg.locationLat,
locationLng: leg.locationLng,
timeLimit: leg.timeLimit
}
});
}
const fullRoute = await index_1.prisma.route.findUnique({
where: { id: newRoute.id },
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
});
res.json(fullRoute);
}
catch (error) {
console.error('Copy route error:', error);
res.status(500).json({ error: 'Failed to copy route' });
}
});
exports.default = router;

View file

@ -1,18 +1,26 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express"); const express_1 = require("express");
const index_js_1 = require("../index.js"); const index_1 = require("../index");
const auth_js_1 = require("../middleware/auth.js"); const auth_1 = require("../middleware/auth");
const router = (0, express_1.Router)(); const router = (0, express_1.Router)();
router.get('/game/:gameId', async (req, res) => { router.get('/game/:gameId', async (req, res) => {
try { try {
const { gameId } = req.params; const { gameId } = req.params;
const teams = await index_js_1.prisma.team.findMany({ const teams = await index_1.prisma.team.findMany({
where: { gameId }, where: { gameId },
include: { include: {
members: { include: { user: { select: { id: true, name: true, email: true } } } }, members: { include: { user: { select: { id: true, name: true, email: true } } } },
captain: { select: { id: true, name: true } }, captain: { select: { id: true, name: true } },
currentLeg: true teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
}, },
orderBy: { createdAt: 'asc' } orderBy: { createdAt: 'asc' }
}); });
@ -23,11 +31,11 @@ router.get('/game/:gameId', async (req, res) => {
res.status(500).json({ error: 'Failed to get teams' }); res.status(500).json({ error: 'Failed to get teams' });
} }
}); });
router.post('/game/:gameId', auth_js_1.authenticate, async (req, res) => { router.post('/game/:gameId', auth_1.authenticate, async (req, res) => {
try { try {
const { gameId } = req.params; const { gameId } = req.params;
const { name } = req.body; const { name } = req.body;
const game = await index_js_1.prisma.game.findUnique({ const game = await index_1.prisma.game.findUnique({
where: { id: gameId }, where: { id: gameId },
include: { teams: true } include: { teams: true }
}); });
@ -37,7 +45,7 @@ router.post('/game/:gameId', auth_js_1.authenticate, async (req, res) => {
if (game.status !== 'DRAFT' && game.status !== 'LIVE') { if (game.status !== 'DRAFT' && game.status !== 'LIVE') {
return res.status(400).json({ error: 'Cannot join game at this time' }); return res.status(400).json({ error: 'Cannot join game at this time' });
} }
const existingMember = await index_js_1.prisma.teamMember.findFirst({ const existingMember = await index_1.prisma.teamMember.findFirst({
where: { where: {
userId: req.user.id, userId: req.user.id,
team: { gameId } team: { gameId }
@ -46,24 +54,33 @@ router.post('/game/:gameId', auth_js_1.authenticate, async (req, res) => {
if (existingMember) { if (existingMember) {
return res.status(400).json({ error: 'Already in a team for this game' }); return res.status(400).json({ error: 'Already in a team for this game' });
} }
const team = await index_js_1.prisma.team.create({ const team = await index_1.prisma.team.create({
data: { data: {
gameId, gameId,
name, name,
captainId: req.user.id captainId: req.user.id
} }
}); });
await index_js_1.prisma.teamMember.create({ await index_1.prisma.teamMember.create({
data: { data: {
teamId: team.id, teamId: team.id,
userId: req.user.id userId: req.user.id
} }
}); });
const created = await index_js_1.prisma.team.findUnique({ const created = await index_1.prisma.team.findUnique({
where: { id: team.id }, where: { id: team.id },
include: { include: {
members: { include: { user: { select: { id: true, name: true, email: true } } } }, members: { include: { user: { select: { id: true, name: true, email: true } } } },
captain: { select: { id: true, name: true } } captain: { select: { id: true, name: true } },
teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
} }
}); });
res.json(created); res.json(created);
@ -73,10 +90,10 @@ router.post('/game/:gameId', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to create team' }); res.status(500).json({ error: 'Failed to create team' });
} }
}); });
router.post('/:teamId/join', auth_js_1.authenticate, async (req, res) => { router.post('/:teamId/join', auth_1.authenticate, async (req, res) => {
try { try {
const { teamId } = req.params; const { teamId } = req.params;
const team = await index_js_1.prisma.team.findUnique({ const team = await index_1.prisma.team.findUnique({
where: { id: teamId }, where: { id: teamId },
include: { game: true, members: true } include: { game: true, members: true }
}); });
@ -86,7 +103,7 @@ router.post('/:teamId/join', auth_js_1.authenticate, async (req, res) => {
if (team.members.length >= 5) { if (team.members.length >= 5) {
return res.status(400).json({ error: 'Team is full (max 5 members)' }); return res.status(400).json({ error: 'Team is full (max 5 members)' });
} }
const existingMember = await index_js_1.prisma.teamMember.findFirst({ const existingMember = await index_1.prisma.teamMember.findFirst({
where: { where: {
userId: req.user.id, userId: req.user.id,
teamId teamId
@ -95,7 +112,7 @@ router.post('/:teamId/join', auth_js_1.authenticate, async (req, res) => {
if (existingMember) { if (existingMember) {
return res.status(400).json({ error: 'Already in this team' }); return res.status(400).json({ error: 'Already in this team' });
} }
const gameMember = await index_js_1.prisma.teamMember.findFirst({ const gameMember = await index_1.prisma.teamMember.findFirst({
where: { where: {
userId: req.user.id, userId: req.user.id,
team: { gameId: team.gameId } team: { gameId: team.gameId }
@ -104,7 +121,7 @@ router.post('/:teamId/join', auth_js_1.authenticate, async (req, res) => {
if (gameMember) { if (gameMember) {
return res.status(400).json({ error: 'Already in another team for this game' }); return res.status(400).json({ error: 'Already in another team for this game' });
} }
await index_js_1.prisma.teamMember.create({ await index_1.prisma.teamMember.create({
data: { data: {
teamId, teamId,
userId: req.user.id userId: req.user.id
@ -117,10 +134,10 @@ router.post('/:teamId/join', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to join team' }); res.status(500).json({ error: 'Failed to join team' });
} }
}); });
router.post('/:teamId/leave', auth_js_1.authenticate, async (req, res) => { router.post('/:teamId/leave', auth_1.authenticate, async (req, res) => {
try { try {
const { teamId } = req.params; const { teamId } = req.params;
const team = await index_js_1.prisma.team.findUnique({ const team = await index_1.prisma.team.findUnique({
where: { id: teamId } where: { id: teamId }
}); });
if (!team) { if (!team) {
@ -129,7 +146,7 @@ router.post('/:teamId/leave', auth_js_1.authenticate, async (req, res) => {
if (team.captainId === req.user.id) { if (team.captainId === req.user.id) {
return res.status(400).json({ error: 'Captain cannot leave the team' }); return res.status(400).json({ error: 'Captain cannot leave the team' });
} }
await index_js_1.prisma.teamMember.deleteMany({ await index_1.prisma.teamMember.deleteMany({
where: { where: {
teamId, teamId,
userId: req.user.id userId: req.user.id
@ -142,14 +159,65 @@ router.post('/:teamId/leave', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to leave team' }); res.status(500).json({ error: 'Failed to leave team' });
} }
}); });
router.post('/:teamId/advance', auth_js_1.authenticate, async (req, res) => { router.post('/:teamId/assign-route', auth_1.authenticate, async (req, res) => {
try { try {
const { teamId } = req.params; const { teamId } = req.params;
const team = await index_js_1.prisma.team.findUnique({ const { routeId } = req.body;
const team = await index_1.prisma.team.findUnique({
where: { id: teamId },
include: { game: true, teamRoutes: true }
});
if (!team) {
return res.status(404).json({ error: 'Team not found' });
}
if (team.game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const route = await index_1.prisma.route.findUnique({
where: { id: routeId }
});
if (!route || route.gameId !== team.gameId) {
return res.status(400).json({ error: 'Invalid route for this game' });
}
await index_1.prisma.teamRoute.deleteMany({
where: { teamId }
});
const teamRoute = await index_1.prisma.teamRoute.create({
data: {
teamId,
routeId
},
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
});
res.json(teamRoute);
}
catch (error) {
console.error('Assign route error:', error);
res.status(500).json({ error: 'Failed to assign route' });
}
});
router.post('/:teamId/advance', auth_1.authenticate, async (req, res) => {
try {
const { teamId } = req.params;
const team = await index_1.prisma.team.findUnique({
where: { id: teamId }, where: { id: teamId },
include: { include: {
game: { include: { legs: { orderBy: { sequenceNumber: 'asc' } } } }, game: true,
currentLeg: true teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
} }
}); });
if (!team) { if (!team) {
@ -158,27 +226,33 @@ router.post('/:teamId/advance', auth_js_1.authenticate, async (req, res) => {
if (team.game.gameMasterId !== req.user.id) { if (team.game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
const legs = team.game.legs; const teamRoute = team.teamRoutes[0];
const currentLeg = team.currentLeg; if (!teamRoute) {
let nextLeg = null; return res.status(400).json({ error: 'Team has no assigned route' });
if (currentLeg) {
const currentIndex = legs.findIndex((l) => l.id === currentLeg.id);
if (currentIndex < legs.length - 1) {
nextLeg = legs[currentIndex + 1];
}
} }
else if (legs.length > 0) { const legs = teamRoute.route.routeLegs;
nextLeg = legs[0]; const currentLegIndex = team.currentLegIndex;
let nextLegIndex = currentLegIndex;
if (currentLegIndex < legs.length - 1) {
nextLegIndex = currentLegIndex + 1;
} }
const updated = await index_js_1.prisma.team.update({ const updated = await index_1.prisma.team.update({
where: { id: teamId }, where: { id: teamId },
data: { data: {
currentLegId: nextLeg?.id || null, currentLegIndex: nextLegIndex,
status: nextLeg ? 'ACTIVE' : 'FINISHED' status: nextLegIndex >= legs.length - 1 ? 'FINISHED' : 'ACTIVE'
}, },
include: { include: {
members: { include: { user: { select: { id: true, name: true } } } }, members: { include: { user: { select: { id: true, name: true } } } },
currentLeg: true teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
} }
}); });
res.json(updated); res.json(updated);
@ -188,11 +262,11 @@ router.post('/:teamId/advance', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to advance team' }); res.status(500).json({ error: 'Failed to advance team' });
} }
}); });
router.post('/:teamId/deduct', auth_js_1.authenticate, async (req, res) => { router.post('/:teamId/deduct', auth_1.authenticate, async (req, res) => {
try { try {
const { teamId } = req.params; const { teamId } = req.params;
const { seconds } = req.body; const { seconds } = req.body;
const team = await index_js_1.prisma.team.findUnique({ const team = await index_1.prisma.team.findUnique({
where: { id: teamId }, where: { id: teamId },
include: { game: true } include: { game: true }
}); });
@ -202,8 +276,8 @@ router.post('/:teamId/deduct', auth_js_1.authenticate, async (req, res) => {
if (team.game.gameMasterId !== req.user.id) { if (team.game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
const deduction = seconds || team.game.timeDeductionPenalty || 60; const deduction = seconds || 60;
const updated = await index_js_1.prisma.team.update({ const updated = await index_1.prisma.team.update({
where: { id: teamId }, where: { id: teamId },
data: { totalTimeDeduction: { increment: deduction } } data: { totalTimeDeduction: { increment: deduction } }
}); });
@ -214,10 +288,10 @@ router.post('/:teamId/deduct', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to deduct time' }); res.status(500).json({ error: 'Failed to deduct time' });
} }
}); });
router.post('/:teamId/disqualify', auth_js_1.authenticate, async (req, res) => { router.post('/:teamId/disqualify', auth_1.authenticate, async (req, res) => {
try { try {
const { teamId } = req.params; const { teamId } = req.params;
const team = await index_js_1.prisma.team.findUnique({ const team = await index_1.prisma.team.findUnique({
where: { id: teamId }, where: { id: teamId },
include: { game: true } include: { game: true }
}); });
@ -227,7 +301,7 @@ router.post('/:teamId/disqualify', auth_js_1.authenticate, async (req, res) => {
if (team.game.gameMasterId !== req.user.id) { if (team.game.gameMasterId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
const updated = await index_js_1.prisma.team.update({ const updated = await index_1.prisma.team.update({
where: { id: teamId }, where: { id: teamId },
data: { status: 'DISQUALIFIED' } data: { status: 'DISQUALIFIED' }
}); });
@ -238,23 +312,23 @@ router.post('/:teamId/disqualify', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to disqualify team' }); res.status(500).json({ error: 'Failed to disqualify team' });
} }
}); });
router.post('/:teamId/location', auth_js_1.authenticate, async (req, res) => { router.post('/:teamId/location', auth_1.authenticate, async (req, res) => {
try { try {
const { teamId } = req.params; const { teamId } = req.params;
const { lat, lng } = req.body; const { lat, lng } = req.body;
const team = await index_js_1.prisma.team.findUnique({ const team = await index_1.prisma.team.findUnique({
where: { id: teamId } where: { id: teamId }
}); });
if (!team) { if (!team) {
return res.status(404).json({ error: 'Team not found' }); return res.status(404).json({ error: 'Team not found' });
} }
const member = await index_js_1.prisma.teamMember.findFirst({ const member = await index_1.prisma.teamMember.findFirst({
where: { teamId, userId: req.user.id } where: { teamId, userId: req.user.id }
}); });
if (!member && team.captainId !== req.user.id) { if (!member && team.captainId !== req.user.id) {
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
const updated = await index_js_1.prisma.team.update({ const updated = await index_1.prisma.team.update({
where: { id: teamId }, where: { id: teamId },
data: { lat, lng } data: { lat, lng }
}); });
@ -265,16 +339,24 @@ router.post('/:teamId/location', auth_js_1.authenticate, async (req, res) => {
res.status(500).json({ error: 'Failed to update location' }); res.status(500).json({ error: 'Failed to update location' });
} }
}); });
router.get('/:teamId', auth_js_1.authenticate, async (req, res) => { router.get('/:teamId', auth_1.authenticate, async (req, res) => {
try { try {
const { teamId } = req.params; const { teamId } = req.params;
const team = await index_js_1.prisma.team.findUnique({ const team = await index_1.prisma.team.findUnique({
where: { id: teamId }, where: { id: teamId },
include: { include: {
members: { include: { user: { select: { id: true, name: true, email: true } } } }, members: { include: { user: { select: { id: true, name: true, email: true } } } },
captain: { select: { id: true, name: true } }, captain: { select: { id: true, name: true } },
currentLeg: true, game: { include: { routes: { include: { routeLegs: { orderBy: { sequenceNumber: 'asc' } } } } } },
game: { include: { legs: { orderBy: { sequenceNumber: 'asc' } } } } teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
} }
}); });
if (!team) { if (!team) {

View file

@ -7,7 +7,7 @@ const express_1 = require("express");
const multer_1 = __importDefault(require("multer")); const multer_1 = __importDefault(require("multer"));
const path_1 = __importDefault(require("path")); const path_1 = __importDefault(require("path"));
const uuid_1 = require("uuid"); const uuid_1 = require("uuid");
const auth_js_1 = require("../middleware/auth.js"); const auth_1 = require("../middleware/auth");
const router = (0, express_1.Router)(); const router = (0, express_1.Router)();
const storage = multer_1.default.diskStorage({ const storage = multer_1.default.diskStorage({
destination: (req, file, cb) => { destination: (req, file, cb) => {
@ -31,7 +31,7 @@ const upload = (0, multer_1.default)({
cb(new Error('Only image files are allowed')); cb(new Error('Only image files are allowed'));
} }
}); });
router.post('/upload', auth_js_1.authenticate, upload.single('photo'), (req, res) => { router.post('/upload', auth_1.authenticate, upload.single('photo'), (req, res) => {
try { try {
if (!req.file) { if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' }); return res.status(400).json({ error: 'No file uploaded' });

2
backend/dist/routes/users.d.ts vendored Normal file
View file

@ -0,0 +1,2 @@
declare const router: import("express-serve-static-core").Router;
export default router;

213
backend/dist/routes/users.js vendored Normal file
View file

@ -0,0 +1,213 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const index_1 = require("../index");
const auth_1 = require("../middleware/auth");
const router = (0, express_1.Router)();
router.get('/me', auth_1.authenticate, async (req, res) => {
try {
const user = await index_1.prisma.user.findUnique({
where: { id: req.user.id },
select: {
id: true,
email: true,
name: true,
screenName: true,
avatarUrl: true,
createdAt: true
}
});
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
}
catch (error) {
console.error('Get user error:', error);
res.status(500).json({ error: 'Failed to get user' });
}
});
router.put('/me', auth_1.authenticate, async (req, res) => {
try {
const { name, screenName, avatarUrl } = req.body;
const updated = await index_1.prisma.user.update({
where: { id: req.user.id },
data: {
name: name || undefined,
screenName: screenName !== undefined ? screenName || null : undefined,
avatarUrl: avatarUrl !== undefined ? avatarUrl || null : undefined
},
select: {
id: true,
email: true,
name: true,
screenName: true,
avatarUrl: true,
createdAt: true
}
});
res.json(updated);
}
catch (error) {
console.error('Update user error:', error);
res.status(500).json({ error: 'Failed to update user' });
}
});
router.get('/me/location-history', auth_1.authenticate, async (req, res) => {
try {
const locations = await index_1.prisma.locationHistory.findMany({
where: { userId: req.user.id },
include: {
game: {
select: { id: true, name: true }
}
},
orderBy: { recordedAt: 'desc' }
});
const games = await index_1.prisma.game.findMany({
where: {
teams: {
some: {
members: {
some: { userId: req.user.id }
}
}
}
},
select: { id: true, name: true }
});
const locationByGame = games.map(game => {
const gameLocations = locations.filter(l => l.gameId === game.id);
return {
game: game,
locations: gameLocations,
locationCount: gameLocations.length
};
}).filter(g => g.locationCount > 0);
res.json({
totalLocations: locations.length,
byGame: locationByGame
});
}
catch (error) {
console.error('Get location history error:', error);
res.status(500).json({ error: 'Failed to get location history' });
}
});
router.get('/me/games', auth_1.authenticate, async (req, res) => {
try {
const memberships = await index_1.prisma.teamMember.findMany({
where: { userId: req.user.id },
include: {
team: {
include: {
game: {
select: {
id: true,
name: true,
status: true,
startDate: true,
locationLat: true,
locationLng: true,
gameMasterId: true,
gameMaster: { select: { name: true } }
}
},
teamRoutes: {
include: {
route: {
include: {
routeLegs: {
orderBy: { sequenceNumber: 'asc' }
}
}
}
}
},
photoSubmissions: true
}
}
}
});
const gamesWithDetails = memberships.map(m => {
const team = m.team;
const game = team.game;
const teamRoute = team.teamRoutes[0];
const route = teamRoute?.route;
const photoSubmissions = team.photoSubmissions;
const routeLegs = route?.routeLegs || [];
const proofLocations = routeLegs.filter(leg => photoSubmissions.some(p => p.routeLegId === leg.id));
let totalDistance = 0;
if (game.locationLat && game.locationLng) {
let prevLat = game.locationLat;
let prevLng = game.locationLng;
for (const leg of routeLegs) {
if (leg.locationLat && leg.locationLng) {
const R = 6371;
const dLat = (leg.locationLat - prevLat) * Math.PI / 180;
const dLng = (leg.locationLng - prevLng) * Math.PI / 180;
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(prevLat * Math.PI / 180) * Math.cos(leg.locationLat * Math.PI / 180) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
totalDistance += R * c;
prevLat = leg.locationLat;
prevLng = leg.locationLng;
}
}
}
return {
gameId: game.id,
gameName: game.name,
gameStatus: game.status,
gameMaster: game.gameMaster.name,
startDate: game.startDate,
teamId: team.id,
teamName: team.name,
teamStatus: team.status,
routeId: route?.id || null,
routeName: route?.name || null,
routeColor: route?.color || null,
totalLegs: routeLegs.length,
totalDistance: Math.round(totalDistance * 100) / 100,
proofLocations: proofLocations.map(leg => ({
legNumber: leg.sequenceNumber,
description: leg.description,
locationLat: leg.locationLat,
locationLng: leg.locationLng,
hasPhotoProof: photoSubmissions.some(p => p.routeLegId === leg.id)
}))
};
});
res.json(gamesWithDetails);
}
catch (error) {
console.error('Get user games error:', error);
res.status(500).json({ error: 'Failed to get user games' });
}
});
router.delete('/me/location-data', auth_1.authenticate, async (req, res) => {
try {
await index_1.prisma.locationHistory.deleteMany({
where: { userId: req.user.id }
});
res.json({ message: 'Location data deleted' });
}
catch (error) {
console.error('Delete location data error:', error);
res.status(500).json({ error: 'Failed to delete location data' });
}
});
router.delete('/me/account', auth_1.authenticate, async (req, res) => {
try {
await index_1.prisma.user.delete({
where: { id: req.user.id }
});
res.json({ message: 'Account deleted' });
}
catch (error) {
console.error('Delete account error:', error);
res.status(500).json({ error: 'Failed to delete account' });
}
});
exports.default = router;

View file

@ -1,7 +1,7 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.default = setupSocket; exports.default = setupSocket;
const index_js_1 = require("../index.js"); const index_1 = require("../index");
function setupSocket(io) { function setupSocket(io) {
io.on('connection', (socket) => { io.on('connection', (socket) => {
console.log('Client connected:', socket.id); console.log('Client connected:', socket.id);
@ -13,7 +13,7 @@ function setupSocket(io) {
socket.leave(`game:${gameId}`); socket.leave(`game:${gameId}`);
}); });
socket.on('team-location', async (data) => { socket.on('team-location', async (data) => {
await index_js_1.prisma.team.update({ await index_1.prisma.team.update({
where: { id: data.teamId }, where: { id: data.teamId },
data: { lat: data.lat, lng: data.lng } data: { lat: data.lat, lng: data.lng }
}); });
@ -24,7 +24,7 @@ function setupSocket(io) {
}); });
}); });
socket.on('chat-message', async (data) => { socket.on('chat-message', async (data) => {
const chatMessage = await index_js_1.prisma.chatMessage.create({ const chatMessage = await index_1.prisma.chatMessage.create({
data: { data: {
gameId: data.gameId, gameId: data.gameId,
teamId: data.teamId, teamId: data.teamId,

View file

@ -23,7 +23,7 @@
"devDependencies": { "devDependencies": {
"@types/bcryptjs": "^2.4.6", "@types/bcryptjs": "^2.4.6",
"@types/cors": "^2.8.17", "@types/cors": "^2.8.17",
"@types/express": "^5.0.1", "@types/express": "^4.17.21",
"@types/jsonwebtoken": "^9.0.7", "@types/jsonwebtoken": "^9.0.7",
"@types/multer": "^1.4.12", "@types/multer": "^1.4.12",
"@types/node": "^22.15.21", "@types/node": "^22.15.21",
@ -215,21 +215,22 @@
} }
}, },
"node_modules/@types/express": { "node_modules/@types/express": {
"version": "5.0.6", "version": "4.17.21",
"resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz", "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz",
"integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==", "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@types/body-parser": "*", "@types/body-parser": "*",
"@types/express-serve-static-core": "^5.0.0", "@types/express-serve-static-core": "^4.17.33",
"@types/serve-static": "^2" "@types/qs": "*",
"@types/serve-static": "*"
} }
}, },
"node_modules/@types/express-serve-static-core": { "node_modules/@types/express-serve-static-core": {
"version": "5.1.1", "version": "4.19.8",
"resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz", "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.8.tgz",
"integrity": "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A==", "integrity": "sha512-02S5fmqeoKzVZCHPZid4b8JH2eM5HzQLZWN2FohQEy/0eXTq8VXZfSN6Pcr3F6N9R/vNrj7cpgbhjie6m/1tCA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {

View file

@ -29,7 +29,7 @@
"devDependencies": { "devDependencies": {
"@types/bcryptjs": "^2.4.6", "@types/bcryptjs": "^2.4.6",
"@types/cors": "^2.8.17", "@types/cors": "^2.8.17",
"@types/express": "^5.0.1", "@types/express": "^4.17.21",
"@types/jsonwebtoken": "^9.0.7", "@types/jsonwebtoken": "^9.0.7",
"@types/multer": "^1.4.12", "@types/multer": "^1.4.12",
"@types/node": "^22.15.21", "@types/node": "^22.15.21",

View file

@ -12,40 +12,58 @@ model User {
email String @unique email String @unique
passwordHash String passwordHash String
name String name String
screenName String?
avatarUrl String?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
games Game[] @relation("GameMaster") games Game[] @relation("GameMaster")
teams TeamMember[] teams TeamMember[]
captainOf Team? @relation("TeamCaptain") captainOf Team? @relation("TeamCaptain")
chatMessages ChatMessage[] chatMessages ChatMessage[]
locationHistory LocationHistory[]
} }
model Game { model Game {
id String @id @default(uuid()) id String @id @default(uuid())
name String name String
description String? description String?
prizeDetails String? prizeDetails String?
visibility Visibility @default(PUBLIC) visibility Visibility @default(PUBLIC)
startDate DateTime? startDate DateTime?
locationLat Float? locationLat Float?
locationLng Float? locationLng Float?
searchRadius Float? searchRadius Float?
rules String? rules String?
status GameStatus @default(DRAFT) randomizeRoutes Boolean @default(false)
inviteCode String? @unique status GameStatus @default(DRAFT)
createdAt DateTime @default(now()) inviteCode String? @unique
updatedAt DateTime @updatedAt createdAt DateTime @default(now())
gameMasterId String updatedAt DateTime @updatedAt
gameMaster User @relation("GameMaster", fields: [gameMasterId], references: [id]) gameMasterId String
legs Leg[] gameMaster User @relation("GameMaster", fields: [gameMasterId], references: [id])
teams Team[] routes Route[]
chatMessages ChatMessage[] teams Team[]
chatMessages ChatMessage[]
locationHistory LocationHistory[]
} }
model Leg { model Route {
id String @id @default(uuid())
gameId String
game Game @relation(fields: [gameId], references: [id], onDelete: Cascade)
name String
description String?
color String @default("#3498db")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
routeLegs RouteLeg[]
teamRoutes TeamRoute[]
}
model RouteLeg {
id String @id @default(uuid()) id String @id @default(uuid())
gameId String routeId String
game Game @relation(fields: [gameId], references: [id], onDelete: Cascade) route Route @relation(fields: [routeId], references: [id], onDelete: Cascade)
sequenceNumber Int sequenceNumber Int
description String description String
conditionType String @default("photo") conditionType String @default("photo")
@ -53,7 +71,6 @@ model Leg {
locationLat Float? locationLat Float?
locationLng Float? locationLng Float?
timeLimit Int? timeLimit Int?
teams Team[]
} }
model Team { model Team {
@ -61,19 +78,30 @@ model Team {
gameId String gameId String
game Game @relation(fields: [gameId], references: [id], onDelete: Cascade) game Game @relation(fields: [gameId], references: [id], onDelete: Cascade)
name String name String
captainId String? @unique captainId String? @unique
captain User? @relation("TeamCaptain", fields: [captainId], references: [id]) captain User? @relation("TeamCaptain", fields: [captainId], references: [id])
currentLegId String? currentLegIndex Int @default(0)
currentLeg Leg? @relation(fields: [currentLegId], references: [id]) status TeamStatus @default(ACTIVE)
status TeamStatus @default(ACTIVE) totalTimeDeduction Int @default(0)
totalTimeDeduction Int @default(0)
lat Float? lat Float?
lng Float? lng Float?
rank Int? rank Int?
createdAt DateTime @default(now()) createdAt DateTime @default(now())
members TeamMember[] members TeamMember[]
photoSubmissions PhotoSubmission[] photoSubmissions PhotoSubmission[]
chatMessages ChatMessage[] chatMessages ChatMessage[]
teamRoutes TeamRoute[]
}
model TeamRoute {
id String @id @default(uuid())
teamId String
team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
routeId String
route Route @relation(fields: [routeId], references: [id])
assignedAt DateTime @default(now())
@@unique([teamId])
} }
model TeamMember { model TeamMember {
@ -91,7 +119,8 @@ model PhotoSubmission {
id String @id @default(uuid()) id String @id @default(uuid())
teamId String teamId String
team Team @relation(fields: [teamId], references: [id], onDelete: Cascade) team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
legId String routeId String
routeLegId String
photoUrl String photoUrl String
approved Boolean @default(false) approved Boolean @default(false)
submittedAt DateTime @default(now()) submittedAt DateTime @default(now())
@ -109,6 +138,19 @@ model ChatMessage {
sentAt DateTime @default(now()) sentAt DateTime @default(now())
} }
model LocationHistory {
id String @id @default(uuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
gameId String
game Game @relation(fields: [gameId], references: [id], onDelete: Cascade)
teamId String
lat Float
lng Float
accuracy Float?
recordedAt DateTime @default(now())
}
enum Visibility { enum Visibility {
PUBLIC PUBLIC
PRIVATE PRIVATE

View file

@ -6,7 +6,8 @@ import { PrismaClient } from '@prisma/client';
import authRoutes from './routes/auth'; import authRoutes from './routes/auth';
import gameRoutes from './routes/games'; import gameRoutes from './routes/games';
import teamRoutes from './routes/teams'; import teamRoutes from './routes/teams';
import legRoutes from './routes/legs'; import routeRoutes from './routes/routes';
import userRoutes from './routes/users';
import uploadRoutes from './routes/upload'; import uploadRoutes from './routes/upload';
import setupSocket from './socket/index'; import setupSocket from './socket/index';
@ -28,7 +29,8 @@ app.use('/uploads', express.static('uploads'));
app.use('/api/auth', authRoutes); app.use('/api/auth', authRoutes);
app.use('/api/games', gameRoutes); app.use('/api/games', gameRoutes);
app.use('/api/teams', teamRoutes); app.use('/api/teams', teamRoutes);
app.use('/api/legs', legRoutes); app.use('/api/routes', routeRoutes);
app.use('/api/users', userRoutes);
app.use('/api/upload', uploadRoutes); app.use('/api/upload', uploadRoutes);
app.get('/api/health', (req, res) => { app.get('/api/health', (req, res) => {

View file

@ -25,7 +25,7 @@ router.get('/', async (req: AuthRequest, res: Response) => {
where, where,
include: { include: {
gameMaster: { select: { id: true, name: true } }, gameMaster: { select: { id: true, name: true } },
_count: { select: { teams: true, legs: true } } _count: { select: { teams: true, routes: true } }
}, },
orderBy: { createdAt: 'desc' } orderBy: { createdAt: 'desc' }
}); });
@ -42,7 +42,7 @@ router.get('/my-games', authenticate, async (req: AuthRequest, res: Response) =>
const games = await prisma.game.findMany({ const games = await prisma.game.findMany({
where: { gameMasterId: req.user!.id }, where: { gameMasterId: req.user!.id },
include: { include: {
_count: { select: { teams: true, legs: true } } _count: { select: { teams: true, routes: true } }
}, },
orderBy: { createdAt: 'desc' } orderBy: { createdAt: 'desc' }
}); });
@ -62,11 +62,23 @@ router.get('/:id', async (req: AuthRequest, res: Response) => {
where: { id: id as string }, where: { id: id as string },
include: { include: {
gameMaster: { select: { id: true, name: true } }, gameMaster: { select: { id: true, name: true } },
legs: { orderBy: { sequenceNumber: 'asc' } }, routes: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
},
teams: { teams: {
include: { include: {
members: { include: { user: { select: { id: true, name: true, email: true } } } }, members: { include: { user: { select: { id: true, name: true, email: true } } } },
currentLeg: true teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
} }
} }
} }
@ -98,7 +110,7 @@ router.post('/', authenticate, async (req: AuthRequest, res: Response) => {
try { try {
const { const {
name, description, prizeDetails, visibility, startDate, name, description, prizeDetails, visibility, startDate,
locationLat, locationLng, searchRadius, rules locationLat, locationLng, searchRadius, rules, randomizeRoutes
} = req.body; } = req.body;
if (!name) { if (!name) {
@ -122,6 +134,7 @@ router.post('/', authenticate, async (req: AuthRequest, res: Response) => {
locationLng, locationLng,
searchRadius, searchRadius,
rules: rules ? JSON.stringify(rules) : null, rules: rules ? JSON.stringify(rules) : null,
randomizeRoutes: randomizeRoutes || false,
gameMasterId: req.user!.id, gameMasterId: req.user!.id,
inviteCode inviteCode
} }
@ -139,7 +152,7 @@ router.put('/:id', authenticate, async (req: AuthRequest, res: Response) => {
const id = req.params.id as string; const id = req.params.id as string;
const { const {
name, description, prizeDetails, visibility, startDate, name, description, prizeDetails, visibility, startDate,
locationLat, locationLng, searchRadius, rules, status locationLat, locationLng, searchRadius, rules, status, randomizeRoutes
} = req.body; } = req.body;
const game = await prisma.game.findUnique({ where: { id } }); const game = await prisma.game.findUnique({ where: { id } });
@ -163,6 +176,7 @@ router.put('/:id', authenticate, async (req: AuthRequest, res: Response) => {
locationLng, locationLng,
searchRadius, searchRadius,
rules: rules ? JSON.stringify(rules) : undefined, rules: rules ? JSON.stringify(rules) : undefined,
randomizeRoutes,
status status
} }
}); });
@ -202,8 +216,8 @@ router.post('/:id/publish', authenticate, async (req: AuthRequest, res: Response
const game = await prisma.game.findUnique({ const game = await prisma.game.findUnique({
where: { id: id as string }, where: { id: id as string },
include: { legs: true } include: { routes: { include: { routeLegs: true } } }
}) as any; });
if (!game) { if (!game) {
return res.status(404).json({ error: 'Game not found' }); return res.status(404).json({ error: 'Game not found' });
@ -213,8 +227,35 @@ router.post('/:id/publish', authenticate, async (req: AuthRequest, res: Response
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
if (!game.legs || game.legs.length === 0) { if (!game.routes || game.routes.length === 0) {
return res.status(400).json({ error: 'Game must have at least one leg' }); return res.status(400).json({ error: 'Game must have at least one route' });
}
const hasValidRoute = game.routes.some(route => route.routeLegs.length > 0);
if (!hasValidRoute) {
return res.status(400).json({ error: 'At least one route must have legs' });
}
if (game.randomizeRoutes) {
const teams = await prisma.team.findMany({
where: { gameId: id as string }
});
const shuffledRoutes = [...game.routes].sort(() => Math.random() - 0.5);
for (let i = 0; i < teams.length; i++) {
const routeIndex = i % game.routes.length;
await prisma.teamRoute.upsert({
where: { teamId: teams[i].id },
create: {
teamId: teams[i].id,
routeId: shuffledRoutes[routeIndex].id
},
update: {
routeId: shuffledRoutes[routeIndex].id
}
});
}
} }
const updated = await prisma.game.update({ const updated = await prisma.game.update({

View file

@ -1,175 +0,0 @@
import { Router, Response } from 'express';
import { prisma } from '../index';
import { authenticate, AuthRequest } from '../middleware/auth';
const router = Router();
router.get('/game/:gameId', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { gameId } = req.params;
const game = await prisma.game.findUnique({
where: { id: gameId },
include: { legs: { orderBy: { sequenceNumber: 'asc' } } }
});
if (!game) {
return res.status(404).json({ error: 'Game not found' });
}
if (game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
res.json(game.legs);
} catch (error) {
console.error('Get legs error:', error);
res.status(500).json({ error: 'Failed to get legs' });
}
});
router.post('/game/:gameId', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { gameId } = req.params;
const { description, conditionType, conditionDetails, locationLat, locationLng, timeLimit } = req.body;
const game = await prisma.game.findUnique({
where: { id: gameId },
include: { legs: true }
});
if (!game) {
return res.status(404).json({ error: 'Game not found' });
}
if (game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const maxSequence = game.legs.reduce((max: number, leg: { sequenceNumber: number }) => Math.max(max, leg.sequenceNumber), 0);
const leg = await prisma.leg.create({
data: {
gameId,
sequenceNumber: maxSequence + 1,
description,
conditionType: conditionType || 'photo',
conditionDetails,
locationLat,
locationLng,
timeLimit
}
});
res.json(leg);
} catch (error) {
console.error('Create leg error:', error);
res.status(500).json({ error: 'Failed to create leg' });
}
});
router.put('/:legId', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { legId } = req.params;
const { description, conditionType, conditionDetails, locationLat, locationLng, timeLimit } = req.body;
const leg = await prisma.leg.findUnique({
where: { id: legId },
include: { game: true }
});
if (!leg) {
return res.status(404).json({ error: 'Leg not found' });
}
if (leg.game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const updated = await prisma.leg.update({
where: { id: legId },
data: {
description,
conditionType,
conditionDetails,
locationLat,
locationLng,
timeLimit
}
});
res.json(updated);
} catch (error) {
console.error('Update leg error:', error);
res.status(500).json({ error: 'Failed to update leg' });
}
});
router.delete('/:legId', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { legId } = req.params;
const leg = await prisma.leg.findUnique({
where: { id: legId },
include: { game: true }
});
if (!leg) {
return res.status(404).json({ error: 'Leg not found' });
}
if (leg.game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
await prisma.leg.delete({ where: { id: legId } });
res.json({ message: 'Leg deleted' });
} catch (error) {
console.error('Delete leg error:', error);
res.status(500).json({ error: 'Failed to delete leg' });
}
});
router.post('/:legId/photo', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { legId } = req.params;
const { teamId, photoUrl } = req.body;
if (!teamId || !photoUrl) {
return res.status(400).json({ error: 'Team ID and photo URL are required' });
}
const leg = await prisma.leg.findUnique({
where: { id: legId },
include: { game: true }
});
if (!leg) {
return res.status(404).json({ error: 'Leg not found' });
}
const team = await prisma.team.findUnique({
where: { id: teamId }
});
if (!team || team.gameId !== leg.gameId) {
return res.status(403).json({ error: 'Team not in this game' });
}
const submission = await prisma.photoSubmission.create({
data: {
teamId,
legId,
photoUrl
}
});
res.json(submission);
} catch (error) {
console.error('Submit photo error:', error);
res.status(500).json({ error: 'Failed to submit photo' });
}
});
export default router;

View file

@ -0,0 +1,398 @@
import { Router, Response } from 'express';
import { prisma } from '../index';
import { authenticate, AuthRequest } from '../middleware/auth';
const router = Router();
router.get('/game/:gameId', async (req: AuthRequest, res: Response) => {
try {
const { gameId } = req.params;
const routes = await prisma.route.findMany({
where: { gameId: gameId as string },
include: {
routeLegs: {
orderBy: { sequenceNumber: 'asc' }
},
_count: { select: { teamRoutes: true } }
},
orderBy: { createdAt: 'asc' }
});
res.json(routes);
} catch (error) {
console.error('List routes error:', error);
res.status(500).json({ error: 'Failed to list routes' });
}
});
router.get('/:id', async (req: AuthRequest, res: Response) => {
try {
const { id } = req.params;
const route = await prisma.route.findUnique({
where: { id: id as string },
include: {
routeLegs: {
orderBy: { sequenceNumber: 'asc' }
},
teamRoutes: {
include: {
team: {
include: {
members: { include: { user: { select: { id: true, name: true } } } }
}
}
}
}
}
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
res.json(route);
} catch (error) {
console.error('Get route error:', error);
res.status(500).json({ error: 'Failed to get route' });
}
});
router.post('/', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { gameId, name, description, color } = req.body;
if (!gameId || !name) {
return res.status(400).json({ error: 'Game ID and name are required' });
}
const game = await prisma.game.findUnique({ where: { id: gameId } });
if (!game) {
return res.status(404).json({ error: 'Game not found' });
}
if (game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const route = await prisma.route.create({
data: {
gameId,
name,
description,
color: color || '#3498db'
},
include: {
routeLegs: true
}
});
res.json(route);
} catch (error) {
console.error('Create route error:', error);
res.status(500).json({ error: 'Failed to create route' });
}
});
router.put('/:id', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { id } = req.params;
const { name, description, color } = req.body;
const route = await prisma.route.findUnique({
where: { id: id as string },
include: { game: true }
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
if (route.game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const updated = await prisma.route.update({
where: { id: id as string },
data: {
name: name || route.name,
description: description !== undefined ? description : route.description,
color: color || route.color
},
include: {
routeLegs: {
orderBy: { sequenceNumber: 'asc' }
}
}
});
res.json(updated);
} catch (error) {
console.error('Update route error:', error);
res.status(500).json({ error: 'Failed to update route' });
}
});
router.delete('/:id', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { id } = req.params;
const route = await prisma.route.findUnique({
where: { id: id as string },
include: { game: true }
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
if (route.game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
await prisma.route.delete({ where: { id: id as string } });
res.json({ message: 'Route deleted' });
} catch (error) {
console.error('Delete route error:', error);
res.status(500).json({ error: 'Failed to delete route' });
}
});
router.post('/:id/legs', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { id } = req.params;
const {
description, conditionType, conditionDetails,
locationLat, locationLng, timeLimit
} = req.body;
const route = await prisma.route.findUnique({
where: { id: id as string },
include: {
game: true,
routeLegs: true
}
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
if (route.game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const maxSequence = route.routeLegs.length > 0
? Math.max(...route.routeLegs.map(l => l.sequenceNumber))
: 0;
const routeLeg = await prisma.routeLeg.create({
data: {
routeId: id as string,
sequenceNumber: maxSequence + 1,
description: description || '',
conditionType: conditionType || 'photo',
conditionDetails,
locationLat,
locationLng,
timeLimit
}
});
res.json(routeLeg);
} catch (error) {
console.error('Add route leg error:', error);
res.status(500).json({ error: 'Failed to add leg to route' });
}
});
router.put('/:id/legs/:legId', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { id, legId } = req.params;
const {
description, conditionType, conditionDetails,
locationLat, locationLng, timeLimit, sequenceNumber
} = req.body;
const route = await prisma.route.findUnique({
where: { id: id as string },
include: { game: true }
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
if (route.game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const routeLeg = await prisma.routeLeg.update({
where: { id: legId as string },
data: {
description: description !== undefined ? description : undefined,
conditionType: conditionType !== undefined ? conditionType : undefined,
conditionDetails: conditionDetails !== undefined ? conditionDetails : undefined,
locationLat: locationLat !== undefined ? locationLat : undefined,
locationLng: locationLng !== undefined ? locationLng : undefined,
timeLimit: timeLimit !== undefined ? timeLimit : undefined,
sequenceNumber: sequenceNumber !== undefined ? sequenceNumber : undefined
}
});
res.json(routeLeg);
} catch (error) {
console.error('Update route leg error:', error);
res.status(500).json({ error: 'Failed to update route leg' });
}
});
router.delete('/:id/legs/:legId', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { id, legId } = req.params;
const route = await prisma.route.findUnique({
where: { id: id as string },
include: { game: true }
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
if (route.game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
await prisma.routeLeg.delete({ where: { id: legId as string } });
const remainingLegs = await prisma.routeLeg.findMany({
where: { routeId: id as string },
orderBy: { sequenceNumber: 'asc' }
});
for (let i = 0; i < remainingLegs.length; i++) {
if (remainingLegs[i].sequenceNumber !== i + 1) {
await prisma.routeLeg.update({
where: { id: remainingLegs[i].id },
data: { sequenceNumber: i + 1 }
});
}
}
res.json({ message: 'Leg deleted' });
} catch (error) {
console.error('Delete route leg error:', error);
res.status(500).json({ error: 'Failed to delete route leg' });
}
});
router.post('/:id/legs/:legId/photo', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { id, legId } = req.params;
const { teamId, photoUrl } = req.body;
const route = await prisma.route.findUnique({
where: { id: id as string },
include: { game: true }
});
if (!route) {
return res.status(404).json({ error: 'Route not found' });
}
const routeLeg = await prisma.routeLeg.findFirst({
where: { id: legId as string, routeId: id as string }
});
if (!routeLeg) {
return res.status(404).json({ error: 'Route leg not found' });
}
const member = await prisma.teamMember.findFirst({
where: { teamId, userId: req.user!.id }
});
const team = await prisma.team.findUnique({ where: { id: teamId } });
if (!member && team?.captainId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const submission = await prisma.photoSubmission.create({
data: {
teamId,
routeId: id as string,
routeLegId: legId as string,
photoUrl
}
});
res.json(submission);
} catch (error) {
console.error('Photo submission error:', error);
res.status(500).json({ error: 'Failed to submit photo' });
}
});
router.post('/:id/copy', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { id } = req.params;
const originalRoute = await prisma.route.findUnique({
where: { id: id as string },
include: {
game: true,
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
});
if (!originalRoute) {
return res.status(404).json({ error: 'Route not found' });
}
if (originalRoute.game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const newRoute = await prisma.route.create({
data: {
gameId: originalRoute.gameId,
name: `${originalRoute.name} (Copy)`,
description: originalRoute.description,
color: originalRoute.color
}
});
for (const leg of originalRoute.routeLegs) {
await prisma.routeLeg.create({
data: {
routeId: newRoute.id,
sequenceNumber: leg.sequenceNumber,
description: leg.description,
conditionType: leg.conditionType,
conditionDetails: leg.conditionDetails,
locationLat: leg.locationLat,
locationLng: leg.locationLng,
timeLimit: leg.timeLimit
}
});
}
const fullRoute = await prisma.route.findUnique({
where: { id: newRoute.id },
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
});
res.json(fullRoute);
} catch (error) {
console.error('Copy route error:', error);
res.status(500).json({ error: 'Failed to copy route' });
}
});
export default router;

View file

@ -13,7 +13,15 @@ router.get('/game/:gameId', async (req: AuthRequest, res: Response) => {
include: { include: {
members: { include: { user: { select: { id: true, name: true, email: true } } } }, members: { include: { user: { select: { id: true, name: true, email: true } } } },
captain: { select: { id: true, name: true } }, captain: { select: { id: true, name: true } },
currentLeg: true teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
}, },
orderBy: { createdAt: 'asc' } orderBy: { createdAt: 'asc' }
}); });
@ -73,7 +81,16 @@ router.post('/game/:gameId', authenticate, async (req: AuthRequest, res: Respons
where: { id: team.id }, where: { id: team.id },
include: { include: {
members: { include: { user: { select: { id: true, name: true, email: true } } } }, members: { include: { user: { select: { id: true, name: true, email: true } } } },
captain: { select: { id: true, name: true } } captain: { select: { id: true, name: true } },
teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
} }
}); });
@ -167,6 +184,57 @@ router.post('/:teamId/leave', authenticate, async (req: AuthRequest, res: Respon
} }
}); });
router.post('/:teamId/assign-route', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { teamId } = req.params;
const { routeId } = req.body;
const team = await prisma.team.findUnique({
where: { id: teamId },
include: { game: true, teamRoutes: true }
});
if (!team) {
return res.status(404).json({ error: 'Team not found' });
}
if (team.game.gameMasterId !== req.user!.id) {
return res.status(403).json({ error: 'Not authorized' });
}
const route = await prisma.route.findUnique({
where: { id: routeId }
});
if (!route || route.gameId !== team.gameId) {
return res.status(400).json({ error: 'Invalid route for this game' });
}
await prisma.teamRoute.deleteMany({
where: { teamId }
});
const teamRoute = await prisma.teamRoute.create({
data: {
teamId,
routeId
},
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
});
res.json(teamRoute);
} catch (error) {
console.error('Assign route error:', error);
res.status(500).json({ error: 'Failed to assign route' });
}
});
router.post('/:teamId/advance', authenticate, async (req: AuthRequest, res: Response) => { router.post('/:teamId/advance', authenticate, async (req: AuthRequest, res: Response) => {
try { try {
const { teamId } = req.params; const { teamId } = req.params;
@ -174,8 +242,16 @@ router.post('/:teamId/advance', authenticate, async (req: AuthRequest, res: Resp
const team = await prisma.team.findUnique({ const team = await prisma.team.findUnique({
where: { id: teamId }, where: { id: teamId },
include: { include: {
game: { include: { legs: { orderBy: { sequenceNumber: 'asc' } } } }, game: true,
currentLeg: true teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
} }
}); });
@ -187,28 +263,36 @@ router.post('/:teamId/advance', authenticate, async (req: AuthRequest, res: Resp
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
const legs = team.game.legs; const teamRoute = team.teamRoutes[0];
const currentLeg = team.currentLeg; if (!teamRoute) {
return res.status(400).json({ error: 'Team has no assigned route' });
}
const legs = teamRoute.route.routeLegs;
const currentLegIndex = team.currentLegIndex;
let nextLeg = null; let nextLegIndex = currentLegIndex;
if (currentLeg) { if (currentLegIndex < legs.length - 1) {
const currentIndex = legs.findIndex((l: { id: string }) => l.id === currentLeg.id); nextLegIndex = currentLegIndex + 1;
if (currentIndex < legs.length - 1) {
nextLeg = legs[currentIndex + 1];
}
} else if (legs.length > 0) {
nextLeg = legs[0];
} }
const updated = await prisma.team.update({ const updated = await prisma.team.update({
where: { id: teamId }, where: { id: teamId },
data: { data: {
currentLegId: nextLeg?.id || null, currentLegIndex: nextLegIndex,
status: nextLeg ? 'ACTIVE' : 'FINISHED' status: nextLegIndex >= legs.length - 1 ? 'FINISHED' : 'ACTIVE'
}, },
include: { include: {
members: { include: { user: { select: { id: true, name: true } } } }, members: { include: { user: { select: { id: true, name: true } } } },
currentLeg: true teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
} }
}); });
@ -237,7 +321,7 @@ router.post('/:teamId/deduct', authenticate, async (req: AuthRequest, res: Respo
return res.status(403).json({ error: 'Not authorized' }); return res.status(403).json({ error: 'Not authorized' });
} }
const deduction = seconds || team.game.timeDeductionPenalty || 60; const deduction = seconds || 60;
const updated = await prisma.team.update({ const updated = await prisma.team.update({
where: { id: teamId }, where: { id: teamId },
@ -322,8 +406,16 @@ router.get('/:teamId', authenticate, async (req: AuthRequest, res: Response) =>
include: { include: {
members: { include: { user: { select: { id: true, name: true, email: true } } } }, members: { include: { user: { select: { id: true, name: true, email: true } } } },
captain: { select: { id: true, name: true } }, captain: { select: { id: true, name: true } },
currentLeg: true, game: { include: { routes: { include: { routeLegs: { orderBy: { sequenceNumber: 'asc' } } } } } },
game: { include: { legs: { orderBy: { sequenceNumber: 'asc' } } } } teamRoutes: {
include: {
route: {
include: {
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
}
}
}
}
} }
}); });

229
backend/src/routes/users.ts Normal file
View file

@ -0,0 +1,229 @@
import { Router, Response } from 'express';
import { prisma } from '../index';
import { authenticate, AuthRequest } from '../middleware/auth';
const router = Router();
router.get('/me', authenticate, async (req: AuthRequest, res: Response) => {
try {
const user = await prisma.user.findUnique({
where: { id: req.user!.id },
select: {
id: true,
email: true,
name: true,
screenName: true,
avatarUrl: true,
createdAt: true
}
});
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
} catch (error) {
console.error('Get user error:', error);
res.status(500).json({ error: 'Failed to get user' });
}
});
router.put('/me', authenticate, async (req: AuthRequest, res: Response) => {
try {
const { name, screenName, avatarUrl } = req.body;
const updated = await prisma.user.update({
where: { id: req.user!.id },
data: {
name: name || undefined,
screenName: screenName !== undefined ? screenName || null : undefined,
avatarUrl: avatarUrl !== undefined ? avatarUrl || null : undefined
},
select: {
id: true,
email: true,
name: true,
screenName: true,
avatarUrl: true,
createdAt: true
}
});
res.json(updated);
} catch (error) {
console.error('Update user error:', error);
res.status(500).json({ error: 'Failed to update user' });
}
});
router.get('/me/location-history', authenticate, async (req: AuthRequest, res: Response) => {
try {
const locations = await prisma.locationHistory.findMany({
where: { userId: req.user!.id },
include: {
game: {
select: { id: true, name: true }
}
},
orderBy: { recordedAt: 'desc' }
});
const games = await prisma.game.findMany({
where: {
teams: {
some: {
members: {
some: { userId: req.user!.id }
}
}
}
},
select: { id: true, name: true }
});
const locationByGame = games.map(game => {
const gameLocations = locations.filter(l => l.gameId === game.id);
return {
game: game,
locations: gameLocations,
locationCount: gameLocations.length
};
}).filter(g => g.locationCount > 0);
res.json({
totalLocations: locations.length,
byGame: locationByGame
});
} catch (error) {
console.error('Get location history error:', error);
res.status(500).json({ error: 'Failed to get location history' });
}
});
router.get('/me/games', authenticate, async (req: AuthRequest, res: Response) => {
try {
const memberships = await prisma.teamMember.findMany({
where: { userId: req.user!.id },
include: {
team: {
include: {
game: {
select: {
id: true,
name: true,
status: true,
startDate: true,
locationLat: true,
locationLng: true,
gameMasterId: true,
gameMaster: { select: { name: true } }
}
},
teamRoutes: {
include: {
route: {
include: {
routeLegs: {
orderBy: { sequenceNumber: 'asc' }
}
}
}
}
},
photoSubmissions: true
}
}
}
});
const gamesWithDetails = memberships.map(m => {
const team = m.team;
const game = team.game;
const teamRoute = team.teamRoutes[0];
const route = teamRoute?.route;
const photoSubmissions = team.photoSubmissions;
const routeLegs = route?.routeLegs || [];
const proofLocations = routeLegs.filter(leg =>
photoSubmissions.some(p => p.routeLegId === leg.id)
);
let totalDistance = 0;
if (game.locationLat && game.locationLng) {
let prevLat = game.locationLat;
let prevLng = game.locationLng;
for (const leg of routeLegs) {
if (leg.locationLat && leg.locationLng) {
const R = 6371;
const dLat = (leg.locationLat - prevLat) * Math.PI / 180;
const dLng = (leg.locationLng - prevLng) * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(prevLat * Math.PI / 180) * Math.cos(leg.locationLat * Math.PI / 180) *
Math.sin(dLng/2) * Math.sin(dLng/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
totalDistance += R * c;
prevLat = leg.locationLat;
prevLng = leg.locationLng;
}
}
}
return {
gameId: game.id,
gameName: game.name,
gameStatus: game.status,
gameMaster: game.gameMaster.name,
startDate: game.startDate,
teamId: team.id,
teamName: team.name,
teamStatus: team.status,
routeId: route?.id || null,
routeName: route?.name || null,
routeColor: route?.color || null,
totalLegs: routeLegs.length,
totalDistance: Math.round(totalDistance * 100) / 100,
proofLocations: proofLocations.map(leg => ({
legNumber: leg.sequenceNumber,
description: leg.description,
locationLat: leg.locationLat,
locationLng: leg.locationLng,
hasPhotoProof: photoSubmissions.some(p => p.routeLegId === leg.id)
}))
};
});
res.json(gamesWithDetails);
} catch (error) {
console.error('Get user games error:', error);
res.status(500).json({ error: 'Failed to get user games' });
}
});
router.delete('/me/location-data', authenticate, async (req: AuthRequest, res: Response) => {
try {
await prisma.locationHistory.deleteMany({
where: { userId: req.user!.id }
});
res.json({ message: 'Location data deleted' });
} catch (error) {
console.error('Delete location data error:', error);
res.status(500).json({ error: 'Failed to delete location data' });
}
});
router.delete('/me/account', authenticate, async (req: AuthRequest, res: Response) => {
try {
await prisma.user.delete({
where: { id: req.user!.id }
});
res.json({ message: 'Account deleted' });
} catch (error) {
console.error('Delete account error:', error);
res.status(500).json({ error: 'Failed to delete account' });
}
});
export default router;

View file

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

View file

@ -11,6 +11,7 @@ const name = ref('');
const description = ref(''); const description = ref('');
const prizeDetails = ref(''); const prizeDetails = ref('');
const visibility = ref<'PUBLIC' | 'PRIVATE'>('PUBLIC'); const visibility = ref<'PUBLIC' | 'PRIVATE'>('PUBLIC');
const randomizeRoutes = ref(false);
const startDate = ref(''); const startDate = ref('');
const locationLat = ref<number | null>(null); const locationLat = ref<number | null>(null);
const locationLng = ref<number | null>(null); const locationLng = ref<number | null>(null);
@ -80,7 +81,8 @@ async function handleSubmit() {
locationLat: locationLat.value || undefined, locationLat: locationLat.value || undefined,
locationLng: locationLng.value || undefined, locationLng: locationLng.value || undefined,
searchRadius: searchRadius.value, 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`); router.push(`/games/${response.data.id}/edit`);
@ -127,6 +129,12 @@ onUnmounted(() => {
<option value="PUBLIC">Public</option> <option value="PUBLIC">Public</option>
<option value="PRIVATE">Private (Invite Only)</option> <option value="PRIVATE">Private (Invite Only)</option>
</select> </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> <label for="startDate">Start Date & Time</label>
<input id="startDate" v-model="startDate" type="datetime-local" /> <input id="startDate" v-model="startDate" type="datetime-local" />
@ -154,7 +162,7 @@ onUnmounted(() => {
<h2>Game Rules</h2> <h2>Game Rules</h2>
<p><small>Add rules for participants to follow during the game</small></p> <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}`"> <label :for="`rule-${index}`">
Rule {{ index + 1 }} Rule {{ index + 1 }}
<input <input

View file

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

View file

@ -1,24 +1,41 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'; import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router'; import { useRoute } from 'vue-router';
import L from 'leaflet'; import L from 'leaflet';
import 'leaflet/dist/leaflet.css'; import 'leaflet/dist/leaflet.css';
import type { Game, Leg } from '../types'; import type { Game, Route } from '../types';
import { gameService, legService } from '../services/api'; import { gameService, routeService } from '../services/api';
const route = useRoute(); const route = useRoute();
const router = useRouter();
const game = ref<Game | null>(null); 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 loading = ref(true);
const saving = ref(false); const saving = ref(false);
const gameId = computed(() => route.params.id as string); 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); const mapContainer = ref<HTMLDivElement | null>(null);
let map: L.Map | 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({ const newLeg = ref({
description: '', description: '',
@ -29,12 +46,52 @@ const newLeg = ref({
timeLimit: 30 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() { async function loadGame() {
loading.value = true; loading.value = true;
try { try {
const response = await gameService.get(gameId.value); const response = await gameService.get(gameId.value);
game.value = response.data; 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) { } catch (err) {
console.error('Failed to load game:', err); console.error('Failed to load game:', err);
} finally { } finally {
@ -43,7 +100,7 @@ async function loadGame() {
} }
function initMap() { function initMap() {
if (!mapContainer.value) return; if (!mapContainer.value || map) return;
const center = game.value?.locationLat && game.value?.locationLng const center = game.value?.locationLat && game.value?.locationLng
? [game.value.locationLat, game.value.locationLng] as [number, number] ? [game.value.locationLat, game.value.locationLng] as [number, number]
@ -64,30 +121,109 @@ function initMap() {
}).addTo(map); }).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) => { map.on('click', (e: L.LeafletMouseEvent) => {
newLeg.value.locationLat = e.latlng.lat; newLeg.value.locationLat = e.latlng.lat;
newLeg.value.locationLng = e.latlng.lng; 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() { async function addLeg() {
if (!newLeg.value.description) { if (!selectedRouteId.value || !newLeg.value.description) {
alert('Please enter a description'); alert('Please enter a description');
return; return;
} }
saving.value = true; saving.value = true;
try { try {
const response = await legService.create(gameId.value, { const response = await routeService.addLeg(selectedRouteId.value, {
description: newLeg.value.description, description: newLeg.value.description,
conditionType: newLeg.value.conditionType, conditionType: newLeg.value.conditionType,
conditionDetails: newLeg.value.conditionDetails || undefined, conditionDetails: newLeg.value.conditionDetails || undefined,
@ -96,7 +232,11 @@ async function addLeg() {
timeLimit: newLeg.value.timeLimit 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 = { newLeg.value = {
description: '', description: '',
@ -107,18 +247,7 @@ async function addLeg() {
timeLimit: 30 timeLimit: 30
}; };
if (map) { updateMapMarkers();
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);
}
});
}
} catch (err) { } catch (err) {
alert('Failed to add leg'); alert('Failed to add leg');
} finally { } finally {
@ -130,8 +259,14 @@ async function deleteLeg(legId: string) {
if (!confirm('Are you sure you want to delete this leg?')) return; if (!confirm('Are you sure you want to delete this leg?')) return;
try { try {
await legService.delete(legId); await routeService.deleteLeg(selectedRouteId.value!, legId);
legs.value = legs.value.filter(l => l.id !== 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) { } catch (err) {
alert('Failed to delete leg'); alert('Failed to delete leg');
} }
@ -148,14 +283,14 @@ function calculateDistance(lat1: number, lon1: number, lat2: number, lon2: numbe
return R * c; return R * c;
} }
function getTotalDistance(): number { function getRouteDistance(route: Route): number {
if (!game.value?.locationLat || !game.value?.locationLng || legs.value.length === 0) return 0; if (!game.value?.locationLat || !game.value?.locationLng || !route.routeLegs?.length) return 0;
let total = 0; let total = 0;
let prevLat = game.value.locationLat; let prevLat = game.value.locationLat;
let prevLng = game.value.locationLng; let prevLng = game.value.locationLng;
for (const leg of legs.value) { for (const leg of route.routeLegs) {
if (leg.locationLat && leg.locationLng) { if (leg.locationLat && leg.locationLng) {
total += calculateDistance(prevLat, prevLng, leg.locationLat, leg.locationLng); total += calculateDistance(prevLat, prevLng, leg.locationLat, leg.locationLng);
prevLat = leg.locationLat; prevLat = leg.locationLat;
@ -166,9 +301,35 @@ function getTotalDistance(): number {
return total; 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(() => { onMounted(() => {
loadGame().then(() => { 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"> <div class="grid">
<article> <article>
<h2>Legs ({{ legs.length }})</h2> <h2>Routes ({{ routes.length }})</h2>
<p><small>Total route distance: {{ getTotalDistance().toFixed(2) }} km</small></p> <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"> <div class="leg-header">
<h3>Leg {{ index + 1 }}</h3> <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> </div>
<p>{{ leg.description }}</p> <p>{{ leg.description }}</p>
<footer> <footer>
<small> <small>
Type: {{ leg.conditionType }} {{ leg.conditionType }}
<span v-if="leg.timeLimit"> · {{ leg.timeLimit }} min</span> <span v-if="leg.timeLimit"> · {{ leg.timeLimit }} min</span>
<span v-if="leg.locationLat && leg.locationLng"> <span v-if="leg.locationLat && leg.locationLng">
· {{ leg.locationLat.toFixed(4) }}, {{ leg.locationLng.toFixed(4) }} · {{ leg.locationLat.toFixed(4) }}, {{ leg.locationLng.toFixed(4) }}
</span> </span>
</small> </small>
</footer> </footer>
</article> </div>
<p v-else>No legs added yet</p> <p v-else>No legs in this route yet.</p>
</article>
<article> <h3>Add Leg</h3>
<h2>Add New Leg</h2>
<div ref="mapContainer" class="map-container"></div> <div ref="mapContainer" class="map-container"></div>
<p><small>Click on map to set location</small></p> <p><small>Click on map to set location</small></p>
@ -256,6 +499,10 @@ onUnmounted(() => {
</button> </button>
</form> </form>
</article> </article>
<article v-else>
<p>Select a route or create a new one to start adding legs.</p>
</article>
</div> </div>
</template> </template>
</main> </main>
@ -268,14 +515,56 @@ onUnmounted(() => {
margin-bottom: 0.5rem; 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; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
margin-bottom: 0.5rem; gap: 1rem;
} }
.leg-header h3 { .route-header h3, .leg-header h3 {
margin: 0; 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> </style>

View file

@ -5,14 +5,15 @@ import { io, Socket } from 'socket.io-client';
import L from 'leaflet'; import L from 'leaflet';
import 'leaflet/dist/leaflet.css'; import 'leaflet/dist/leaflet.css';
import { useAuthStore } from '../stores/auth'; import { useAuthStore } from '../stores/auth';
import type { Game, Team, ChatMessage } from '../types'; import type { Game, Team, ChatMessage, Route } from '../types';
import { gameService, teamService } from '../services/api'; import { gameService, teamService, routeService } from '../services/api';
const route = useRoute(); const route = useRoute();
const authStore = useAuthStore(); const authStore = useAuthStore();
const game = ref<Game | null>(null); const game = ref<Game | null>(null);
const teams = ref<Team[]>([]); const teams = ref<Team[]>([]);
const routes = ref<Route[]>([]);
const chatMessages = ref<ChatMessage[]>([]); const chatMessages = ref<ChatMessage[]>([]);
const loading = ref(true); const loading = ref(true);
@ -28,12 +29,14 @@ const selectedTeam = ref<Team | null>(null);
async function loadGame() { async function loadGame() {
loading.value = true; loading.value = true;
try { try {
const [gameRes, teamsRes] = await Promise.all([ const [gameRes, teamsRes, routesRes] = await Promise.all([
gameService.get(gameId.value), gameService.get(gameId.value),
teamService.getByGame(gameId.value) teamService.getByGame(gameId.value),
routeService.getByGame(gameId.value)
]); ]);
game.value = gameRes.data; game.value = gameRes.data;
teams.value = teamsRes.data; teams.value = teamsRes.data;
routes.value = routesRes.data;
} catch (err) { } catch (err) {
console.error('Failed to load game:', err); console.error('Failed to load game:', err);
} finally { } finally {
@ -57,9 +60,35 @@ function initMap() {
fillOpacity: 0.1 fillOpacity: 0.1
}).addTo(map); }).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 => { teams.value.forEach(team => {
if (team.lat && team.lng) { 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!) .addTo(map!)
.bindPopup(team.name); .bindPopup(team.name);
teamMarkers[team.id] = marker; teamMarkers[team.id] = marker;
@ -196,7 +225,8 @@ onUnmounted(() => {
<footer> <footer>
<small> <small>
{{ team.members?.length || 0 }} members · {{ 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> <span v-if="team.totalTimeDeduction"> · -{{ team.totalTimeDeduction }}s</span>
</small> </small>
</footer> </footer>

View file

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

View file

@ -68,7 +68,7 @@ onMounted(() => {
<h3>{{ game.name }}</h3> <h3>{{ game.name }}</h3>
<p v-if="game.description">{{ game.description.slice(0, 100) }}...</p> <p v-if="game.description">{{ game.description.slice(0, 100) }}...</p>
<footer> <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> <small v-if="game.startDate">{{ new Date(game.startDate).toLocaleDateString() }}</small>
</footer> </footer>
</RouterLink> </RouterLink>

View file

@ -5,7 +5,7 @@ import { io, Socket } from 'socket.io-client';
import L from 'leaflet'; import L from 'leaflet';
import 'leaflet/dist/leaflet.css'; import 'leaflet/dist/leaflet.css';
import { useAuthStore } from '../stores/auth'; 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'; import { teamService, uploadService } from '../services/api';
const route = useRoute(); const route = useRoute();
@ -28,22 +28,27 @@ const showPhotoUpload = ref(false);
const photoFile = ref<File | null>(null); const photoFile = ref<File | null>(null);
const uploading = ref(false); const uploading = ref(false);
const currentLegIndex = computed(() => { const currentRoute = computed<Route | null>(() => {
if (!team.value?.currentLegId || !game.value?.legs) return -1; return team.value?.teamRoutes?.[0]?.route || null;
return game.value.legs.findIndex(l => l.id === team.value!.currentLegId);
}); });
const currentLeg = computed(() => { const currentLegIndex = computed(() => team.value?.currentLegIndex ?? -1);
if (currentLegIndex.value < 0 || !game.value?.legs) return null;
return game.value.legs[currentLegIndex.value]; 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() { async function loadTeam() {
loading.value = true; loading.value = true;
try { try {
const response = await teamService.get(gameId.value); const response = await teamService.get(gameId.value);
team.value = response.data; team.value = response.data;
game.value = response.data.game; game.value = response.data.game || null;
if (team.value?.lat && team.value?.lng && map) { if (team.value?.lat && team.value?.lng && map) {
teamMarker = L.marker([team.value.lat, team.value.lng]).addTo(map); teamMarker = L.marker([team.value.lat, team.value.lng]).addTo(map);
@ -166,7 +171,7 @@ async function submitPhoto() {
uploading.value = true; uploading.value = true;
try { try {
const uploadRes = await uploadService.upload(photoFile.value); 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', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -191,14 +196,6 @@ async function submitPhoto() {
function handleVisibilityChange() { function handleVisibilityChange() {
if (document.hidden) { if (document.hidden) {
alert('Warning: Leaving the game tab may result in time penalties!'); 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> <p>{{ currentLeg.description }}</p>
<footer> <footer>
<small> <small>
Route: {{ currentRoute?.name }} ·
Type: {{ currentLeg.conditionType }} Type: {{ currentLeg.conditionType }}
<span v-if="currentLeg.timeLimit"> · Time limit: {{ currentLeg.timeLimit }} min</span> <span v-if="currentLeg.timeLimit"> · Time limit: {{ currentLeg.timeLimit }} min</span>
</small> </small>
@ -251,6 +249,7 @@ onUnmounted(() => {
<article v-else> <article v-else>
<p v-if="team.status === 'FINISHED'">🎉 Congratulations! You've completed the hunt!</p> <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> <p v-else>Waiting for the game to start...</p>
</article> </article>
@ -258,9 +257,9 @@ onUnmounted(() => {
<h3>Progress</h3> <h3>Progress</h3>
<progress <progress
:value="currentLegIndex + 1" :value="currentLegIndex + 1"
:max="game.legs?.length || 1" :max="totalLegs || 1"
></progress> ></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"> <p v-if="team.totalTimeDeduction" class="error">
<small>Time penalty: {{ team.totalTimeDeduction }} seconds</small> <small>Time penalty: {{ team.totalTimeDeduction }} seconds</small>
</p> </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 { io, Socket } from 'socket.io-client';
import L from 'leaflet'; import L from 'leaflet';
import 'leaflet/dist/leaflet.css'; import 'leaflet/dist/leaflet.css';
import type { Game, Team } from '../types'; import type { Game, Team, Route } from '../types';
import { gameService, teamService } from '../services/api'; import { gameService, teamService, routeService } from '../services/api';
const route = useRoute(); const route = useRoute();
const game = ref<Game | null>(null); const game = ref<Game | null>(null);
const teams = ref<Team[]>([]); const teams = ref<Team[]>([]);
const routes = ref<Route[]>([]);
const loading = ref(true); const loading = ref(true);
const gameId = computed(() => route.params.id as string); const gameId = computed(() => route.params.id as string);
@ -23,9 +24,9 @@ const leaderboard = computed(() => {
return [...teams.value] return [...teams.value]
.filter(t => t.status === 'ACTIVE' || t.status === 'FINISHED') .filter(t => t.status === 'ACTIVE' || t.status === 'FINISHED')
.sort((a, b) => { .sort((a, b) => {
const aLegIndex = game.value?.legs?.findIndex(l => l.id === a.currentLegId) || 0; if (a.status === 'FINISHED' && b.status !== 'FINISHED') return -1;
const bLegIndex = game.value?.legs?.findIndex(l => l.id === b.currentLegId) || 0; if (b.status === 'FINISHED' && a.status !== 'FINISHED') return 1;
if (aLegIndex !== bLegIndex) return bLegIndex - aLegIndex; if (a.currentLegIndex !== b.currentLegIndex) return b.currentLegIndex - a.currentLegIndex;
return a.totalTimeDeduction - b.totalTimeDeduction; return a.totalTimeDeduction - b.totalTimeDeduction;
}); });
}); });
@ -33,12 +34,14 @@ const leaderboard = computed(() => {
async function loadGame() { async function loadGame() {
loading.value = true; loading.value = true;
try { try {
const [gameRes, teamsRes] = await Promise.all([ const [gameRes, teamsRes, routesRes] = await Promise.all([
gameService.get(gameId.value), gameService.get(gameId.value),
teamService.getByGame(gameId.value) teamService.getByGame(gameId.value),
routeService.getByGame(gameId.value)
]); ]);
game.value = gameRes.data; game.value = gameRes.data;
teams.value = teamsRes.data; teams.value = teamsRes.data;
routes.value = routesRes.data;
} catch (err) { } catch (err) {
console.error('Failed to load game:', err); console.error('Failed to load game:', err);
} finally { } finally {
@ -62,9 +65,35 @@ function initMap() {
fillOpacity: 0.1 fillOpacity: 0.1
}).addTo(map); }).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 => { teams.value.forEach(team => {
if (team.lat && team.lng) { 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!) .addTo(map!)
.bindPopup(team.name); .bindPopup(team.name);
teamMarkers[team.id] = marker; teamMarkers[team.id] = marker;
@ -145,7 +174,8 @@ onUnmounted(() => {
</div> </div>
<footer> <footer>
<small> <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> <span v-if="team.totalTimeDeduction" class="error"> · -{{ team.totalTimeDeduction }}s</span>
</small> </small>
</footer> </footer>

View file

@ -67,6 +67,12 @@ const router = createRouter({
name: 'invite', name: 'invite',
component: () => import('../pages/InvitePage.vue'), 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 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({ const api = axios.create({
baseURL: 'http://localhost:3001/api', baseURL: 'http://localhost:3001/api',
@ -37,13 +37,21 @@ export const gameService = {
getInvite: (id: string) => api.get<{ inviteCode: string }>(`/games/${id}/invite`), getInvite: (id: string) => api.get<{ inviteCode: string }>(`/games/${id}/invite`),
}; };
export const legService = { export const routeService = {
getByGame: (gameId: string) => api.get<Leg[]>(`/legs/game/${gameId}`), getByGame: (gameId: string) => api.get<Route[]>(`/routes/game/${gameId}`),
create: (gameId: string, data: Partial<Leg>) => api.post<Leg>(`/legs/game/${gameId}`, data), get: (routeId: string) => api.get<Route>(`/routes/${routeId}`),
update: (legId: string, data: Partial<Leg>) => api.put<Leg>(`/legs/${legId}`, data), create: (data: { gameId: string; name: string; description?: string; color?: string }) =>
delete: (legId: string) => api.delete(`/legs/${legId}`), api.post<Route>('/routes', data),
submitPhoto: (legId: string, data: { teamId: string; photoUrl: string }) => update: (routeId: string, data: Partial<Route>) =>
api.post(`/legs/${legId}/photo`, data), 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 = { export const teamService = {
@ -52,6 +60,8 @@ export const teamService = {
get: (teamId: string) => api.get<Team>(`/teams/${teamId}`), get: (teamId: string) => api.get<Team>(`/teams/${teamId}`),
join: (teamId: string) => api.post(`/teams/${teamId}/join`), join: (teamId: string) => api.post(`/teams/${teamId}/join`),
leave: (teamId: string) => api.post(`/teams/${teamId}/leave`), 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`), advance: (teamId: string) => api.post<Team>(`/teams/${teamId}/advance`),
deduct: (teamId: string, seconds: number) => api.post<Team>(`/teams/${teamId}/deduct`, { seconds }), deduct: (teamId: string, seconds: number) => api.post<Team>(`/teams/${teamId}/deduct`, { seconds }),
disqualify: (teamId: string) => api.post<Team>(`/teams/${teamId}/disqualify`), 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; export default api;

View file

@ -2,9 +2,48 @@ export interface User {
id: string; id: string;
email: string; email: string;
name: string; name: string;
screenName?: string;
avatarUrl?: string;
createdAt?: 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 { export interface Game {
id: string; id: string;
name: string; name: string;
@ -16,20 +55,33 @@ export interface Game {
locationLng?: number; locationLng?: number;
searchRadius?: number; searchRadius?: number;
rules?: string[]; rules?: string[];
randomizeRoutes?: boolean;
status: 'DRAFT' | 'LIVE' | 'ENDED' | 'ARCHIVED'; status: 'DRAFT' | 'LIVE' | 'ENDED' | 'ARCHIVED';
inviteCode?: string; inviteCode?: string;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
gameMasterId: string; gameMasterId: string;
gameMaster?: User; gameMaster?: User;
legs?: Leg[]; routes?: Route[];
teams?: Team[]; teams?: Team[];
_count?: { teams: number; legs: number }; _count?: { teams: number; routes: number };
} }
export interface Leg { export interface Route {
id: string; id: string;
gameId: 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; sequenceNumber: number;
description: string; description: string;
conditionType: string; conditionType: string;
@ -45,8 +97,7 @@ export interface Team {
name: string; name: string;
captainId?: string; captainId?: string;
captain?: User; captain?: User;
currentLegId?: string; currentLegIndex: number;
currentLeg?: Leg;
status: 'ACTIVE' | 'DISQUALIFIED' | 'FINISHED'; status: 'ACTIVE' | 'DISQUALIFIED' | 'FINISHED';
totalTimeDeduction: number; totalTimeDeduction: number;
lat?: number; lat?: number;
@ -54,6 +105,16 @@ export interface Team {
rank?: number; rank?: number;
createdAt: string; createdAt: string;
members?: TeamMember[]; members?: TeamMember[];
teamRoutes?: TeamRoute[];
game?: Game;
}
export interface TeamRoute {
id: string;
teamId: string;
routeId: string;
assignedAt: string;
route?: Route;
} }
export interface TeamMember { export interface TeamMember {
@ -67,7 +128,7 @@ export interface TeamMember {
export interface PhotoSubmission { export interface PhotoSubmission {
id: string; id: string;
teamId: string; teamId: string;
legId: string; routeLegId: string;
photoUrl: string; photoUrl: string;
approved: boolean; approved: boolean;
submittedAt: string; submittedAt: string;

2
node_modules/.package-lock.json generated vendored
View file

@ -1,5 +1,5 @@
{ {
"name": "scavenge", "name": "TreasureTrails",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {

2
package-lock.json generated
View file

@ -1,5 +1,5 @@
{ {
"name": "scavenge", "name": "TreasureTrails",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {