Added settings for user data deletion
This commit is contained in:
parent
59e15cfde8
commit
f49490042a
35 changed files with 2758 additions and 499 deletions
26
backend/dist/index.js
vendored
26
backend/dist/index.js
vendored
|
|
@ -9,12 +9,13 @@ const cors_1 = __importDefault(require("cors"));
|
|||
const http_1 = require("http");
|
||||
const socket_io_1 = require("socket.io");
|
||||
const client_1 = require("@prisma/client");
|
||||
const auth_js_1 = __importDefault(require("./routes/auth.js"));
|
||||
const games_js_1 = __importDefault(require("./routes/games.js"));
|
||||
const teams_js_1 = __importDefault(require("./routes/teams.js"));
|
||||
const legs_js_1 = __importDefault(require("./routes/legs.js"));
|
||||
const upload_js_1 = __importDefault(require("./routes/upload.js"));
|
||||
const index_js_1 = __importDefault(require("./socket/index.js"));
|
||||
const auth_1 = __importDefault(require("./routes/auth"));
|
||||
const games_1 = __importDefault(require("./routes/games"));
|
||||
const teams_1 = __importDefault(require("./routes/teams"));
|
||||
const routes_1 = __importDefault(require("./routes/routes"));
|
||||
const users_1 = __importDefault(require("./routes/users"));
|
||||
const upload_1 = __importDefault(require("./routes/upload"));
|
||||
const index_1 = __importDefault(require("./socket/index"));
|
||||
const app = (0, express_1.default)();
|
||||
const httpServer = (0, http_1.createServer)(app);
|
||||
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(express_1.default.json());
|
||||
app.use('/uploads', express_1.default.static('uploads'));
|
||||
app.use('/api/auth', auth_js_1.default);
|
||||
app.use('/api/games', games_js_1.default);
|
||||
app.use('/api/teams', teams_js_1.default);
|
||||
app.use('/api/legs', legs_js_1.default);
|
||||
app.use('/api/upload', upload_js_1.default);
|
||||
app.use('/api/auth', auth_1.default);
|
||||
app.use('/api/games', games_1.default);
|
||||
app.use('/api/teams', teams_1.default);
|
||||
app.use('/api/routes', routes_1.default);
|
||||
app.use('/api/users', users_1.default);
|
||||
app.use('/api/upload', upload_1.default);
|
||||
app.get('/api/health', (req, res) => {
|
||||
res.json({ status: 'ok' });
|
||||
});
|
||||
(0, index_js_1.default)(io);
|
||||
(0, index_1.default)(io);
|
||||
const PORT = process.env.PORT || 3001;
|
||||
httpServer.listen(PORT, () => {
|
||||
console.log(`Server running on port ${PORT}`);
|
||||
|
|
|
|||
6
backend/dist/middleware/auth.js
vendored
6
backend/dist/middleware/auth.js
vendored
|
|
@ -5,7 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.optionalAuth = exports.authenticate = void 0;
|
||||
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 authenticate = async (req, res, next) => {
|
||||
try {
|
||||
|
|
@ -15,7 +15,7 @@ const authenticate = async (req, res, next) => {
|
|||
}
|
||||
const token = authHeader.split(' ')[1];
|
||||
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 },
|
||||
select: { id: true, email: true, name: true }
|
||||
});
|
||||
|
|
@ -38,7 +38,7 @@ const optionalAuth = async (req, res, next) => {
|
|||
}
|
||||
const token = authHeader.split(' ')[1];
|
||||
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 },
|
||||
select: { id: true, email: true, name: true }
|
||||
});
|
||||
|
|
|
|||
10
backend/dist/routes/auth.js
vendored
10
backend/dist/routes/auth.js
vendored
|
|
@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|||
const express_1 = require("express");
|
||||
const bcryptjs_1 = __importDefault(require("bcryptjs"));
|
||||
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 JWT_SECRET = process.env.JWT_SECRET || 'treasure-trails-secret-key';
|
||||
router.post('/register', async (req, res) => {
|
||||
|
|
@ -15,12 +15,12 @@ router.post('/register', async (req, res) => {
|
|||
if (!email || !password || !name) {
|
||||
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) {
|
||||
return res.status(400).json({ error: 'Email already registered' });
|
||||
}
|
||||
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 }
|
||||
});
|
||||
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) {
|
||||
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) {
|
||||
return res.status(401).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
|
@ -67,7 +67,7 @@ router.get('/me', async (req, res) => {
|
|||
}
|
||||
const token = authHeader.split(' ')[1];
|
||||
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 },
|
||||
select: { id: true, email: true, name: true, createdAt: true }
|
||||
});
|
||||
|
|
|
|||
171
backend/dist/routes/games.js
vendored
171
backend/dist/routes/games.js
vendored
|
|
@ -1,8 +1,8 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = require("express");
|
||||
const index_js_1 = require("../index.js");
|
||||
const auth_js_1 = require("../middleware/auth.js");
|
||||
const index_1 = require("../index");
|
||||
const auth_1 = require("../middleware/auth");
|
||||
const uuid_1 = require("uuid");
|
||||
const router = (0, express_1.Router)();
|
||||
router.get('/', async (req, res) => {
|
||||
|
|
@ -17,11 +17,11 @@ router.get('/', async (req, res) => {
|
|||
if (search) {
|
||||
where.name = { contains: search, mode: 'insensitive' };
|
||||
}
|
||||
const games = await index_js_1.prisma.game.findMany({
|
||||
const games = await index_1.prisma.game.findMany({
|
||||
where,
|
||||
include: {
|
||||
gameMaster: { select: { id: true, name: true } },
|
||||
_count: { select: { teams: true, legs: true } }
|
||||
_count: { select: { teams: true, routes: true } }
|
||||
},
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
|
|
@ -32,12 +32,12 @@ router.get('/', async (req, res) => {
|
|||
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 {
|
||||
const games = await index_js_1.prisma.game.findMany({
|
||||
const games = await index_1.prisma.game.findMany({
|
||||
where: { gameMasterId: req.user.id },
|
||||
include: {
|
||||
_count: { select: { teams: true, legs: true } }
|
||||
_count: { select: { teams: true, routes: true } }
|
||||
},
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
|
|
@ -51,15 +51,27 @@ router.get('/my-games', auth_js_1.authenticate, async (req, res) => {
|
|||
router.get('/:id', async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const game = await index_js_1.prisma.game.findUnique({
|
||||
where: { id },
|
||||
const game = await index_1.prisma.game.findUnique({
|
||||
where: { id: id },
|
||||
include: {
|
||||
gameMaster: { select: { id: true, name: true } },
|
||||
legs: { orderBy: { sequenceNumber: 'asc' } },
|
||||
routes: {
|
||||
include: {
|
||||
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
|
||||
}
|
||||
},
|
||||
teams: {
|
||||
include: {
|
||||
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) {
|
||||
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) {
|
||||
console.error('Get game error:', error);
|
||||
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 {
|
||||
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) {
|
||||
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' });
|
||||
}
|
||||
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: {
|
||||
name,
|
||||
description,
|
||||
|
|
@ -98,8 +114,8 @@ router.post('/', auth_js_1.authenticate, async (req, res) => {
|
|||
locationLat,
|
||||
locationLng,
|
||||
searchRadius,
|
||||
timeLimitPerLeg,
|
||||
timeDeductionPenalty,
|
||||
rules: rules ? JSON.stringify(rules) : null,
|
||||
randomizeRoutes: randomizeRoutes || false,
|
||||
gameMasterId: req.user.id,
|
||||
inviteCode
|
||||
}
|
||||
|
|
@ -111,19 +127,19 @@ router.post('/', auth_js_1.authenticate, async (req, res) => {
|
|||
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 {
|
||||
const { id } = req.params;
|
||||
const { name, description, prizeDetails, visibility, startDate, locationLat, locationLng, searchRadius, timeLimitPerLeg, timeDeductionPenalty, status } = req.body;
|
||||
const game = await index_js_1.prisma.game.findUnique({ where: { id } });
|
||||
const id = req.params.id;
|
||||
const { name, description, prizeDetails, visibility, startDate, locationLat, locationLng, searchRadius, rules, status, randomizeRoutes } = req.body;
|
||||
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_js_1.prisma.game.update({
|
||||
where: { id },
|
||||
const updated = await index_1.prisma.game.update({
|
||||
where: { id: id },
|
||||
data: {
|
||||
name,
|
||||
description,
|
||||
|
|
@ -133,8 +149,8 @@ router.put('/:id', auth_js_1.authenticate, async (req, res) => {
|
|||
locationLat,
|
||||
locationLng,
|
||||
searchRadius,
|
||||
timeLimitPerLeg,
|
||||
timeDeductionPenalty,
|
||||
rules: rules ? JSON.stringify(rules) : undefined,
|
||||
randomizeRoutes,
|
||||
status
|
||||
}
|
||||
});
|
||||
|
|
@ -145,17 +161,17 @@ router.put('/:id', auth_js_1.authenticate, async (req, res) => {
|
|||
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 {
|
||||
const { id } = req.params;
|
||||
const game = await index_js_1.prisma.game.findUnique({ where: { id } });
|
||||
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' });
|
||||
}
|
||||
await index_js_1.prisma.game.delete({ where: { id } });
|
||||
await index_1.prisma.game.delete({ where: { id } });
|
||||
res.json({ message: 'Game deleted' });
|
||||
}
|
||||
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' });
|
||||
}
|
||||
});
|
||||
router.post('/:id/publish', auth_js_1.authenticate, async (req, res) => {
|
||||
router.post('/:id/publish', auth_1.authenticate, async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const game = await index_js_1.prisma.game.findUnique({
|
||||
where: { id },
|
||||
include: { legs: true }
|
||||
const game = await index_1.prisma.game.findUnique({
|
||||
where: { id: id },
|
||||
include: { routes: { include: { routeLegs: true } } }
|
||||
});
|
||||
if (!game) {
|
||||
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) {
|
||||
return res.status(403).json({ error: 'Not authorized' });
|
||||
}
|
||||
if (game.legs.length === 0) {
|
||||
return res.status(400).json({ error: 'Game must have at least one leg' });
|
||||
if (!game.routes || game.routes.length === 0) {
|
||||
return res.status(400).json({ error: 'Game must have at least one route' });
|
||||
}
|
||||
const updated = await index_js_1.prisma.game.update({
|
||||
where: { id },
|
||||
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 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' }
|
||||
});
|
||||
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' });
|
||||
}
|
||||
});
|
||||
router.post('/:id/end', auth_js_1.authenticate, async (req, res) => {
|
||||
router.post('/:id/end', auth_1.authenticate, async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const game = await index_js_1.prisma.game.findUnique({ where: { id } });
|
||||
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_js_1.prisma.game.update({
|
||||
const updated = await index_1.prisma.game.update({
|
||||
where: { id },
|
||||
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' });
|
||||
}
|
||||
});
|
||||
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) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const game = await index_js_1.prisma.game.findUnique({ where: { id } });
|
||||
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' });
|
||||
}
|
||||
|
|
@ -230,8 +311,8 @@ router.get('/:id/invite', async (req, res) => {
|
|||
});
|
||||
router.get('/invite/:code', async (req, res) => {
|
||||
try {
|
||||
const { code } = req.params;
|
||||
const game = await index_js_1.prisma.game.findUnique({
|
||||
const code = req.params.code;
|
||||
const game = await index_1.prisma.game.findUnique({
|
||||
where: { inviteCode: code },
|
||||
include: { gameMaster: { select: { id: true, name: true } } }
|
||||
});
|
||||
|
|
|
|||
2
backend/dist/routes/routes.d.ts
vendored
Normal file
2
backend/dist/routes/routes.d.ts
vendored
Normal 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
338
backend/dist/routes/routes.js
vendored
Normal 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;
|
||||
186
backend/dist/routes/teams.js
vendored
186
backend/dist/routes/teams.js
vendored
|
|
@ -1,18 +1,26 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const express_1 = require("express");
|
||||
const index_js_1 = require("../index.js");
|
||||
const auth_js_1 = require("../middleware/auth.js");
|
||||
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 teams = await index_js_1.prisma.team.findMany({
|
||||
const teams = await index_1.prisma.team.findMany({
|
||||
where: { gameId },
|
||||
include: {
|
||||
members: { include: { user: { select: { id: true, name: true, email: true } } } },
|
||||
captain: { select: { id: true, name: true } },
|
||||
currentLeg: true
|
||||
teamRoutes: {
|
||||
include: {
|
||||
route: {
|
||||
include: {
|
||||
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: { createdAt: 'asc' }
|
||||
});
|
||||
|
|
@ -23,11 +31,11 @@ router.get('/game/:gameId', async (req, res) => {
|
|||
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 {
|
||||
const { gameId } = req.params;
|
||||
const { name } = req.body;
|
||||
const game = await index_js_1.prisma.game.findUnique({
|
||||
const game = await index_1.prisma.game.findUnique({
|
||||
where: { id: gameId },
|
||||
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') {
|
||||
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: {
|
||||
userId: req.user.id,
|
||||
team: { gameId }
|
||||
|
|
@ -46,24 +54,33 @@ router.post('/game/:gameId', auth_js_1.authenticate, async (req, res) => {
|
|||
if (existingMember) {
|
||||
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: {
|
||||
gameId,
|
||||
name,
|
||||
captainId: req.user.id
|
||||
}
|
||||
});
|
||||
await index_js_1.prisma.teamMember.create({
|
||||
await index_1.prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.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 },
|
||||
include: {
|
||||
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);
|
||||
|
|
@ -73,10 +90,10 @@ router.post('/game/:gameId', auth_js_1.authenticate, async (req, res) => {
|
|||
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 {
|
||||
const { teamId } = req.params;
|
||||
const team = await index_js_1.prisma.team.findUnique({
|
||||
const team = await index_1.prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
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) {
|
||||
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: {
|
||||
userId: req.user.id,
|
||||
teamId
|
||||
|
|
@ -95,7 +112,7 @@ router.post('/:teamId/join', auth_js_1.authenticate, async (req, res) => {
|
|||
if (existingMember) {
|
||||
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: {
|
||||
userId: req.user.id,
|
||||
team: { gameId: team.gameId }
|
||||
|
|
@ -104,7 +121,7 @@ router.post('/:teamId/join', auth_js_1.authenticate, async (req, res) => {
|
|||
if (gameMember) {
|
||||
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: {
|
||||
teamId,
|
||||
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' });
|
||||
}
|
||||
});
|
||||
router.post('/:teamId/leave', auth_js_1.authenticate, async (req, res) => {
|
||||
router.post('/:teamId/leave', auth_1.authenticate, async (req, res) => {
|
||||
try {
|
||||
const { teamId } = req.params;
|
||||
const team = await index_js_1.prisma.team.findUnique({
|
||||
const team = await index_1.prisma.team.findUnique({
|
||||
where: { id: teamId }
|
||||
});
|
||||
if (!team) {
|
||||
|
|
@ -129,7 +146,7 @@ router.post('/:teamId/leave', auth_js_1.authenticate, async (req, res) => {
|
|||
if (team.captainId === req.user.id) {
|
||||
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: {
|
||||
teamId,
|
||||
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' });
|
||||
}
|
||||
});
|
||||
router.post('/:teamId/advance', auth_js_1.authenticate, async (req, res) => {
|
||||
router.post('/:teamId/assign-route', auth_1.authenticate, async (req, res) => {
|
||||
try {
|
||||
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 },
|
||||
include: {
|
||||
game: { include: { legs: { orderBy: { sequenceNumber: 'asc' } } } },
|
||||
currentLeg: true
|
||||
game: true,
|
||||
teamRoutes: {
|
||||
include: {
|
||||
route: {
|
||||
include: {
|
||||
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!team) {
|
||||
|
|
@ -158,27 +226,33 @@ router.post('/:teamId/advance', auth_js_1.authenticate, async (req, res) => {
|
|||
if (team.game.gameMasterId !== req.user.id) {
|
||||
return res.status(403).json({ error: 'Not authorized' });
|
||||
}
|
||||
const legs = team.game.legs;
|
||||
const currentLeg = team.currentLeg;
|
||||
let nextLeg = null;
|
||||
if (currentLeg) {
|
||||
const currentIndex = legs.findIndex((l) => l.id === currentLeg.id);
|
||||
if (currentIndex < legs.length - 1) {
|
||||
nextLeg = legs[currentIndex + 1];
|
||||
const teamRoute = team.teamRoutes[0];
|
||||
if (!teamRoute) {
|
||||
return res.status(400).json({ error: 'Team has no assigned route' });
|
||||
}
|
||||
const legs = teamRoute.route.routeLegs;
|
||||
const currentLegIndex = team.currentLegIndex;
|
||||
let nextLegIndex = currentLegIndex;
|
||||
if (currentLegIndex < legs.length - 1) {
|
||||
nextLegIndex = currentLegIndex + 1;
|
||||
}
|
||||
else if (legs.length > 0) {
|
||||
nextLeg = legs[0];
|
||||
}
|
||||
const updated = await index_js_1.prisma.team.update({
|
||||
const updated = await index_1.prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
currentLegId: nextLeg?.id || null,
|
||||
status: nextLeg ? 'ACTIVE' : 'FINISHED'
|
||||
currentLegIndex: nextLegIndex,
|
||||
status: nextLegIndex >= legs.length - 1 ? 'FINISHED' : 'ACTIVE'
|
||||
},
|
||||
include: {
|
||||
members: { include: { user: { select: { id: true, name: true } } } },
|
||||
currentLeg: true
|
||||
teamRoutes: {
|
||||
include: {
|
||||
route: {
|
||||
include: {
|
||||
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
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' });
|
||||
}
|
||||
});
|
||||
router.post('/:teamId/deduct', auth_js_1.authenticate, async (req, res) => {
|
||||
router.post('/:teamId/deduct', auth_1.authenticate, async (req, res) => {
|
||||
try {
|
||||
const { teamId } = req.params;
|
||||
const { seconds } = req.body;
|
||||
const team = await index_js_1.prisma.team.findUnique({
|
||||
const team = await index_1.prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
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) {
|
||||
return res.status(403).json({ error: 'Not authorized' });
|
||||
}
|
||||
const deduction = seconds || team.game.timeDeductionPenalty || 60;
|
||||
const updated = await index_js_1.prisma.team.update({
|
||||
const deduction = seconds || 60;
|
||||
const updated = await index_1.prisma.team.update({
|
||||
where: { id: teamId },
|
||||
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' });
|
||||
}
|
||||
});
|
||||
router.post('/:teamId/disqualify', auth_js_1.authenticate, async (req, res) => {
|
||||
router.post('/:teamId/disqualify', auth_1.authenticate, async (req, res) => {
|
||||
try {
|
||||
const { teamId } = req.params;
|
||||
const team = await index_js_1.prisma.team.findUnique({
|
||||
const team = await index_1.prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
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) {
|
||||
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 },
|
||||
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' });
|
||||
}
|
||||
});
|
||||
router.post('/:teamId/location', auth_js_1.authenticate, async (req, res) => {
|
||||
router.post('/:teamId/location', auth_1.authenticate, async (req, res) => {
|
||||
try {
|
||||
const { teamId } = req.params;
|
||||
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 }
|
||||
});
|
||||
if (!team) {
|
||||
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 }
|
||||
});
|
||||
if (!member && team.captainId !== req.user.id) {
|
||||
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 },
|
||||
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' });
|
||||
}
|
||||
});
|
||||
router.get('/:teamId', auth_js_1.authenticate, async (req, res) => {
|
||||
router.get('/:teamId', auth_1.authenticate, async (req, res) => {
|
||||
try {
|
||||
const { teamId } = req.params;
|
||||
const team = await index_js_1.prisma.team.findUnique({
|
||||
const team = await index_1.prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
include: {
|
||||
members: { include: { user: { select: { id: true, name: true, email: true } } } },
|
||||
captain: { select: { id: true, name: true } },
|
||||
currentLeg: true,
|
||||
game: { include: { legs: { orderBy: { sequenceNumber: 'asc' } } } }
|
||||
game: { include: { routes: { include: { routeLegs: { orderBy: { sequenceNumber: 'asc' } } } } } },
|
||||
teamRoutes: {
|
||||
include: {
|
||||
route: {
|
||||
include: {
|
||||
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!team) {
|
||||
|
|
|
|||
4
backend/dist/routes/upload.js
vendored
4
backend/dist/routes/upload.js
vendored
|
|
@ -7,7 +7,7 @@ const express_1 = require("express");
|
|||
const multer_1 = __importDefault(require("multer"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
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 storage = multer_1.default.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
|
|
@ -31,7 +31,7 @@ const upload = (0, multer_1.default)({
|
|||
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 {
|
||||
if (!req.file) {
|
||||
return res.status(400).json({ error: 'No file uploaded' });
|
||||
|
|
|
|||
2
backend/dist/routes/users.d.ts
vendored
Normal file
2
backend/dist/routes/users.d.ts
vendored
Normal 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
213
backend/dist/routes/users.js
vendored
Normal 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;
|
||||
6
backend/dist/socket/index.js
vendored
6
backend/dist/socket/index.js
vendored
|
|
@ -1,7 +1,7 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = setupSocket;
|
||||
const index_js_1 = require("../index.js");
|
||||
const index_1 = require("../index");
|
||||
function setupSocket(io) {
|
||||
io.on('connection', (socket) => {
|
||||
console.log('Client connected:', socket.id);
|
||||
|
|
@ -13,7 +13,7 @@ function setupSocket(io) {
|
|||
socket.leave(`game:${gameId}`);
|
||||
});
|
||||
socket.on('team-location', async (data) => {
|
||||
await index_js_1.prisma.team.update({
|
||||
await index_1.prisma.team.update({
|
||||
where: { id: data.teamId },
|
||||
data: { lat: data.lat, lng: data.lng }
|
||||
});
|
||||
|
|
@ -24,7 +24,7 @@ function setupSocket(io) {
|
|||
});
|
||||
});
|
||||
socket.on('chat-message', async (data) => {
|
||||
const chatMessage = await index_js_1.prisma.chatMessage.create({
|
||||
const chatMessage = await index_1.prisma.chatMessage.create({
|
||||
data: {
|
||||
gameId: data.gameId,
|
||||
teamId: data.teamId,
|
||||
|
|
|
|||
19
backend/package-lock.json
generated
19
backend/package-lock.json
generated
|
|
@ -23,7 +23,7 @@
|
|||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^5.0.1",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/jsonwebtoken": "^9.0.7",
|
||||
"@types/multer": "^1.4.12",
|
||||
"@types/node": "^22.15.21",
|
||||
|
|
@ -215,21 +215,22 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@types/express": {
|
||||
"version": "5.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz",
|
||||
"integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==",
|
||||
"version": "4.17.21",
|
||||
"resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz",
|
||||
"integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/body-parser": "*",
|
||||
"@types/express-serve-static-core": "^5.0.0",
|
||||
"@types/serve-static": "^2"
|
||||
"@types/express-serve-static-core": "^4.17.33",
|
||||
"@types/qs": "*",
|
||||
"@types/serve-static": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/express-serve-static-core": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.1.tgz",
|
||||
"integrity": "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A==",
|
||||
"version": "4.19.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.8.tgz",
|
||||
"integrity": "sha512-02S5fmqeoKzVZCHPZid4b8JH2eM5HzQLZWN2FohQEy/0eXTq8VXZfSN6Pcr3F6N9R/vNrj7cpgbhjie6m/1tCA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@
|
|||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^5.0.1",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/jsonwebtoken": "^9.0.7",
|
||||
"@types/multer": "^1.4.12",
|
||||
"@types/node": "^22.15.21",
|
||||
|
|
|
|||
|
|
@ -12,12 +12,15 @@ model User {
|
|||
email String @unique
|
||||
passwordHash String
|
||||
name String
|
||||
screenName String?
|
||||
avatarUrl String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
games Game[] @relation("GameMaster")
|
||||
teams TeamMember[]
|
||||
captainOf Team? @relation("TeamCaptain")
|
||||
chatMessages ChatMessage[]
|
||||
locationHistory LocationHistory[]
|
||||
}
|
||||
|
||||
model Game {
|
||||
|
|
@ -31,21 +34,36 @@ model Game {
|
|||
locationLng Float?
|
||||
searchRadius Float?
|
||||
rules String?
|
||||
randomizeRoutes Boolean @default(false)
|
||||
status GameStatus @default(DRAFT)
|
||||
inviteCode String? @unique
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
gameMasterId String
|
||||
gameMaster User @relation("GameMaster", fields: [gameMasterId], references: [id])
|
||||
legs Leg[]
|
||||
routes Route[]
|
||||
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())
|
||||
routeId String
|
||||
route Route @relation(fields: [routeId], references: [id], onDelete: Cascade)
|
||||
sequenceNumber Int
|
||||
description String
|
||||
conditionType String @default("photo")
|
||||
|
|
@ -53,7 +71,6 @@ model Leg {
|
|||
locationLat Float?
|
||||
locationLng Float?
|
||||
timeLimit Int?
|
||||
teams Team[]
|
||||
}
|
||||
|
||||
model Team {
|
||||
|
|
@ -63,8 +80,7 @@ model Team {
|
|||
name String
|
||||
captainId String? @unique
|
||||
captain User? @relation("TeamCaptain", fields: [captainId], references: [id])
|
||||
currentLegId String?
|
||||
currentLeg Leg? @relation(fields: [currentLegId], references: [id])
|
||||
currentLegIndex Int @default(0)
|
||||
status TeamStatus @default(ACTIVE)
|
||||
totalTimeDeduction Int @default(0)
|
||||
lat Float?
|
||||
|
|
@ -74,6 +90,18 @@ model Team {
|
|||
members TeamMember[]
|
||||
photoSubmissions PhotoSubmission[]
|
||||
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 {
|
||||
|
|
@ -91,7 +119,8 @@ model PhotoSubmission {
|
|||
id String @id @default(uuid())
|
||||
teamId String
|
||||
team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
|
||||
legId String
|
||||
routeId String
|
||||
routeLegId String
|
||||
photoUrl String
|
||||
approved Boolean @default(false)
|
||||
submittedAt DateTime @default(now())
|
||||
|
|
@ -109,6 +138,19 @@ model ChatMessage {
|
|||
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 {
|
||||
PUBLIC
|
||||
PRIVATE
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@ import { PrismaClient } from '@prisma/client';
|
|||
import authRoutes from './routes/auth';
|
||||
import gameRoutes from './routes/games';
|
||||
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 setupSocket from './socket/index';
|
||||
|
||||
|
|
@ -28,7 +29,8 @@ app.use('/uploads', express.static('uploads'));
|
|||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/games', gameRoutes);
|
||||
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.get('/api/health', (req, res) => {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ router.get('/', async (req: AuthRequest, res: Response) => {
|
|||
where,
|
||||
include: {
|
||||
gameMaster: { select: { id: true, name: true } },
|
||||
_count: { select: { teams: true, legs: true } }
|
||||
_count: { select: { teams: true, routes: true } }
|
||||
},
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
|
|
@ -42,7 +42,7 @@ router.get('/my-games', authenticate, async (req: AuthRequest, res: Response) =>
|
|||
const games = await prisma.game.findMany({
|
||||
where: { gameMasterId: req.user!.id },
|
||||
include: {
|
||||
_count: { select: { teams: true, legs: true } }
|
||||
_count: { select: { teams: true, routes: true } }
|
||||
},
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
|
|
@ -62,11 +62,23 @@ router.get('/:id', async (req: AuthRequest, res: Response) => {
|
|||
where: { id: id as string },
|
||||
include: {
|
||||
gameMaster: { select: { id: true, name: true } },
|
||||
legs: { orderBy: { sequenceNumber: 'asc' } },
|
||||
routes: {
|
||||
include: {
|
||||
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
|
||||
}
|
||||
},
|
||||
teams: {
|
||||
include: {
|
||||
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 {
|
||||
const {
|
||||
name, description, prizeDetails, visibility, startDate,
|
||||
locationLat, locationLng, searchRadius, rules
|
||||
locationLat, locationLng, searchRadius, rules, randomizeRoutes
|
||||
} = req.body;
|
||||
|
||||
if (!name) {
|
||||
|
|
@ -122,6 +134,7 @@ router.post('/', authenticate, async (req: AuthRequest, res: Response) => {
|
|||
locationLng,
|
||||
searchRadius,
|
||||
rules: rules ? JSON.stringify(rules) : null,
|
||||
randomizeRoutes: randomizeRoutes || false,
|
||||
gameMasterId: req.user!.id,
|
||||
inviteCode
|
||||
}
|
||||
|
|
@ -139,7 +152,7 @@ router.put('/:id', authenticate, async (req: AuthRequest, res: Response) => {
|
|||
const id = req.params.id as string;
|
||||
const {
|
||||
name, description, prizeDetails, visibility, startDate,
|
||||
locationLat, locationLng, searchRadius, rules, status
|
||||
locationLat, locationLng, searchRadius, rules, status, randomizeRoutes
|
||||
} = req.body;
|
||||
|
||||
const game = await prisma.game.findUnique({ where: { id } });
|
||||
|
|
@ -163,6 +176,7 @@ router.put('/:id', authenticate, async (req: AuthRequest, res: Response) => {
|
|||
locationLng,
|
||||
searchRadius,
|
||||
rules: rules ? JSON.stringify(rules) : undefined,
|
||||
randomizeRoutes,
|
||||
status
|
||||
}
|
||||
});
|
||||
|
|
@ -202,8 +216,8 @@ router.post('/:id/publish', authenticate, async (req: AuthRequest, res: Response
|
|||
|
||||
const game = await prisma.game.findUnique({
|
||||
where: { id: id as string },
|
||||
include: { legs: true }
|
||||
}) as any;
|
||||
include: { routes: { include: { routeLegs: true } } }
|
||||
});
|
||||
|
||||
if (!game) {
|
||||
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' });
|
||||
}
|
||||
|
||||
if (!game.legs || game.legs.length === 0) {
|
||||
return res.status(400).json({ error: 'Game must have at least one leg' });
|
||||
if (!game.routes || game.routes.length === 0) {
|
||||
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({
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
398
backend/src/routes/routes.ts
Normal file
398
backend/src/routes/routes.ts
Normal 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;
|
||||
|
|
@ -13,7 +13,15 @@ router.get('/game/:gameId', async (req: AuthRequest, res: Response) => {
|
|||
include: {
|
||||
members: { include: { user: { select: { id: true, name: true, email: true } } } },
|
||||
captain: { select: { id: true, name: true } },
|
||||
currentLeg: true
|
||||
teamRoutes: {
|
||||
include: {
|
||||
route: {
|
||||
include: {
|
||||
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: { createdAt: 'asc' }
|
||||
});
|
||||
|
|
@ -73,7 +81,16 @@ router.post('/game/:gameId', authenticate, async (req: AuthRequest, res: Respons
|
|||
where: { id: team.id },
|
||||
include: {
|
||||
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) => {
|
||||
try {
|
||||
const { teamId } = req.params;
|
||||
|
|
@ -174,8 +242,16 @@ router.post('/:teamId/advance', authenticate, async (req: AuthRequest, res: Resp
|
|||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
include: {
|
||||
game: { include: { legs: { orderBy: { sequenceNumber: 'asc' } } } },
|
||||
currentLeg: true
|
||||
game: 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' });
|
||||
}
|
||||
|
||||
const legs = team.game.legs;
|
||||
const currentLeg = team.currentLeg;
|
||||
|
||||
let nextLeg = null;
|
||||
if (currentLeg) {
|
||||
const currentIndex = legs.findIndex((l: { id: string }) => l.id === currentLeg.id);
|
||||
if (currentIndex < legs.length - 1) {
|
||||
nextLeg = legs[currentIndex + 1];
|
||||
const teamRoute = team.teamRoutes[0];
|
||||
if (!teamRoute) {
|
||||
return res.status(400).json({ error: 'Team has no assigned route' });
|
||||
}
|
||||
} else if (legs.length > 0) {
|
||||
nextLeg = legs[0];
|
||||
|
||||
const legs = teamRoute.route.routeLegs;
|
||||
const currentLegIndex = team.currentLegIndex;
|
||||
|
||||
let nextLegIndex = currentLegIndex;
|
||||
if (currentLegIndex < legs.length - 1) {
|
||||
nextLegIndex = currentLegIndex + 1;
|
||||
}
|
||||
|
||||
const updated = await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
data: {
|
||||
currentLegId: nextLeg?.id || null,
|
||||
status: nextLeg ? 'ACTIVE' : 'FINISHED'
|
||||
currentLegIndex: nextLegIndex,
|
||||
status: nextLegIndex >= legs.length - 1 ? 'FINISHED' : 'ACTIVE'
|
||||
},
|
||||
include: {
|
||||
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' });
|
||||
}
|
||||
|
||||
const deduction = seconds || team.game.timeDeductionPenalty || 60;
|
||||
const deduction = seconds || 60;
|
||||
|
||||
const updated = await prisma.team.update({
|
||||
where: { id: teamId },
|
||||
|
|
@ -322,8 +406,16 @@ router.get('/:teamId', authenticate, async (req: AuthRequest, res: Response) =>
|
|||
include: {
|
||||
members: { include: { user: { select: { id: true, name: true, email: true } } } },
|
||||
captain: { select: { id: true, name: true } },
|
||||
currentLeg: true,
|
||||
game: { include: { legs: { orderBy: { sequenceNumber: 'asc' } } } }
|
||||
game: { include: { routes: { include: { routeLegs: { orderBy: { sequenceNumber: 'asc' } } } } } },
|
||||
teamRoutes: {
|
||||
include: {
|
||||
route: {
|
||||
include: {
|
||||
routeLegs: { orderBy: { sequenceNumber: 'asc' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
229
backend/src/routes/users.ts
Normal file
229
backend/src/routes/users.ts
Normal 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;
|
||||
|
|
@ -32,6 +32,7 @@ function closeNav() {
|
|||
|
||||
<ul v-if="authStore.isLoggedIn">
|
||||
<li><RouterLink to="/dashboard" @click="closeNav">Dashboard</RouterLink></li>
|
||||
<li><RouterLink to="/settings" @click="closeNav">Settings</RouterLink></li>
|
||||
</ul>
|
||||
|
||||
<ul class="nav-actions">
|
||||
|
|
@ -61,6 +62,7 @@ function closeNav() {
|
|||
<li><RouterLink to="/" @click="closeNav">Home</RouterLink></li>
|
||||
<template v-if="authStore.isLoggedIn">
|
||||
<li><RouterLink to="/dashboard" @click="closeNav">Dashboard</RouterLink></li>
|
||||
<li><RouterLink to="/settings" @click="closeNav">Settings</RouterLink></li>
|
||||
<li><button @click="authStore.logout(); closeNav()" class="secondary">Logout</button></li>
|
||||
</template>
|
||||
<template v-else>
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ const name = ref('');
|
|||
const description = ref('');
|
||||
const prizeDetails = ref('');
|
||||
const visibility = ref<'PUBLIC' | 'PRIVATE'>('PUBLIC');
|
||||
const randomizeRoutes = ref(false);
|
||||
const startDate = ref('');
|
||||
const locationLat = ref<number | null>(null);
|
||||
const locationLng = ref<number | null>(null);
|
||||
|
|
@ -80,7 +81,8 @@ async function handleSubmit() {
|
|||
locationLat: locationLat.value || undefined,
|
||||
locationLng: locationLng.value || undefined,
|
||||
searchRadius: searchRadius.value,
|
||||
rules: filteredRules.length > 0 ? filteredRules : undefined
|
||||
rules: filteredRules.length > 0 ? filteredRules : undefined,
|
||||
randomizeRoutes: randomizeRoutes.value
|
||||
});
|
||||
|
||||
router.push(`/games/${response.data.id}/edit`);
|
||||
|
|
@ -128,6 +130,12 @@ onUnmounted(() => {
|
|||
<option value="PRIVATE">Private (Invite Only)</option>
|
||||
</select>
|
||||
|
||||
<label for="randomizeRoutes">
|
||||
<input id="randomizeRoutes" v-model="randomizeRoutes" type="checkbox" role="switch" />
|
||||
Randomize Team Routes
|
||||
</label>
|
||||
<p><small>When enabled, teams will be randomly assigned routes when the game starts</small></p>
|
||||
|
||||
<label for="startDate">Start Date & Time</label>
|
||||
<input id="startDate" v-model="startDate" type="datetime-local" />
|
||||
|
||||
|
|
@ -154,7 +162,7 @@ onUnmounted(() => {
|
|||
<h2>Game Rules</h2>
|
||||
<p><small>Add rules for participants to follow during the game</small></p>
|
||||
|
||||
<div v-for="(rule, index) in rules" :key="index" class="grid" style="grid-template-columns: 1fr auto;">
|
||||
<div v-for="(_, index) in rules" :key="index" class="grid" style="grid-template-columns: 1fr auto;">
|
||||
<label :for="`rule-${index}`">
|
||||
Rule {{ index + 1 }}
|
||||
<input
|
||||
|
|
|
|||
|
|
@ -1,11 +1,9 @@
|
|||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed } from 'vue';
|
||||
import { RouterLink } from 'vue-router';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import type { Game } from '../types';
|
||||
import { gameService } from '../services/api';
|
||||
|
||||
const authStore = useAuthStore();
|
||||
const games = ref<Game[]>([]);
|
||||
const loading = ref(false);
|
||||
const showArchived = ref(false);
|
||||
|
|
@ -88,7 +86,7 @@ onMounted(() => {
|
|||
<footer>
|
||||
<small>
|
||||
<span :class="['status', game.status.toLowerCase()]">{{ game.status }}</span>
|
||||
· {{ game._count?.legs || 0 }} legs
|
||||
· {{ game._count?.routes || 0 }} routes
|
||||
· {{ game._count?.teams || 0 }} teams
|
||||
</small>
|
||||
</footer>
|
||||
|
|
|
|||
|
|
@ -1,24 +1,41 @@
|
|||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted, computed } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { ref, onMounted, onUnmounted, computed, watch, nextTick } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import L from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import type { Game, Leg } from '../types';
|
||||
import { gameService, legService } from '../services/api';
|
||||
import type { Game, Route } from '../types';
|
||||
import { gameService, routeService } from '../services/api';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const game = ref<Game | null>(null);
|
||||
const legs = ref<Leg[]>([]);
|
||||
const routes = ref<Route[]>([]);
|
||||
const selectedRouteId = ref<string | null>(null);
|
||||
const loading = ref(true);
|
||||
const saving = ref(false);
|
||||
|
||||
const gameId = computed(() => route.params.id as string);
|
||||
|
||||
const selectedRoute = computed(() =>
|
||||
routes.value.find(r => r.id === selectedRouteId.value) || null
|
||||
);
|
||||
|
||||
const mapContainer = ref<HTMLDivElement | null>(null);
|
||||
let map: L.Map | null = null;
|
||||
let markers: L.Marker[] = [];
|
||||
let routeMarkers: { [routeId: string]: L.Marker[] } = {};
|
||||
let mapInitialized = false;
|
||||
|
||||
const newRoute = ref({
|
||||
name: '',
|
||||
description: '',
|
||||
color: '#3498db'
|
||||
});
|
||||
|
||||
const editRoute = ref({
|
||||
name: '',
|
||||
description: '',
|
||||
color: ''
|
||||
});
|
||||
|
||||
const newLeg = ref({
|
||||
description: '',
|
||||
|
|
@ -29,12 +46,52 @@ const newLeg = ref({
|
|||
timeLimit: 30
|
||||
});
|
||||
|
||||
function startEditRoute() {
|
||||
if (selectedRoute.value) {
|
||||
editRoute.value = {
|
||||
name: selectedRoute.value.name,
|
||||
description: selectedRoute.value.description || '',
|
||||
color: selectedRoute.value.color
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function saveRoute() {
|
||||
if (!selectedRouteId.value) return;
|
||||
|
||||
saving.value = true;
|
||||
try {
|
||||
const response = await routeService.update(selectedRouteId.value, {
|
||||
name: editRoute.value.name,
|
||||
description: editRoute.value.description || undefined,
|
||||
color: editRoute.value.color
|
||||
});
|
||||
|
||||
const idx = routes.value.findIndex(r => r.id === selectedRouteId.value);
|
||||
if (idx >= 0) {
|
||||
routes.value[idx].name = response.data.name;
|
||||
routes.value[idx].description = response.data.description;
|
||||
routes.value[idx].color = response.data.color;
|
||||
}
|
||||
|
||||
updateMapMarkers();
|
||||
} catch (err) {
|
||||
alert('Failed to update route');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadGame() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const response = await gameService.get(gameId.value);
|
||||
game.value = response.data;
|
||||
legs.value = response.data.legs || [];
|
||||
routes.value = response.data.routes || [];
|
||||
|
||||
if (routes.value.length > 0 && !selectedRouteId.value) {
|
||||
selectedRouteId.value = routes.value[0].id;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load game:', err);
|
||||
} finally {
|
||||
|
|
@ -43,7 +100,7 @@ async function loadGame() {
|
|||
}
|
||||
|
||||
function initMap() {
|
||||
if (!mapContainer.value) return;
|
||||
if (!mapContainer.value || map) return;
|
||||
|
||||
const center = game.value?.locationLat && game.value?.locationLng
|
||||
? [game.value.locationLat, game.value.locationLng] as [number, number]
|
||||
|
|
@ -64,30 +121,109 @@ function initMap() {
|
|||
}).addTo(map);
|
||||
}
|
||||
|
||||
legs.value.forEach((leg, index) => {
|
||||
if (leg.locationLat && leg.locationLng) {
|
||||
const marker = L.marker([leg.locationLat, leg.locationLng])
|
||||
.addTo(map!)
|
||||
.bindPopup(`Leg ${index + 1}`);
|
||||
markers.push(marker);
|
||||
}
|
||||
});
|
||||
|
||||
map.on('click', (e: L.LeafletMouseEvent) => {
|
||||
newLeg.value.locationLat = e.latlng.lat;
|
||||
newLeg.value.locationLng = e.latlng.lng;
|
||||
});
|
||||
|
||||
updateMapMarkers();
|
||||
}
|
||||
|
||||
function updateMapMarkers() {
|
||||
if (!map) return;
|
||||
|
||||
Object.values(routeMarkers).forEach(markers => {
|
||||
markers.forEach(m => m.remove());
|
||||
});
|
||||
routeMarkers = {};
|
||||
|
||||
routes.value.forEach((route) => {
|
||||
const color = route.color || '#3498db';
|
||||
routeMarkers[route.id] = [];
|
||||
|
||||
route.routeLegs?.forEach((leg, legIndex) => {
|
||||
if (leg.locationLat && leg.locationLng) {
|
||||
const marker = L.marker([leg.locationLat, leg.locationLng], {
|
||||
icon: L.divIcon({
|
||||
className: `route-marker-${route.id}`,
|
||||
html: `<div style="background: ${color}; width: 20px; height: 20px; border-radius: 50%; border: 2px solid white; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 12px;">${legIndex + 1}</div>`,
|
||||
iconSize: [20, 20]
|
||||
})
|
||||
})
|
||||
.addTo(map!)
|
||||
.bindPopup(`${route.name} - Leg ${legIndex + 1}`);
|
||||
routeMarkers[route.id].push(marker);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
setTimeout(() => map?.invalidateSize(), 100);
|
||||
}
|
||||
|
||||
async function createRoute() {
|
||||
if (!newRoute.value.name.trim()) {
|
||||
alert('Please enter a route name');
|
||||
return;
|
||||
}
|
||||
|
||||
saving.value = true;
|
||||
try {
|
||||
const response = await routeService.create({
|
||||
gameId: gameId.value,
|
||||
name: newRoute.value.name,
|
||||
description: newRoute.value.description || undefined,
|
||||
color: newRoute.value.color
|
||||
});
|
||||
|
||||
routes.value.push(response.data);
|
||||
selectedRouteId.value = response.data.id;
|
||||
|
||||
newRoute.value = { name: '', description: '', color: '#3498db' };
|
||||
updateMapMarkers();
|
||||
} catch (err) {
|
||||
alert('Failed to create route');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function copyRoute(routeId: string) {
|
||||
try {
|
||||
const response = await routeService.copy(routeId);
|
||||
routes.value.push(response.data);
|
||||
selectedRouteId.value = response.data.id;
|
||||
updateMapMarkers();
|
||||
} catch (err) {
|
||||
alert('Failed to copy route');
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteRoute(routeId: string) {
|
||||
if (!confirm('Are you sure you want to delete this route and all its legs?')) return;
|
||||
|
||||
try {
|
||||
await routeService.delete(routeId);
|
||||
routes.value = routes.value.filter(r => r.id !== routeId);
|
||||
|
||||
if (selectedRouteId.value === routeId) {
|
||||
selectedRouteId.value = routes.value[0]?.id || null;
|
||||
}
|
||||
|
||||
updateMapMarkers();
|
||||
} catch (err) {
|
||||
alert('Failed to delete route');
|
||||
}
|
||||
}
|
||||
|
||||
async function addLeg() {
|
||||
if (!newLeg.value.description) {
|
||||
if (!selectedRouteId.value || !newLeg.value.description) {
|
||||
alert('Please enter a description');
|
||||
return;
|
||||
}
|
||||
|
||||
saving.value = true;
|
||||
try {
|
||||
const response = await legService.create(gameId.value, {
|
||||
const response = await routeService.addLeg(selectedRouteId.value, {
|
||||
description: newLeg.value.description,
|
||||
conditionType: newLeg.value.conditionType,
|
||||
conditionDetails: newLeg.value.conditionDetails || undefined,
|
||||
|
|
@ -96,7 +232,11 @@ async function addLeg() {
|
|||
timeLimit: newLeg.value.timeLimit
|
||||
});
|
||||
|
||||
legs.value.push(response.data);
|
||||
const route = routes.value.find(r => r.id === selectedRouteId.value);
|
||||
if (route) {
|
||||
if (!route.routeLegs) route.routeLegs = [];
|
||||
route.routeLegs.push(response.data);
|
||||
}
|
||||
|
||||
newLeg.value = {
|
||||
description: '',
|
||||
|
|
@ -107,18 +247,7 @@ async function addLeg() {
|
|||
timeLimit: 30
|
||||
};
|
||||
|
||||
if (map) {
|
||||
markers.forEach(m => m.remove());
|
||||
markers = [];
|
||||
legs.value.forEach((leg, index) => {
|
||||
if (leg.locationLat && leg.locationLng) {
|
||||
const marker = L.marker([leg.locationLat, leg.locationLng])
|
||||
.addTo(map!)
|
||||
.bindPopup(`Leg ${index + 1}`);
|
||||
markers.push(marker);
|
||||
}
|
||||
});
|
||||
}
|
||||
updateMapMarkers();
|
||||
} catch (err) {
|
||||
alert('Failed to add leg');
|
||||
} finally {
|
||||
|
|
@ -130,8 +259,14 @@ async function deleteLeg(legId: string) {
|
|||
if (!confirm('Are you sure you want to delete this leg?')) return;
|
||||
|
||||
try {
|
||||
await legService.delete(legId);
|
||||
legs.value = legs.value.filter(l => l.id !== legId);
|
||||
await routeService.deleteLeg(selectedRouteId.value!, legId);
|
||||
|
||||
const route = routes.value.find(r => r.id === selectedRouteId.value);
|
||||
if (route && route.routeLegs) {
|
||||
route.routeLegs = route.routeLegs.filter(l => l.id !== legId);
|
||||
}
|
||||
|
||||
updateMapMarkers();
|
||||
} catch (err) {
|
||||
alert('Failed to delete leg');
|
||||
}
|
||||
|
|
@ -148,14 +283,14 @@ function calculateDistance(lat1: number, lon1: number, lat2: number, lon2: numbe
|
|||
return R * c;
|
||||
}
|
||||
|
||||
function getTotalDistance(): number {
|
||||
if (!game.value?.locationLat || !game.value?.locationLng || legs.value.length === 0) return 0;
|
||||
function getRouteDistance(route: Route): number {
|
||||
if (!game.value?.locationLat || !game.value?.locationLng || !route.routeLegs?.length) return 0;
|
||||
|
||||
let total = 0;
|
||||
let prevLat = game.value.locationLat;
|
||||
let prevLng = game.value.locationLng;
|
||||
|
||||
for (const leg of legs.value) {
|
||||
for (const leg of route.routeLegs) {
|
||||
if (leg.locationLat && leg.locationLng) {
|
||||
total += calculateDistance(prevLat, prevLng, leg.locationLat, leg.locationLng);
|
||||
prevLat = leg.locationLat;
|
||||
|
|
@ -166,9 +301,35 @@ function getTotalDistance(): number {
|
|||
return total;
|
||||
}
|
||||
|
||||
function getTotalLegs(): number {
|
||||
return routes.value.reduce((sum, r) => sum + (r.routeLegs?.length || 0), 0);
|
||||
}
|
||||
|
||||
watch(selectedRouteId, async (newId) => {
|
||||
if (newId) {
|
||||
startEditRoute();
|
||||
if (!mapInitialized) {
|
||||
await nextTick();
|
||||
if (mapContainer.value) {
|
||||
initMap();
|
||||
mapInitialized = true;
|
||||
}
|
||||
} else {
|
||||
updateMapMarkers();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
loadGame().then(() => {
|
||||
setTimeout(initMap, 100);
|
||||
if (selectedRouteId.value) {
|
||||
setTimeout(() => {
|
||||
if (mapContainer.value && !mapInitialized) {
|
||||
initMap();
|
||||
mapInitialized = true;
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -192,31 +353,113 @@ onUnmounted(() => {
|
|||
|
||||
<div class="grid">
|
||||
<article>
|
||||
<h2>Legs ({{ legs.length }})</h2>
|
||||
<p><small>Total route distance: {{ getTotalDistance().toFixed(2) }} km</small></p>
|
||||
<h2>Routes ({{ routes.length }})</h2>
|
||||
<p><small>Total legs: {{ getTotalLegs() }}</small></p>
|
||||
|
||||
<article v-if="legs.length" v-for="(leg, index) in legs" :key="leg.id">
|
||||
<div v-for="routeItem in routes" :key="routeItem.id"
|
||||
class="route-card"
|
||||
:class="{ selected: selectedRouteId === routeItem.id }"
|
||||
@click="selectedRouteId = routeItem.id">
|
||||
<div class="route-header">
|
||||
<svg width="16" height="18" viewBox="0 0 16 18" :style="{ flexShrink: 0 }">
|
||||
<path d="M0 0h16v10c0 4-4 6-8 8-4-2-8-4-8-8V0z" :fill="routeItem.color" stroke="white" stroke-width="1"/>
|
||||
</svg>
|
||||
<h3>{{ routeItem.name }}</h3>
|
||||
<div class="route-actions">
|
||||
<button @click.stop="copyRoute(routeItem.id)" class="secondary outline">Copy</button>
|
||||
<button @click.stop="deleteRoute(routeItem.id)" class="contrast outline">Delete</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="routeItem.description">{{ routeItem.description }}</p>
|
||||
<footer>
|
||||
<small>
|
||||
{{ routeItem.routeLegs?.length || 0 }} legs
|
||||
· {{ getRouteDistance(routeItem).toFixed(2) }} km
|
||||
</small>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<details class="add-route" open>
|
||||
<summary>Add New Route</summary>
|
||||
<form @submit.prevent="createRoute">
|
||||
<label>
|
||||
Route Name
|
||||
<input v-model="newRoute.name" type="text" placeholder="e.g., Route A" required />
|
||||
</label>
|
||||
<label>
|
||||
Description (optional)
|
||||
<input v-model="newRoute.description" type="text" placeholder="e.g., Via downtown" />
|
||||
</label>
|
||||
<label class="color-label">
|
||||
Color
|
||||
<div style="display: flex; align-items: center; gap: 0.5rem;">
|
||||
<input v-model="newRoute.color" type="color" style="width: 40px; height: 40px; padding: 2px;" />
|
||||
<span :style="{ color: newRoute.color, fontWeight: 'bold' }">{{ newRoute.color }}</span>
|
||||
</div>
|
||||
</label>
|
||||
<button type="submit" :disabled="saving">
|
||||
{{ saving ? 'Creating...' : 'Create Route' }}
|
||||
</button>
|
||||
</form>
|
||||
</details>
|
||||
</article>
|
||||
|
||||
<article v-if="selectedRoute">
|
||||
<div class="route-header">
|
||||
<svg width="20" height="22" viewBox="0 0 16 18" :style="{ flexShrink: 0 }">
|
||||
<path d="M0 0h16v10c0 4-4 6-8 8-4-2-8-4-8-8V0z" :fill="selectedRoute.color" stroke="white" stroke-width="1"/>
|
||||
</svg>
|
||||
<h2>{{ selectedRoute.name }}</h2>
|
||||
<select v-model="selectedRouteId" style="max-width: 200px;">
|
||||
<option v-for="r in routes" :key="r.id" :value="r.id">
|
||||
{{ r.name }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<details>
|
||||
<summary>Edit Route</summary>
|
||||
<form @submit.prevent="saveRoute">
|
||||
<label>
|
||||
Route Name
|
||||
<input v-model="editRoute.name" type="text" required />
|
||||
</label>
|
||||
<label>
|
||||
Description
|
||||
<input v-model="editRoute.description" type="text" />
|
||||
</label>
|
||||
<label class="color-label">
|
||||
Color
|
||||
<div style="display: flex; align-items: center; gap: 0.5rem;">
|
||||
<input v-model="editRoute.color" type="color" style="width: 40px; height: 40px; padding: 2px;" />
|
||||
<span :style="{ color: editRoute.color, fontWeight: 'bold' }">{{ editRoute.color }}</span>
|
||||
</div>
|
||||
</label>
|
||||
<button type="submit" :disabled="saving">
|
||||
{{ saving ? 'Saving...' : 'Save Changes' }}
|
||||
</button>
|
||||
</form>
|
||||
</details>
|
||||
|
||||
<div v-if="selectedRoute.routeLegs?.length" v-for="(leg, index) in selectedRoute.routeLegs" :key="leg.id" class="leg-card">
|
||||
<div class="leg-header">
|
||||
<h3>Leg {{ index + 1 }}</h3>
|
||||
<button @click="deleteLeg(leg.id)" class="secondary">Delete</button>
|
||||
<button @click="deleteLeg(leg.id)" class="secondary outline">Delete</button>
|
||||
</div>
|
||||
<p>{{ leg.description }}</p>
|
||||
<footer>
|
||||
<small>
|
||||
Type: {{ leg.conditionType }}
|
||||
{{ leg.conditionType }}
|
||||
<span v-if="leg.timeLimit"> · {{ leg.timeLimit }} min</span>
|
||||
<span v-if="leg.locationLat && leg.locationLng">
|
||||
· {{ leg.locationLat.toFixed(4) }}, {{ leg.locationLng.toFixed(4) }}
|
||||
</span>
|
||||
</small>
|
||||
</footer>
|
||||
</article>
|
||||
<p v-else>No legs added yet</p>
|
||||
</article>
|
||||
|
||||
<article>
|
||||
<h2>Add New Leg</h2>
|
||||
</div>
|
||||
<p v-else>No legs in this route yet.</p>
|
||||
|
||||
<h3>Add Leg</h3>
|
||||
<div ref="mapContainer" class="map-container"></div>
|
||||
<p><small>Click on map to set location</small></p>
|
||||
|
||||
|
|
@ -256,6 +499,10 @@ onUnmounted(() => {
|
|||
</button>
|
||||
</form>
|
||||
</article>
|
||||
|
||||
<article v-else>
|
||||
<p>Select a route or create a new one to start adding legs.</p>
|
||||
</article>
|
||||
</div>
|
||||
</template>
|
||||
</main>
|
||||
|
|
@ -268,14 +515,56 @@ onUnmounted(() => {
|
|||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.leg-header {
|
||||
.route-card, .leg-card {
|
||||
margin-bottom: 1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.route-card.selected {
|
||||
border-color: var(--pico-primary-focus);
|
||||
}
|
||||
|
||||
.route-header, .leg-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 0.5rem;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.leg-header h3 {
|
||||
.route-header h3, .leg-header h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.route-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.add-route {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.add-route summary {
|
||||
cursor: pointer;
|
||||
padding: 0.5rem;
|
||||
background: var(--pico-muted-border-color);
|
||||
border-radius: var(--pico-border-radius);
|
||||
}
|
||||
|
||||
.add-route form {
|
||||
padding-top: 1rem;
|
||||
}
|
||||
|
||||
input[type="color"] {
|
||||
width: 100%;
|
||||
height: 40px;
|
||||
padding: 2px;
|
||||
border-radius: var(--pico-border-radius);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.color-label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
</style>
|
||||
|
|
|
|||
|
|
@ -5,14 +5,15 @@ import { io, Socket } from 'socket.io-client';
|
|||
import L from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import type { Game, Team, ChatMessage } from '../types';
|
||||
import { gameService, teamService } from '../services/api';
|
||||
import type { Game, Team, ChatMessage, Route } from '../types';
|
||||
import { gameService, teamService, routeService } from '../services/api';
|
||||
|
||||
const route = useRoute();
|
||||
const authStore = useAuthStore();
|
||||
|
||||
const game = ref<Game | null>(null);
|
||||
const teams = ref<Team[]>([]);
|
||||
const routes = ref<Route[]>([]);
|
||||
const chatMessages = ref<ChatMessage[]>([]);
|
||||
const loading = ref(true);
|
||||
|
||||
|
|
@ -28,12 +29,14 @@ const selectedTeam = ref<Team | null>(null);
|
|||
async function loadGame() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const [gameRes, teamsRes] = await Promise.all([
|
||||
const [gameRes, teamsRes, routesRes] = await Promise.all([
|
||||
gameService.get(gameId.value),
|
||||
teamService.getByGame(gameId.value)
|
||||
teamService.getByGame(gameId.value),
|
||||
routeService.getByGame(gameId.value)
|
||||
]);
|
||||
game.value = gameRes.data;
|
||||
teams.value = teamsRes.data;
|
||||
routes.value = routesRes.data;
|
||||
} catch (err) {
|
||||
console.error('Failed to load game:', err);
|
||||
} finally {
|
||||
|
|
@ -57,9 +60,35 @@ function initMap() {
|
|||
fillOpacity: 0.1
|
||||
}).addTo(map);
|
||||
|
||||
routes.value.forEach((route) => {
|
||||
const color = route.color || '#3498db';
|
||||
route.routeLegs?.forEach((leg, legIndex) => {
|
||||
if (leg.locationLat && leg.locationLng) {
|
||||
const legIcon = L.divIcon({
|
||||
className: 'route-leg-marker',
|
||||
html: `<div style="background:${color}; width:24px; height:24px; border-radius:50%; border:2px solid white; display:flex; align-items:center; justify-content:center; color:white; font-weight:bold; font-size:12px;">${legIndex + 1}</div>`,
|
||||
iconSize: [24, 24],
|
||||
iconAnchor: [12, 12]
|
||||
});
|
||||
L.marker([leg.locationLat, leg.locationLng], { icon: legIcon })
|
||||
.addTo(map!)
|
||||
.bindPopup(`${route.name} - Leg ${legIndex + 1}: ${leg.description}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
teams.value.forEach(team => {
|
||||
if (team.lat && team.lng) {
|
||||
const marker = L.marker([team.lat, team.lng])
|
||||
const teamRoute = team.teamRoutes?.[0];
|
||||
const teamRouteData = routes.value.find(r => r.id === teamRoute?.routeId);
|
||||
const color = teamRouteData?.color || '#666';
|
||||
const teamIcon = L.divIcon({
|
||||
className: 'team-marker',
|
||||
html: `<div style="background:${color}; width:20px; height:20px; border-radius:50%; border:2px solid white; box-shadow:0 2px 4px rgba(0,0,0,0.3);"></div>`,
|
||||
iconSize: [20, 20],
|
||||
iconAnchor: [10, 10]
|
||||
});
|
||||
const marker = L.marker([team.lat, team.lng], { icon: teamIcon })
|
||||
.addTo(map!)
|
||||
.bindPopup(team.name);
|
||||
teamMarkers[team.id] = marker;
|
||||
|
|
@ -196,7 +225,8 @@ onUnmounted(() => {
|
|||
<footer>
|
||||
<small>
|
||||
{{ team.members?.length || 0 }} members ·
|
||||
Leg {{ game.legs?.findIndex(l => l.id === team.currentLegId) + 1 || 0 }} / {{ game.legs?.length || 0 }}
|
||||
Route: {{ team.teamRoutes?.[0]?.route?.name || 'Not assigned' }} ·
|
||||
Leg {{ team.currentLegIndex + 1 }}
|
||||
<span v-if="team.totalTimeDeduction"> · -{{ team.totalTimeDeduction }}s</span>
|
||||
</small>
|
||||
</footer>
|
||||
|
|
|
|||
|
|
@ -155,26 +155,13 @@ onMounted(() => {
|
|||
</ul>
|
||||
</section>
|
||||
|
||||
<section v-if="game.legs?.length">
|
||||
<h2>Legs ({{ game.legs.length }})</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Description</th>
|
||||
<th>Type</th>
|
||||
<th>Time</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="leg in game.legs" :key="leg.id">
|
||||
<td>{{ leg.sequenceNumber }}</td>
|
||||
<td>{{ leg.description }}</td>
|
||||
<td>{{ leg.conditionType }}</td>
|
||||
<td>{{ leg.timeLimit ? `${leg.timeLimit} min` : '-' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<section v-if="game.routes?.length">
|
||||
<h2>Routes ({{ game.routes.length }})</h2>
|
||||
<div v-for="route in game.routes" :key="route.id" class="route-info">
|
||||
<h3>{{ route.name }}</h3>
|
||||
<p v-if="route.description">{{ route.description }}</p>
|
||||
<p><small>{{ route.routeLegs?.length || 0 }} legs</small></p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="game.teams?.length">
|
||||
|
|
@ -183,6 +170,7 @@ onMounted(() => {
|
|||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Route</th>
|
||||
<th>Status</th>
|
||||
<th>Members</th>
|
||||
</tr>
|
||||
|
|
@ -190,6 +178,7 @@ onMounted(() => {
|
|||
<tbody>
|
||||
<tr v-for="team in game.teams" :key="team.id">
|
||||
<td>{{ team.name }}</td>
|
||||
<td>{{ team.teamRoutes?.[0]?.route?.name || 'Not assigned' }}</td>
|
||||
<td><span :class="['status', team.status.toLowerCase()]">{{ team.status }}</span></td>
|
||||
<td>{{ team.members?.length || 0 }}</td>
|
||||
</tr>
|
||||
|
|
|
|||
|
|
@ -68,7 +68,7 @@ onMounted(() => {
|
|||
<h3>{{ game.name }}</h3>
|
||||
<p v-if="game.description">{{ game.description.slice(0, 100) }}...</p>
|
||||
<footer>
|
||||
<small>{{ game._count?.legs || 0 }} legs · {{ game._count?.teams || 0 }} teams</small>
|
||||
<small>{{ game._count?.routes || 0 }} routes · {{ game._count?.teams || 0 }} teams</small>
|
||||
<small v-if="game.startDate">{{ new Date(game.startDate).toLocaleDateString() }}</small>
|
||||
</footer>
|
||||
</RouterLink>
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { io, Socket } from 'socket.io-client';
|
|||
import L from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import type { Game, Team, ChatMessage } from '../types';
|
||||
import type { Game, Team, ChatMessage, Route, RouteLeg } from '../types';
|
||||
import { teamService, uploadService } from '../services/api';
|
||||
|
||||
const route = useRoute();
|
||||
|
|
@ -28,22 +28,27 @@ const showPhotoUpload = ref(false);
|
|||
const photoFile = ref<File | null>(null);
|
||||
const uploading = ref(false);
|
||||
|
||||
const currentLegIndex = computed(() => {
|
||||
if (!team.value?.currentLegId || !game.value?.legs) return -1;
|
||||
return game.value.legs.findIndex(l => l.id === team.value!.currentLegId);
|
||||
const currentRoute = computed<Route | null>(() => {
|
||||
return team.value?.teamRoutes?.[0]?.route || null;
|
||||
});
|
||||
|
||||
const currentLeg = computed(() => {
|
||||
if (currentLegIndex.value < 0 || !game.value?.legs) return null;
|
||||
return game.value.legs[currentLegIndex.value];
|
||||
const currentLegIndex = computed(() => team.value?.currentLegIndex ?? -1);
|
||||
|
||||
const currentLeg = computed<RouteLeg | null>(() => {
|
||||
if (currentRoute.value && currentLegIndex.value >= 0) {
|
||||
return currentRoute.value.routeLegs?.[currentLegIndex.value] || null;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const totalLegs = computed(() => currentRoute.value?.routeLegs?.length || 0);
|
||||
|
||||
async function loadTeam() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const response = await teamService.get(gameId.value);
|
||||
team.value = response.data;
|
||||
game.value = response.data.game;
|
||||
game.value = response.data.game || null;
|
||||
|
||||
if (team.value?.lat && team.value?.lng && map) {
|
||||
teamMarker = L.marker([team.value.lat, team.value.lng]).addTo(map);
|
||||
|
|
@ -166,7 +171,7 @@ async function submitPhoto() {
|
|||
uploading.value = true;
|
||||
try {
|
||||
const uploadRes = await uploadService.upload(photoFile.value);
|
||||
await fetch(`http://localhost:3001/api/legs/${currentLeg.value.id}/photo`, {
|
||||
await fetch(`http://localhost:3001/api/routes/${currentRoute.value?.id}/legs/${currentLeg.value.id}/photo`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
|
|
@ -191,14 +196,6 @@ async function submitPhoto() {
|
|||
function handleVisibilityChange() {
|
||||
if (document.hidden) {
|
||||
alert('Warning: Leaving the game tab may result in time penalties!');
|
||||
if (game.value?.timeDeductionPenalty && socket) {
|
||||
socket.emit('chat-message', {
|
||||
gameId: gameId.value,
|
||||
message: `Warning: ${authStore.user?.name} navigated away from the game`,
|
||||
userId: authStore.user?.id || '',
|
||||
userName: authStore.user?.name || ''
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -237,6 +234,7 @@ onUnmounted(() => {
|
|||
<p>{{ currentLeg.description }}</p>
|
||||
<footer>
|
||||
<small>
|
||||
Route: {{ currentRoute?.name }} ·
|
||||
Type: {{ currentLeg.conditionType }}
|
||||
<span v-if="currentLeg.timeLimit"> · Time limit: {{ currentLeg.timeLimit }} min</span>
|
||||
</small>
|
||||
|
|
@ -251,6 +249,7 @@ onUnmounted(() => {
|
|||
|
||||
<article v-else>
|
||||
<p v-if="team.status === 'FINISHED'">🎉 Congratulations! You've completed the hunt!</p>
|
||||
<p v-else-if="!currentRoute">Waiting for route assignment...</p>
|
||||
<p v-else>Waiting for the game to start...</p>
|
||||
</article>
|
||||
|
||||
|
|
@ -258,9 +257,9 @@ onUnmounted(() => {
|
|||
<h3>Progress</h3>
|
||||
<progress
|
||||
:value="currentLegIndex + 1"
|
||||
:max="game.legs?.length || 1"
|
||||
:max="totalLegs || 1"
|
||||
></progress>
|
||||
<p><small>Leg {{ currentLegIndex + 1 }} of {{ game.legs?.length || 0 }}</small></p>
|
||||
<p><small>Leg {{ currentLegIndex + 1 }} of {{ totalLegs }}</small></p>
|
||||
<p v-if="team.totalTimeDeduction" class="error">
|
||||
<small>Time penalty: {{ team.totalTimeDeduction }} seconds</small>
|
||||
</p>
|
||||
|
|
|
|||
477
frontend/src/pages/SettingsPage.vue
Normal file
477
frontend/src/pages/SettingsPage.vue
Normal 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>
|
||||
|
|
@ -4,13 +4,14 @@ import { useRoute } from 'vue-router';
|
|||
import { io, Socket } from 'socket.io-client';
|
||||
import L from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import type { Game, Team } from '../types';
|
||||
import { gameService, teamService } from '../services/api';
|
||||
import type { Game, Team, Route } from '../types';
|
||||
import { gameService, teamService, routeService } from '../services/api';
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
const game = ref<Game | null>(null);
|
||||
const teams = ref<Team[]>([]);
|
||||
const routes = ref<Route[]>([]);
|
||||
const loading = ref(true);
|
||||
|
||||
const gameId = computed(() => route.params.id as string);
|
||||
|
|
@ -23,9 +24,9 @@ const leaderboard = computed(() => {
|
|||
return [...teams.value]
|
||||
.filter(t => t.status === 'ACTIVE' || t.status === 'FINISHED')
|
||||
.sort((a, b) => {
|
||||
const aLegIndex = game.value?.legs?.findIndex(l => l.id === a.currentLegId) || 0;
|
||||
const bLegIndex = game.value?.legs?.findIndex(l => l.id === b.currentLegId) || 0;
|
||||
if (aLegIndex !== bLegIndex) return bLegIndex - aLegIndex;
|
||||
if (a.status === 'FINISHED' && b.status !== 'FINISHED') return -1;
|
||||
if (b.status === 'FINISHED' && a.status !== 'FINISHED') return 1;
|
||||
if (a.currentLegIndex !== b.currentLegIndex) return b.currentLegIndex - a.currentLegIndex;
|
||||
return a.totalTimeDeduction - b.totalTimeDeduction;
|
||||
});
|
||||
});
|
||||
|
|
@ -33,12 +34,14 @@ const leaderboard = computed(() => {
|
|||
async function loadGame() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const [gameRes, teamsRes] = await Promise.all([
|
||||
const [gameRes, teamsRes, routesRes] = await Promise.all([
|
||||
gameService.get(gameId.value),
|
||||
teamService.getByGame(gameId.value)
|
||||
teamService.getByGame(gameId.value),
|
||||
routeService.getByGame(gameId.value)
|
||||
]);
|
||||
game.value = gameRes.data;
|
||||
teams.value = teamsRes.data;
|
||||
routes.value = routesRes.data;
|
||||
} catch (err) {
|
||||
console.error('Failed to load game:', err);
|
||||
} finally {
|
||||
|
|
@ -62,9 +65,35 @@ function initMap() {
|
|||
fillOpacity: 0.1
|
||||
}).addTo(map);
|
||||
|
||||
routes.value.forEach((route) => {
|
||||
const color = route.color || '#3498db';
|
||||
route.routeLegs?.forEach((leg, legIndex) => {
|
||||
if (leg.locationLat && leg.locationLng) {
|
||||
const legIcon = L.divIcon({
|
||||
className: 'route-leg-marker',
|
||||
html: `<div style="background:${color}; width:20px; height:20px; border-radius:50%; border:2px solid white; display:flex; align-items:center; justify-content:center; color:white; font-weight:bold; font-size:10px;">${legIndex + 1}</div>`,
|
||||
iconSize: [20, 20],
|
||||
iconAnchor: [10, 10]
|
||||
});
|
||||
L.marker([leg.locationLat, leg.locationLng], { icon: legIcon })
|
||||
.addTo(map!)
|
||||
.bindPopup(`${route.name} - Leg ${legIndex + 1}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
teams.value.forEach(team => {
|
||||
if (team.lat && team.lng) {
|
||||
const marker = L.marker([team.lat, team.lng])
|
||||
const teamRoute = team.teamRoutes?.[0];
|
||||
const teamRouteData = routes.value.find(r => r.id === teamRoute?.routeId);
|
||||
const color = teamRouteData?.color || '#666';
|
||||
const teamIcon = L.divIcon({
|
||||
className: 'team-marker',
|
||||
html: `<div style="background:${color}; width:16px; height:16px; border-radius:50%; border:2px solid white; box-shadow:0 2px 4px rgba(0,0,0,0.3);"></div>`,
|
||||
iconSize: [16, 16],
|
||||
iconAnchor: [8, 8]
|
||||
});
|
||||
const marker = L.marker([team.lat, team.lng], { icon: teamIcon })
|
||||
.addTo(map!)
|
||||
.bindPopup(team.name);
|
||||
teamMarkers[team.id] = marker;
|
||||
|
|
@ -145,7 +174,8 @@ onUnmounted(() => {
|
|||
</div>
|
||||
<footer>
|
||||
<small>
|
||||
Leg {{ game.legs?.findIndex(l => l.id === team.currentLegId) + 1 || 0 }}/{{ game.legs?.length || 0 }}
|
||||
{{ team.teamRoutes?.[0]?.route?.name || 'No route' }} ·
|
||||
Leg {{ team.currentLegIndex + 1 }}
|
||||
<span v-if="team.totalTimeDeduction" class="error"> · -{{ team.totalTimeDeduction }}s</span>
|
||||
</small>
|
||||
</footer>
|
||||
|
|
|
|||
|
|
@ -67,6 +67,12 @@ const router = createRouter({
|
|||
name: 'invite',
|
||||
component: () => import('../pages/InvitePage.vue'),
|
||||
},
|
||||
{
|
||||
path: '/settings',
|
||||
name: 'settings',
|
||||
component: () => import('../pages/SettingsPage.vue'),
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import axios from 'axios';
|
||||
import type { Game, Leg, Team, User, AuthResponse } from '../types';
|
||||
import type { Game, Route, RouteLeg, Team, User, AuthResponse, LocationHistory, UserGameHistory } from '../types';
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: 'http://localhost:3001/api',
|
||||
|
|
@ -37,13 +37,21 @@ export const gameService = {
|
|||
getInvite: (id: string) => api.get<{ inviteCode: string }>(`/games/${id}/invite`),
|
||||
};
|
||||
|
||||
export const legService = {
|
||||
getByGame: (gameId: string) => api.get<Leg[]>(`/legs/game/${gameId}`),
|
||||
create: (gameId: string, data: Partial<Leg>) => api.post<Leg>(`/legs/game/${gameId}`, data),
|
||||
update: (legId: string, data: Partial<Leg>) => api.put<Leg>(`/legs/${legId}`, data),
|
||||
delete: (legId: string) => api.delete(`/legs/${legId}`),
|
||||
submitPhoto: (legId: string, data: { teamId: string; photoUrl: string }) =>
|
||||
api.post(`/legs/${legId}/photo`, data),
|
||||
export const routeService = {
|
||||
getByGame: (gameId: string) => api.get<Route[]>(`/routes/game/${gameId}`),
|
||||
get: (routeId: string) => api.get<Route>(`/routes/${routeId}`),
|
||||
create: (data: { gameId: string; name: string; description?: string; color?: string }) =>
|
||||
api.post<Route>('/routes', data),
|
||||
update: (routeId: string, data: Partial<Route>) =>
|
||||
api.put<Route>(`/routes/${routeId}`, data),
|
||||
delete: (routeId: string) => api.delete(`/routes/${routeId}`),
|
||||
copy: (routeId: string) => api.post<Route>(`/routes/${routeId}/copy`),
|
||||
addLeg: (routeId: string, data: Partial<RouteLeg>) =>
|
||||
api.post<RouteLeg>(`/routes/${routeId}/legs`, data),
|
||||
updateLeg: (routeId: string, legId: string, data: Partial<RouteLeg>) =>
|
||||
api.put<RouteLeg>(`/routes/${routeId}/legs/${legId}`, data),
|
||||
deleteLeg: (routeId: string, legId: string) =>
|
||||
api.delete(`/routes/${routeId}/legs/${legId}`),
|
||||
};
|
||||
|
||||
export const teamService = {
|
||||
|
|
@ -52,6 +60,8 @@ export const teamService = {
|
|||
get: (teamId: string) => api.get<Team>(`/teams/${teamId}`),
|
||||
join: (teamId: string) => api.post(`/teams/${teamId}/join`),
|
||||
leave: (teamId: string) => api.post(`/teams/${teamId}/leave`),
|
||||
assignRoute: (teamId: string, routeId: string) =>
|
||||
api.post(`/teams/${teamId}/assign-route`, { routeId }),
|
||||
advance: (teamId: string) => api.post<Team>(`/teams/${teamId}/advance`),
|
||||
deduct: (teamId: string, seconds: number) => api.post<Team>(`/teams/${teamId}/deduct`, { seconds }),
|
||||
disqualify: (teamId: string) => api.post<Team>(`/teams/${teamId}/disqualify`),
|
||||
|
|
@ -69,4 +79,14 @@ export const uploadService = {
|
|||
},
|
||||
};
|
||||
|
||||
export const userService = {
|
||||
getProfile: () => api.get<User>('/users/me'),
|
||||
updateProfile: (data: { name?: string; screenName?: string; avatarUrl?: string }) =>
|
||||
api.put<User>('/users/me', data),
|
||||
getLocationHistory: () => api.get<{ totalLocations: number; byGame: { game: { id: string; name: string }; locations: LocationHistory[]; locationCount: number }[] }>('/users/me/location-history'),
|
||||
getGamesHistory: () => api.get<UserGameHistory[]>('/users/me/games'),
|
||||
deleteLocationData: () => api.delete('/users/me/location-data'),
|
||||
deleteAccount: () => api.delete('/users/me/account'),
|
||||
};
|
||||
|
||||
export default api;
|
||||
|
|
|
|||
|
|
@ -2,9 +2,48 @@ export interface User {
|
|||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
screenName?: string;
|
||||
avatarUrl?: string;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
export interface LocationHistory {
|
||||
id: string;
|
||||
userId: string;
|
||||
gameId: string;
|
||||
teamId: string;
|
||||
lat: number;
|
||||
lng: number;
|
||||
accuracy?: number;
|
||||
recordedAt: string;
|
||||
game?: { id: string; name: string };
|
||||
}
|
||||
|
||||
export interface UserGameHistory {
|
||||
gameId: string;
|
||||
gameName: string;
|
||||
gameStatus: string;
|
||||
gameMaster: string;
|
||||
startDate?: string;
|
||||
teamId: string;
|
||||
teamName: string;
|
||||
teamStatus: string;
|
||||
routeId?: string;
|
||||
routeName?: string;
|
||||
routeColor?: string;
|
||||
totalLegs: number;
|
||||
totalDistance: number;
|
||||
proofLocations: ProofLocation[];
|
||||
}
|
||||
|
||||
export interface ProofLocation {
|
||||
legNumber: number;
|
||||
description: string;
|
||||
locationLat?: number;
|
||||
locationLng?: number;
|
||||
hasPhotoProof: boolean;
|
||||
}
|
||||
|
||||
export interface Game {
|
||||
id: string;
|
||||
name: string;
|
||||
|
|
@ -16,20 +55,33 @@ export interface Game {
|
|||
locationLng?: number;
|
||||
searchRadius?: number;
|
||||
rules?: string[];
|
||||
randomizeRoutes?: boolean;
|
||||
status: 'DRAFT' | 'LIVE' | 'ENDED' | 'ARCHIVED';
|
||||
inviteCode?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
gameMasterId: string;
|
||||
gameMaster?: User;
|
||||
legs?: Leg[];
|
||||
routes?: Route[];
|
||||
teams?: Team[];
|
||||
_count?: { teams: number; legs: number };
|
||||
_count?: { teams: number; routes: number };
|
||||
}
|
||||
|
||||
export interface Leg {
|
||||
export interface Route {
|
||||
id: string;
|
||||
gameId: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
color: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
routeLegs?: RouteLeg[];
|
||||
_count?: { teamRoutes: number };
|
||||
}
|
||||
|
||||
export interface RouteLeg {
|
||||
id: string;
|
||||
routeId: string;
|
||||
sequenceNumber: number;
|
||||
description: string;
|
||||
conditionType: string;
|
||||
|
|
@ -45,8 +97,7 @@ export interface Team {
|
|||
name: string;
|
||||
captainId?: string;
|
||||
captain?: User;
|
||||
currentLegId?: string;
|
||||
currentLeg?: Leg;
|
||||
currentLegIndex: number;
|
||||
status: 'ACTIVE' | 'DISQUALIFIED' | 'FINISHED';
|
||||
totalTimeDeduction: number;
|
||||
lat?: number;
|
||||
|
|
@ -54,6 +105,16 @@ export interface Team {
|
|||
rank?: number;
|
||||
createdAt: string;
|
||||
members?: TeamMember[];
|
||||
teamRoutes?: TeamRoute[];
|
||||
game?: Game;
|
||||
}
|
||||
|
||||
export interface TeamRoute {
|
||||
id: string;
|
||||
teamId: string;
|
||||
routeId: string;
|
||||
assignedAt: string;
|
||||
route?: Route;
|
||||
}
|
||||
|
||||
export interface TeamMember {
|
||||
|
|
@ -67,7 +128,7 @@ export interface TeamMember {
|
|||
export interface PhotoSubmission {
|
||||
id: string;
|
||||
teamId: string;
|
||||
legId: string;
|
||||
routeLegId: string;
|
||||
photoUrl: string;
|
||||
approved: boolean;
|
||||
submittedAt: string;
|
||||
|
|
|
|||
2
node_modules/.package-lock.json
generated
vendored
2
node_modules/.package-lock.json
generated
vendored
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"name": "scavenge",
|
||||
"name": "TreasureTrails",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
|
|
|||
2
package-lock.json
generated
2
package-lock.json
generated
|
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"name": "scavenge",
|
||||
"name": "TreasureTrails",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue