Refaktoryzacja struktury i podział modułów (app/admin/api), konsolidacja testów w test/, komunikator (lista kontaktów, załącznik bez treści), profil podopiecznego (menu kontekstowe, nagłówek, zapamiętywanie zakładki), Tabs: strzałki poza scrollem + scroll-snap do całych zakładek, podniesione limity rate-limit
This commit is contained in:
@@ -3,9 +3,15 @@ import rateLimit from 'express-rate-limit';
|
||||
/** Standard error body — spójny z resztą API (JSON, nie plain text). */
|
||||
export const RATE_LIMIT_BODY = { error: { code: 'RATE_LIMITED', message: 'Too many requests, try later' } };
|
||||
|
||||
/**
|
||||
* Globalny limit per IP. SPA robi dużo równoległych zapytań (strona = kilka
|
||||
* query React Query, staleTime=0 refetchuje przy nawigacji), a app i admin
|
||||
* dzielą jedno IP — limit musi być wysoki, żeby normalne korzystanie nie
|
||||
* blokowało nawet logowania. Ochronę anty-brute-force robi authLimiter.
|
||||
*/
|
||||
export const apiLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
limit: 300,
|
||||
limit: 1500,
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: RATE_LIMIT_BODY,
|
||||
@@ -13,7 +19,7 @@ export const apiLimiter = rateLimit({
|
||||
|
||||
export const authLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
limit: 20,
|
||||
limit: 50,
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: { error: { code: 'RATE_LIMITED', message: 'Too many attempts, try later' } },
|
||||
|
||||
@@ -1,119 +1,35 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type { AppDeps } from '../deps.js';
|
||||
import { authenticate } from '../middleware/auth.js';
|
||||
import { validate } from '../middleware/validate.js';
|
||||
import {
|
||||
acceptGymInvitation,
|
||||
addEquipment,
|
||||
addGymPhotos,
|
||||
canManageGym,
|
||||
createGym,
|
||||
createGymClaim,
|
||||
createOwnedGymException,
|
||||
declineGymInvitation,
|
||||
deleteGymPhoto,
|
||||
deleteOwnedGym,
|
||||
deleteOwnedGymException,
|
||||
getGymPublic,
|
||||
joinGym,
|
||||
listAllGyms,
|
||||
listGymInvitations,
|
||||
listMyGymClaims,
|
||||
listOwnedGymExceptions,
|
||||
listUserGyms,
|
||||
listVirtualGyms,
|
||||
rateGym,
|
||||
removeEquipment,
|
||||
searchGymInvitees,
|
||||
sendGymInvitation,
|
||||
setGymPhotoCover,
|
||||
updateEquipmentQuantity,
|
||||
updateOwnedGym,
|
||||
withdrawGymClaim,
|
||||
withdrawGymInvitation,
|
||||
} from '../services/gyms.js';
|
||||
import { availabilitySchema } from './me.js';
|
||||
import type { Availability } from '../services/me.js';
|
||||
import { logActivity } from '../services/audit.js';
|
||||
import { config } from '../config.js';
|
||||
import {
|
||||
MAX_CLAIM_FILES,
|
||||
MAX_PHOTO_FILES,
|
||||
claimUpload,
|
||||
gymPhotoUpload,
|
||||
photoUploadDir,
|
||||
removeTmpFiles,
|
||||
} from '../lib/uploads.js';
|
||||
import { badRequest, forbidden, notFound } from '../lib/errors.js';
|
||||
import { createGymSchema, rateGymSchema, updateGymSchema } from './gyms/schemas.js';
|
||||
import { createGymClaimRoutes } from './gyms/claims.js';
|
||||
import { createGymInvitationRoutes } from './gyms/invitations.js';
|
||||
import { createGymPhotoRoutes } from './gyms/photos.js';
|
||||
import { createGymManagementRoutes } from './gyms/management.js';
|
||||
|
||||
const createGymSchema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
location: z.string().max(500).nullable().optional(),
|
||||
availability: availabilitySchema,
|
||||
capacity: z.number().int().positive().max(100000).nullable().optional(),
|
||||
kind: z.enum(['VIRTUAL', 'REAL']).optional(),
|
||||
isPrivate: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const updateGymSchema = createGymSchema.partial().omit({ kind: true });
|
||||
|
||||
const rateGymSchema = z.object({
|
||||
vote: z.enum(['UP', 'DOWN']),
|
||||
});
|
||||
|
||||
/** Multipart fields arrive as strings (multer) — gymAvailability is a JSON string. */
|
||||
const gymClaimSchema = z.object({
|
||||
gymId: z.string().min(1).optional(),
|
||||
description: z.string().min(1).max(5000),
|
||||
companyName: z.string().max(200).optional(),
|
||||
nip: z.string().regex(/^\d{10}$/).optional(),
|
||||
phone: z.string().max(20).optional(),
|
||||
email: z.string().email().max(200).optional(),
|
||||
address: z.string().max(500).optional(),
|
||||
gymName: z.string().min(1).max(200).optional(),
|
||||
gymLocation: z.string().max(500).optional(),
|
||||
gymAvailability: z.string().optional(),
|
||||
gymCapacity: z.coerce.number().int().positive().max(100000).optional(),
|
||||
});
|
||||
|
||||
const gymInvitationSchema = z.object({
|
||||
gymId: z.string().min(1),
|
||||
userId: z.string().min(1),
|
||||
});
|
||||
|
||||
const gymInviteeSearchSchema = z.object({
|
||||
gymId: z.string().min(1),
|
||||
firstName: z.string().min(1).max(100),
|
||||
lastName: z.string().min(1).max(100),
|
||||
});
|
||||
|
||||
const gymExceptionSchema = z.object({
|
||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
availability: z
|
||||
.object({
|
||||
start: z.string().regex(/^\d{2}:\d{2}$/),
|
||||
end: z.string().regex(/^\d{2}:\d{2}$/),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const equipmentSchema = z.object({
|
||||
equipmentId: z.string().min(1),
|
||||
quantity: z.number().int().min(1).max(10000).optional(),
|
||||
});
|
||||
|
||||
const equipmentQuantitySchema = z.object({
|
||||
quantity: z.number().int().min(1).max(10000),
|
||||
});
|
||||
|
||||
export function createGymRoutes({ prisma }: AppDeps) {
|
||||
export function createGymRoutes(deps: AppDeps) {
|
||||
const { prisma } = deps;
|
||||
const router = Router();
|
||||
router.use(authenticate(prisma));
|
||||
|
||||
// Static prefixes first — before any /:gymId handler.
|
||||
router.use('/claims', createGymClaimRoutes(deps));
|
||||
router.use('/invitations', createGymInvitationRoutes(deps));
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms:
|
||||
@@ -122,7 +38,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
*/
|
||||
*/
|
||||
router.get('/', async (req, res, next) => {
|
||||
try {
|
||||
const result = await listUserGyms(prisma, req.user!.id);
|
||||
@@ -140,7 +56,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
*/
|
||||
*/
|
||||
router.get('/all', async (_req, res, next) => {
|
||||
try {
|
||||
const result = await listAllGyms(prisma);
|
||||
@@ -160,7 +76,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
* 201: { description: Created }
|
||||
* 400: { description: Validation failed (e.g. missing location for VIRTUAL) }
|
||||
* 403: { description: Non-admin requested kind=REAL }
|
||||
*/
|
||||
*/
|
||||
router.post('/', validate(createGymSchema), async (req, res, next) => {
|
||||
try {
|
||||
const data = req.body as z.infer<typeof createGymSchema>;
|
||||
@@ -186,7 +102,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
*/
|
||||
*/
|
||||
router.get('/virtual', async (req, res, next) => {
|
||||
try {
|
||||
const result = await listVirtualGyms(prisma, req.user!.id);
|
||||
@@ -196,284 +112,9 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/claims:
|
||||
* post:
|
||||
* summary: Submit a gym claim (multipart; verification of a virtual gym or a new real gym)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 201: { description: Created }
|
||||
* 400: { description: Validation failed (fields or files) }
|
||||
* 404: { description: Gym not found }
|
||||
* 409: { description: Gym is not virtual / pending claim already exists }
|
||||
*/
|
||||
router.post(
|
||||
'/claims',
|
||||
(req, res, next) =>
|
||||
claimUpload.array('files', MAX_CLAIM_FILES)(req, res, (err) => {
|
||||
if (err) {
|
||||
const message =
|
||||
err.code === 'LIMIT_FILE_SIZE'
|
||||
? 'File too large (max 5 MB)'
|
||||
: err.code === 'LIMIT_FILE_COUNT'
|
||||
? 'Too many files (max 5)'
|
||||
: err.message;
|
||||
return next(badRequest(message));
|
||||
}
|
||||
next();
|
||||
}),
|
||||
validate(gymClaimSchema),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const body = req.body as z.infer<typeof gymClaimSchema>;
|
||||
let gymAvailability: Availability | null | undefined;
|
||||
if (body.gymAvailability) {
|
||||
try {
|
||||
gymAvailability = availabilitySchema.parse(JSON.parse(body.gymAvailability));
|
||||
} catch {
|
||||
throw badRequest('Invalid gym availability');
|
||||
}
|
||||
}
|
||||
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
|
||||
originalName: f.originalname,
|
||||
mimeType: f.mimetype,
|
||||
sizeBytes: f.size,
|
||||
path: f.path,
|
||||
}));
|
||||
const result = await createGymClaim(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
{
|
||||
gymId: body.gymId,
|
||||
description: body.description,
|
||||
companyName: body.companyName,
|
||||
nip: body.nip,
|
||||
phone: body.phone,
|
||||
email: body.email,
|
||||
address: body.address,
|
||||
gymName: body.gymName,
|
||||
gymLocation: body.gymLocation,
|
||||
gymAvailability,
|
||||
gymCapacity: body.gymCapacity,
|
||||
},
|
||||
files,
|
||||
);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.claim.created',
|
||||
entityType: 'gym-claim',
|
||||
entityId: result.claim.id,
|
||||
details: { gymId: result.claim.gymId, type: result.claim.type },
|
||||
});
|
||||
res.status(201).json(result);
|
||||
} catch (e) {
|
||||
removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })));
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/claims:
|
||||
* get:
|
||||
* summary: The user's own gym claims (all statuses)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
*/
|
||||
router.get('/claims', async (req, res, next) => {
|
||||
try {
|
||||
const result = await listMyGymClaims(prisma, req.user!.id);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/claims/{claimId}:
|
||||
* delete:
|
||||
* summary: Withdraw the user's own PENDING gym claim
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 204: { description: Withdrawn }
|
||||
* 403: { description: Not the claim author }
|
||||
* 409: { description: Claim is not pending }
|
||||
*/
|
||||
router.delete('/claims/:claimId', async (req, res, next) => {
|
||||
try {
|
||||
await withdrawGymClaim(prisma, req.user!.id, req.params.claimId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.claim.withdrawn',
|
||||
entityType: 'gym-claim',
|
||||
entityId: req.params.claimId,
|
||||
});
|
||||
res.status(204).end();
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations:
|
||||
* post:
|
||||
* summary: Invite a user to a private virtual gym (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 201: { description: Invitation sent }
|
||||
* 400: { description: Cannot invite yourself }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Gym or user not found }
|
||||
* 409: { description: Gym not private virtual / already a member / pending invitation exists }
|
||||
*/
|
||||
router.post('/invitations', validate(gymInvitationSchema), async (req, res, next) => {
|
||||
try {
|
||||
const { gymId, userId } = req.body as z.infer<typeof gymInvitationSchema>;
|
||||
const result = await sendGymInvitation(prisma, req.user!.id, gymId, userId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.invited',
|
||||
entityType: 'gym-invitation',
|
||||
entityId: result.invitation.id,
|
||||
details: { gymId, userId },
|
||||
});
|
||||
res.status(201).json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations:
|
||||
* get:
|
||||
* summary: The user's pending gym invitations (sent and received)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
*/
|
||||
router.get('/invitations', async (req, res, next) => {
|
||||
try {
|
||||
const result = await listGymInvitations(prisma, req.user!.id);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations/search:
|
||||
* get:
|
||||
* summary: Search users to invite to a private virtual gym (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Gym not found }
|
||||
*/
|
||||
router.get(
|
||||
'/invitations/search',
|
||||
validate(gymInviteeSearchSchema, 'query'),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const q = req.query as z.infer<typeof gymInviteeSearchSchema>;
|
||||
const result = await searchGymInvitees(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
q.gymId,
|
||||
q.firstName,
|
||||
q.lastName,
|
||||
);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations/{invitationId}/accept:
|
||||
* post:
|
||||
* summary: Accept a gym invitation (invited user only) → MEMBER
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: Accepted }
|
||||
* 403: { description: Not the invited user }
|
||||
* 410: { description: Invitation expired }
|
||||
*/
|
||||
router.post('/invitations/:invitationId/accept', async (req, res, next) => {
|
||||
try {
|
||||
const result = await acceptGymInvitation(prisma, req.user!.id, req.params.invitationId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.invitation.accepted',
|
||||
entityType: 'gym-invitation',
|
||||
entityId: req.params.invitationId,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations/{invitationId}/decline:
|
||||
* post:
|
||||
* summary: Decline a gym invitation (invited user only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: Declined }
|
||||
* 403: { description: Not the invited user }
|
||||
* 410: { description: Invitation expired }
|
||||
*/
|
||||
router.post('/invitations/:invitationId/decline', async (req, res, next) => {
|
||||
try {
|
||||
const result = await declineGymInvitation(prisma, req.user!.id, req.params.invitationId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.invitation.declined',
|
||||
entityType: 'gym-invitation',
|
||||
entityId: req.params.invitationId,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations/{invitationId}:
|
||||
* delete:
|
||||
* summary: Withdraw a pending gym invitation (sender only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 204: { description: Withdrawn }
|
||||
* 403: { description: Not the sender }
|
||||
* 409: { description: Invitation is not pending }
|
||||
*/
|
||||
router.delete('/invitations/:invitationId', async (req, res, next) => {
|
||||
try {
|
||||
await withdrawGymInvitation(prisma, req.user!.id, req.params.invitationId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.invitation.withdrawn',
|
||||
entityType: 'gym-invitation',
|
||||
entityId: req.params.invitationId,
|
||||
});
|
||||
res.status(204).end();
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
// Per-gym sub-routes: gallery photos, then equipment/exceptions.
|
||||
router.use('/:gymId/photos', createGymPhotoRoutes(deps));
|
||||
router.use('/:gymId', createGymManagementRoutes(deps));
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
@@ -485,7 +126,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
* 200: { description: OK, returns { gym, roles, isAdmin } }
|
||||
* 403: { description: VIRTUAL gym and the caller is not a manager }
|
||||
* 404: { description: Gym not found }
|
||||
*/
|
||||
*/
|
||||
router.get('/:gymId', async (req, res, next) => {
|
||||
try {
|
||||
const result = await getGymPublic(prisma, req.user!.id, req.user!.isAdmin, req.params.gymId);
|
||||
@@ -495,160 +136,6 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/photos:
|
||||
* post:
|
||||
* summary: Add photos to a REAL gym's gallery (owner or admin; multipart field `photos`)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK, returns { gym } }
|
||||
* 400: { description: Validation failed (file type/size/count or photo limit) }
|
||||
* 403: { description: Not the gym owner and not an admin }
|
||||
* 404: { description: Gym not found }
|
||||
* 409: { description: Gym is not REAL }
|
||||
*/
|
||||
router.post(
|
||||
'/:gymId/photos',
|
||||
(req, res, next) =>
|
||||
gymPhotoUpload.array('photos', MAX_PHOTO_FILES)(req, res, (err) => {
|
||||
if (err) {
|
||||
const message =
|
||||
err.code === 'LIMIT_FILE_SIZE'
|
||||
? 'File too large (max 5 MB)'
|
||||
: err.code === 'LIMIT_FILE_COUNT'
|
||||
? 'Too many files (max 10)'
|
||||
: err.message;
|
||||
return next(badRequest(message));
|
||||
}
|
||||
next();
|
||||
}),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
|
||||
mimeType: f.mimetype,
|
||||
sizeBytes: f.size,
|
||||
path: f.path,
|
||||
}));
|
||||
const result = await addGymPhotos(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
req.user!.isAdmin,
|
||||
req.params.gymId,
|
||||
files,
|
||||
);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.photos.added',
|
||||
entityType: 'gym',
|
||||
entityId: req.params.gymId,
|
||||
details: { count: files.length },
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })));
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/photos/{photoId}:
|
||||
* delete:
|
||||
* summary: Remove a photo from a gym's gallery (owner or admin)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK, returns { gym } }
|
||||
* 403: { description: Not the gym owner and not an admin }
|
||||
* 404: { description: Photo not found }
|
||||
*/
|
||||
router.delete('/:gymId/photos/:photoId', async (req, res, next) => {
|
||||
try {
|
||||
const result = await deleteGymPhoto(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
req.user!.isAdmin,
|
||||
req.params.gymId,
|
||||
req.params.photoId,
|
||||
);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.photo.deleted',
|
||||
entityType: 'gym',
|
||||
entityId: req.params.gymId,
|
||||
details: { photoId: req.params.photoId },
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/photos/{photoId}/cover:
|
||||
* patch:
|
||||
* summary: Set a photo as the gallery cover (owner or admin)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK, returns { gym } }
|
||||
* 403: { description: Not the gym owner and not an admin }
|
||||
* 404: { description: Photo not found }
|
||||
*/
|
||||
router.patch('/:gymId/photos/:photoId/cover', async (req, res, next) => {
|
||||
try {
|
||||
const result = await setGymPhotoCover(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
req.user!.isAdmin,
|
||||
req.params.gymId,
|
||||
req.params.photoId,
|
||||
);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.photo.cover',
|
||||
entityType: 'gym',
|
||||
entityId: req.params.gymId,
|
||||
details: { photoId: req.params.photoId },
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/photos/{photoId}:
|
||||
* get:
|
||||
* summary: Serve a gym photo (REAL visible to all logged-in users; VIRTUAL to managers)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: Image bytes with the stored Content-Type }
|
||||
* 403: { description: VIRTUAL gym and the caller is not a manager }
|
||||
* 404: { description: Photo not found or file missing }
|
||||
*/
|
||||
router.get('/:gymId/photos/:photoId', async (req, res, next) => {
|
||||
try {
|
||||
const { gymId, photoId } = req.params;
|
||||
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
|
||||
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
|
||||
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
if (gym.kind !== 'REAL' && !(await canManageGym(prisma, gymId, req.user!.id, req.user!.isAdmin)))
|
||||
throw forbidden('You do not have access to this gym');
|
||||
const filePath = path.join(photoUploadDir(gymId), photo.storedName);
|
||||
if (!fs.existsSync(filePath)) throw notFound('Photo file not found');
|
||||
res.type(photo.mimeType);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
res.sendFile(filePath, (err) => (err ? reject(err) : resolve()));
|
||||
});
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/join:
|
||||
@@ -658,7 +145,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
* responses:
|
||||
* 201: { description: Joined }
|
||||
* 409: { description: Already a member }
|
||||
*/
|
||||
*/
|
||||
router.post('/:gymId/join', async (req, res, next) => {
|
||||
try {
|
||||
const result = await joinGym(prisma, req.user!.id, req.params.gymId);
|
||||
@@ -686,7 +173,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
* 403: { description: The gym owner cannot rate their own gym }
|
||||
* 404: { description: Gym not found }
|
||||
* 409: { description: Gym is not a public virtual gym }
|
||||
*/
|
||||
*/
|
||||
router.post('/:gymId/rate', validate(rateGymSchema), async (req, res, next) => {
|
||||
try {
|
||||
const { vote } = req.body as z.infer<typeof rateGymSchema>;
|
||||
@@ -697,88 +184,6 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment:
|
||||
* post:
|
||||
* summary: Add a catalog equipment item to a gym with a quantity (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Equipment not found }
|
||||
* 409: { description: Equipment already exists (update its quantity instead) }
|
||||
*/
|
||||
router.post(
|
||||
'/:gymId/equipment',
|
||||
validate(equipmentSchema),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const { equipmentId, quantity } = req.body as z.infer<typeof equipmentSchema>;
|
||||
const result = await addEquipment(
|
||||
prisma,
|
||||
req.params.gymId,
|
||||
req.user!.id,
|
||||
equipmentId,
|
||||
quantity ?? 1,
|
||||
);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment/{equipmentId}:
|
||||
* patch:
|
||||
* summary: Change the quantity of a gym's equipment item (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 400: { description: Equipment not in the gym }
|
||||
*/
|
||||
router.patch(
|
||||
'/:gymId/equipment/:equipmentId',
|
||||
validate(equipmentQuantitySchema),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const { quantity } = req.body as z.infer<typeof equipmentQuantitySchema>;
|
||||
const result = await updateEquipmentQuantity(
|
||||
prisma,
|
||||
req.params.gymId,
|
||||
req.user!.id,
|
||||
req.params.equipmentId,
|
||||
quantity,
|
||||
);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment/{equipmentId}:
|
||||
* delete:
|
||||
* summary: Remove a catalog equipment item from a gym (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 204: { description: Removed }
|
||||
* 403: { description: Not the gym owner }
|
||||
*/
|
||||
router.delete('/:gymId/equipment/:equipmentId', async (req, res, next) => {
|
||||
try {
|
||||
await removeEquipment(prisma, req.params.gymId, req.user!.id, req.params.equipmentId);
|
||||
res.status(204).end();
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}:
|
||||
@@ -789,7 +194,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
* 200: { description: OK }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Gym not found }
|
||||
*/
|
||||
*/
|
||||
router.patch('/:gymId', validate(updateGymSchema), async (req, res, next) => {
|
||||
try {
|
||||
const data = req.body as z.infer<typeof updateGymSchema>;
|
||||
@@ -817,7 +222,7 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
* 204: { description: Deleted }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Gym not found }
|
||||
*/
|
||||
*/
|
||||
router.delete('/:gymId', async (req, res, next) => {
|
||||
try {
|
||||
const result = await deleteOwnedGym(prisma, req.params.gymId, req.user!.id);
|
||||
@@ -834,77 +239,5 @@ export function createGymRoutes({ prisma }: AppDeps) {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/exceptions:
|
||||
* get:
|
||||
* summary: List a gym's schedule exceptions (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 403: { description: Not the gym owner }
|
||||
*/
|
||||
router.get('/:gymId/exceptions', async (req, res, next) => {
|
||||
try {
|
||||
const result = await listOwnedGymExceptions(prisma, req.params.gymId, req.user!.id);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/exceptions:
|
||||
* post:
|
||||
* summary: Add a one-off schedule exception (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 201: { description: Created }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 409: { description: Exception already exists for this date }
|
||||
*/
|
||||
router.post(
|
||||
'/:gymId/exceptions',
|
||||
validate(gymExceptionSchema),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const data = req.body as z.infer<typeof gymExceptionSchema>;
|
||||
const result = await createOwnedGymException(prisma, req.params.gymId, req.user!.id, {
|
||||
date: data.date,
|
||||
availability: data.availability ?? null,
|
||||
});
|
||||
res.status(201).json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/exceptions/{exceptionId}:
|
||||
* delete:
|
||||
* summary: Remove a schedule exception (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 204: { description: Removed }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Exception not found }
|
||||
*/
|
||||
router.delete('/:gymId/exceptions/:exceptionId', async (req, res, next) => {
|
||||
try {
|
||||
await deleteOwnedGymException(
|
||||
prisma,
|
||||
req.params.gymId,
|
||||
req.user!.id,
|
||||
req.params.exceptionId,
|
||||
);
|
||||
res.status(204).end();
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
140
api/src/routes/gyms/claims.ts
Normal file
140
api/src/routes/gyms/claims.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type { AppDeps } from '../../deps.js';
|
||||
import { validate } from '../../middleware/validate.js';
|
||||
import { createGymClaim, listMyGymClaims, withdrawGymClaim } from '../../services/gyms.js';
|
||||
import { availabilitySchema } from '../me.js';
|
||||
import type { Availability } from '../../services/me.js';
|
||||
import { logActivity } from '../../services/audit.js';
|
||||
import { MAX_CLAIM_FILES, claimUpload, removeTmpFiles } from '../../lib/uploads.js';
|
||||
import { badRequest } from '../../lib/errors.js';
|
||||
import { gymClaimSchema } from './schemas.js';
|
||||
|
||||
/** Mounted at /gyms/claims. */
|
||||
export function createGymClaimRoutes({ prisma }: AppDeps) {
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/claims:
|
||||
* post:
|
||||
* summary: Submit a gym claim (multipart; verification of a virtual gym or a new real gym)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 201: { description: Created }
|
||||
* 400: { description: Validation failed (fields or files) }
|
||||
* 404: { description: Gym not found }
|
||||
* 409: { description: Gym is not virtual / pending claim already exists }
|
||||
*/
|
||||
router.post(
|
||||
'/',
|
||||
(req, res, next) =>
|
||||
claimUpload.array('files', MAX_CLAIM_FILES)(req, res, (err) => {
|
||||
if (err) {
|
||||
const message =
|
||||
err.code === 'LIMIT_FILE_SIZE'
|
||||
? 'File too large (max 5 MB)'
|
||||
: err.code === 'LIMIT_FILE_COUNT'
|
||||
? 'Too many files (max 5)'
|
||||
: err.message;
|
||||
return next(badRequest(message));
|
||||
}
|
||||
next();
|
||||
}),
|
||||
validate(gymClaimSchema),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const body = req.body as z.infer<typeof gymClaimSchema>;
|
||||
let gymAvailability: Availability | null | undefined;
|
||||
if (body.gymAvailability) {
|
||||
try {
|
||||
gymAvailability = availabilitySchema.parse(JSON.parse(body.gymAvailability));
|
||||
} catch {
|
||||
throw badRequest('Invalid gym availability');
|
||||
}
|
||||
}
|
||||
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
|
||||
originalName: f.originalname,
|
||||
mimeType: f.mimetype,
|
||||
sizeBytes: f.size,
|
||||
path: f.path,
|
||||
}));
|
||||
const result = await createGymClaim(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
{
|
||||
gymId: body.gymId,
|
||||
description: body.description,
|
||||
companyName: body.companyName,
|
||||
nip: body.nip,
|
||||
phone: body.phone,
|
||||
email: body.email,
|
||||
address: body.address,
|
||||
gymName: body.gymName,
|
||||
gymLocation: body.gymLocation,
|
||||
gymAvailability,
|
||||
gymCapacity: body.gymCapacity,
|
||||
},
|
||||
files,
|
||||
);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.claim.created',
|
||||
entityType: 'gym-claim',
|
||||
entityId: result.claim.id,
|
||||
details: { gymId: result.claim.gymId, type: result.claim.type },
|
||||
});
|
||||
res.status(201).json(result);
|
||||
} catch (e) {
|
||||
removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })));
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/claims:
|
||||
* get:
|
||||
* summary: The user's own gym claims (all statuses)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
*/
|
||||
router.get('/', async (req, res, next) => {
|
||||
try {
|
||||
const result = await listMyGymClaims(prisma, req.user!.id);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/claims/{claimId}:
|
||||
* delete:
|
||||
* summary: Withdraw the user's own PENDING gym claim
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 204: { description: Withdrawn }
|
||||
* 403: { description: Not the claim author }
|
||||
* 409: { description: Claim is not pending }
|
||||
*/
|
||||
router.delete('/:claimId', async (req, res, next) => {
|
||||
try {
|
||||
await withdrawGymClaim(prisma, req.user!.id, req.params.claimId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.claim.withdrawn',
|
||||
entityType: 'gym-claim',
|
||||
entityId: req.params.claimId,
|
||||
});
|
||||
res.status(204).end();
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
178
api/src/routes/gyms/invitations.ts
Normal file
178
api/src/routes/gyms/invitations.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type { AppDeps } from '../../deps.js';
|
||||
import { validate } from '../../middleware/validate.js';
|
||||
import {
|
||||
acceptGymInvitation,
|
||||
declineGymInvitation,
|
||||
listGymInvitations,
|
||||
searchGymInvitees,
|
||||
sendGymInvitation,
|
||||
withdrawGymInvitation,
|
||||
} from '../../services/gyms.js';
|
||||
import { logActivity } from '../../services/audit.js';
|
||||
import { gymInvitationSchema, gymInviteeSearchSchema } from './schemas.js';
|
||||
|
||||
/** Mounted at /gyms/invitations. */
|
||||
export function createGymInvitationRoutes({ prisma }: AppDeps) {
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations:
|
||||
* post:
|
||||
* summary: Invite a user to a private virtual gym (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 201: { description: Invitation sent }
|
||||
* 400: { description: Cannot invite yourself }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Gym or user not found }
|
||||
* 409: { description: Gym not private virtual / already a member / pending invitation exists }
|
||||
*/
|
||||
router.post('/', validate(gymInvitationSchema), async (req, res, next) => {
|
||||
try {
|
||||
const { gymId, userId } = req.body as z.infer<typeof gymInvitationSchema>;
|
||||
const result = await sendGymInvitation(prisma, req.user!.id, gymId, userId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.invited',
|
||||
entityType: 'gym-invitation',
|
||||
entityId: result.invitation.id,
|
||||
details: { gymId, userId },
|
||||
});
|
||||
res.status(201).json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations:
|
||||
* get:
|
||||
* summary: The user's pending gym invitations (sent and received)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
*/
|
||||
router.get('/', async (req, res, next) => {
|
||||
try {
|
||||
const result = await listGymInvitations(prisma, req.user!.id);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations/search:
|
||||
* get:
|
||||
* summary: Search users to invite to a private virtual gym (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Gym not found }
|
||||
*/
|
||||
router.get(
|
||||
'/search',
|
||||
validate(gymInviteeSearchSchema, 'query'),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const q = req.query as z.infer<typeof gymInviteeSearchSchema>;
|
||||
const result = await searchGymInvitees(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
q.gymId,
|
||||
q.firstName,
|
||||
q.lastName,
|
||||
);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations/{invitationId}/accept:
|
||||
* post:
|
||||
* summary: Accept a gym invitation (invited user only) → MEMBER
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: Accepted }
|
||||
* 403: { description: Not the invited user }
|
||||
* 410: { description: Invitation expired }
|
||||
*/
|
||||
router.post('/:invitationId/accept', async (req, res, next) => {
|
||||
try {
|
||||
const result = await acceptGymInvitation(prisma, req.user!.id, req.params.invitationId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.invitation.accepted',
|
||||
entityType: 'gym-invitation',
|
||||
entityId: req.params.invitationId,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations/{invitationId}/decline:
|
||||
* post:
|
||||
* summary: Decline a gym invitation (invited user only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: Declined }
|
||||
* 403: { description: Not the invited user }
|
||||
* 410: { description: Invitation expired }
|
||||
*/
|
||||
router.post('/:invitationId/decline', async (req, res, next) => {
|
||||
try {
|
||||
const result = await declineGymInvitation(prisma, req.user!.id, req.params.invitationId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.invitation.declined',
|
||||
entityType: 'gym-invitation',
|
||||
entityId: req.params.invitationId,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/invitations/{invitationId}:
|
||||
* delete:
|
||||
* summary: Withdraw a pending gym invitation (sender only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 204: { description: Withdrawn }
|
||||
* 403: { description: Not the sender }
|
||||
* 409: { description: Invitation is not pending }
|
||||
*/
|
||||
router.delete('/:invitationId', async (req, res, next) => {
|
||||
try {
|
||||
await withdrawGymInvitation(prisma, req.user!.id, req.params.invitationId);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.invitation.withdrawn',
|
||||
entityType: 'gym-invitation',
|
||||
entityId: req.params.invitationId,
|
||||
});
|
||||
res.status(204).end();
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
182
api/src/routes/gyms/management.ts
Normal file
182
api/src/routes/gyms/management.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type { AppDeps } from '../../deps.js';
|
||||
import { validate } from '../../middleware/validate.js';
|
||||
import {
|
||||
addEquipment,
|
||||
createOwnedGymException,
|
||||
deleteOwnedGymException,
|
||||
listOwnedGymExceptions,
|
||||
removeEquipment,
|
||||
updateEquipmentQuantity,
|
||||
} from '../../services/gyms.js';
|
||||
import { equipmentQuantitySchema, equipmentSchema, gymExceptionSchema } from './schemas.js';
|
||||
|
||||
type GymParams = { gymId: string };
|
||||
|
||||
/** Mounted at /gyms/:gymId (mergeParams) — equipment and schedule exceptions. */
|
||||
export function createGymManagementRoutes({ prisma }: AppDeps) {
|
||||
const router = Router({ mergeParams: true });
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment:
|
||||
* post:
|
||||
* summary: Add a catalog equipment item to a gym with a quantity (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Equipment not found }
|
||||
* 409: { description: Equipment already exists (update its quantity instead) }
|
||||
*/
|
||||
router.post(
|
||||
'/equipment',
|
||||
validate(equipmentSchema),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const { equipmentId, quantity } = req.body as z.infer<typeof equipmentSchema>;
|
||||
const { gymId } = req.params as GymParams;
|
||||
const result = await addEquipment(
|
||||
prisma,
|
||||
gymId,
|
||||
req.user!.id,
|
||||
equipmentId,
|
||||
quantity ?? 1,
|
||||
);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment/{equipmentId}:
|
||||
* patch:
|
||||
* summary: Change the quantity of a gym's equipment item (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 400: { description: Equipment not in the gym }
|
||||
*/
|
||||
router.patch(
|
||||
'/equipment/:equipmentId',
|
||||
validate(equipmentQuantitySchema),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const { quantity } = req.body as z.infer<typeof equipmentQuantitySchema>;
|
||||
const { gymId } = req.params as GymParams;
|
||||
const result = await updateEquipmentQuantity(
|
||||
prisma,
|
||||
gymId,
|
||||
req.user!.id,
|
||||
req.params.equipmentId,
|
||||
quantity,
|
||||
);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/equipment/{equipmentId}:
|
||||
* delete:
|
||||
* summary: Remove a catalog equipment item from a gym (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 204: { description: Removed }
|
||||
* 403: { description: Not the gym owner }
|
||||
*/
|
||||
router.delete('/equipment/:equipmentId', async (req, res, next) => {
|
||||
try {
|
||||
const { gymId, equipmentId } = req.params as GymParams & { equipmentId: string };
|
||||
await removeEquipment(prisma, gymId, req.user!.id, equipmentId);
|
||||
res.status(204).end();
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/exceptions:
|
||||
* get:
|
||||
* summary: List a gym's schedule exceptions (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK }
|
||||
* 403: { description: Not the gym owner }
|
||||
*/
|
||||
router.get('/exceptions', async (req, res, next) => {
|
||||
try {
|
||||
const { gymId } = req.params as GymParams;
|
||||
const result = await listOwnedGymExceptions(prisma, gymId, req.user!.id);
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/exceptions:
|
||||
* post:
|
||||
* summary: Add a one-off schedule exception (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 201: { description: Created }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 409: { description: Exception already exists for this date }
|
||||
*/
|
||||
router.post(
|
||||
'/exceptions',
|
||||
validate(gymExceptionSchema),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const data = req.body as z.infer<typeof gymExceptionSchema>;
|
||||
const { gymId } = req.params as GymParams;
|
||||
const result = await createOwnedGymException(prisma, gymId, req.user!.id, {
|
||||
date: data.date,
|
||||
availability: data.availability ?? null,
|
||||
});
|
||||
res.status(201).json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/exceptions/{exceptionId}:
|
||||
* delete:
|
||||
* summary: Remove a schedule exception (owner only)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 204: { description: Removed }
|
||||
* 403: { description: Not the gym owner }
|
||||
* 404: { description: Exception not found }
|
||||
*/
|
||||
router.delete('/exceptions/:exceptionId', async (req, res, next) => {
|
||||
try {
|
||||
const { gymId, exceptionId } = req.params as GymParams & { exceptionId: string };
|
||||
await deleteOwnedGymException(
|
||||
prisma,
|
||||
gymId,
|
||||
req.user!.id,
|
||||
exceptionId,
|
||||
);
|
||||
res.status(204).end();
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
179
api/src/routes/gyms/photos.ts
Normal file
179
api/src/routes/gyms/photos.ts
Normal file
@@ -0,0 +1,179 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Router } from 'express';
|
||||
import type { AppDeps } from '../../deps.js';
|
||||
import {
|
||||
addGymPhotos,
|
||||
canManageGym,
|
||||
deleteGymPhoto,
|
||||
setGymPhotoCover,
|
||||
} from '../../services/gyms.js';
|
||||
import { logActivity } from '../../services/audit.js';
|
||||
import { MAX_PHOTO_FILES, gymPhotoUpload, photoUploadDir, removeTmpFiles } from '../../lib/uploads.js';
|
||||
import { badRequest, forbidden, notFound } from '../../lib/errors.js';
|
||||
|
||||
type GymParams = { gymId: string };
|
||||
|
||||
/** Mounted at /gyms/:gymId/photos (mergeParams). */
|
||||
export function createGymPhotoRoutes({ prisma }: AppDeps) {
|
||||
const router = Router({ mergeParams: true });
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/photos:
|
||||
* post:
|
||||
* summary: Add photos to a REAL gym's gallery (owner or admin; multipart field `photos`)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK, returns { gym } }
|
||||
* 400: { description: Validation failed (file type/size/count or photo limit) }
|
||||
* 403: { description: Not the gym owner and not an admin }
|
||||
* 404: { description: Gym not found }
|
||||
* 409: { description: Gym is not REAL }
|
||||
*/
|
||||
router.post(
|
||||
'/',
|
||||
(req, res, next) =>
|
||||
gymPhotoUpload.array('photos', MAX_PHOTO_FILES)(req, res, (err) => {
|
||||
if (err) {
|
||||
const message =
|
||||
err.code === 'LIMIT_FILE_SIZE'
|
||||
? 'File too large (max 5 MB)'
|
||||
: err.code === 'LIMIT_FILE_COUNT'
|
||||
? 'Too many files (max 10)'
|
||||
: err.message;
|
||||
return next(badRequest(message));
|
||||
}
|
||||
next();
|
||||
}),
|
||||
async (req, res, next) => {
|
||||
const { gymId } = req.params as GymParams;
|
||||
try {
|
||||
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
|
||||
mimeType: f.mimetype,
|
||||
sizeBytes: f.size,
|
||||
path: f.path,
|
||||
}));
|
||||
const result = await addGymPhotos(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
req.user!.isAdmin,
|
||||
gymId,
|
||||
files,
|
||||
);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.photos.added',
|
||||
entityType: 'gym',
|
||||
entityId: gymId,
|
||||
details: { count: files.length },
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })));
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/photos/{photoId}:
|
||||
* delete:
|
||||
* summary: Remove a photo from a gym's gallery (owner or admin)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK, returns { gym } }
|
||||
* 403: { description: Not the gym owner and not an admin }
|
||||
* 404: { description: Photo not found }
|
||||
*/
|
||||
router.delete('/:photoId', async (req, res, next) => {
|
||||
const { gymId, photoId } = req.params as GymParams & { photoId: string };
|
||||
try {
|
||||
const result = await deleteGymPhoto(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
req.user!.isAdmin,
|
||||
gymId,
|
||||
photoId,
|
||||
);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.photo.deleted',
|
||||
entityType: 'gym',
|
||||
entityId: gymId,
|
||||
details: { photoId },
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/photos/{photoId}/cover:
|
||||
* patch:
|
||||
* summary: Set a photo as the gallery cover (owner or admin)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: OK, returns { gym } }
|
||||
* 403: { description: Not the gym owner and not an admin }
|
||||
* 404: { description: Photo not found }
|
||||
*/
|
||||
router.patch('/:photoId/cover', async (req, res, next) => {
|
||||
const { gymId, photoId } = req.params as GymParams & { photoId: string };
|
||||
try {
|
||||
const result = await setGymPhotoCover(
|
||||
prisma,
|
||||
req.user!.id,
|
||||
req.user!.isAdmin,
|
||||
gymId,
|
||||
photoId,
|
||||
);
|
||||
await logActivity(prisma, {
|
||||
actorId: req.user!.id,
|
||||
action: 'gym.photo.cover',
|
||||
entityType: 'gym',
|
||||
entityId: gymId,
|
||||
details: { photoId },
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /gyms/{gymId}/photos/{photoId}:
|
||||
* get:
|
||||
* summary: Serve a gym photo (REAL visible to all logged-in users; VIRTUAL to managers)
|
||||
* tags: [Gyms]
|
||||
* responses:
|
||||
* 200: { description: Image bytes with the stored Content-Type }
|
||||
* 403: { description: VIRTUAL gym and the caller is not a manager }
|
||||
* 404: { description: Photo not found or file missing }
|
||||
*/
|
||||
router.get('/:photoId', async (req, res, next) => {
|
||||
try {
|
||||
const { gymId, photoId } = req.params as GymParams & { photoId: string };
|
||||
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
|
||||
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
|
||||
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
if (gym.kind !== 'REAL' && !(await canManageGym(prisma, gymId, req.user!.id, req.user!.isAdmin)))
|
||||
throw forbidden('You do not have access to this gym');
|
||||
const filePath = path.join(photoUploadDir(gymId), photo.storedName);
|
||||
if (!fs.existsSync(filePath)) throw notFound('Photo file not found');
|
||||
res.type(photo.mimeType);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
res.sendFile(filePath, (err) => (err ? reject(err) : resolve()));
|
||||
});
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
63
api/src/routes/gyms/schemas.ts
Normal file
63
api/src/routes/gyms/schemas.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { z } from 'zod';
|
||||
import { availabilitySchema } from '../me.js';
|
||||
|
||||
export const createGymSchema = z.object({
|
||||
name: z.string().min(1).max(200),
|
||||
location: z.string().max(500).nullable().optional(),
|
||||
availability: availabilitySchema,
|
||||
capacity: z.number().int().positive().max(100000).nullable().optional(),
|
||||
kind: z.enum(['VIRTUAL', 'REAL']).optional(),
|
||||
isPrivate: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const updateGymSchema = createGymSchema.partial().omit({ kind: true });
|
||||
|
||||
export const rateGymSchema = z.object({
|
||||
vote: z.enum(['UP', 'DOWN']),
|
||||
});
|
||||
|
||||
/** Multipart fields arrive as strings (multer) — gymAvailability is a JSON string. */
|
||||
export const gymClaimSchema = z.object({
|
||||
gymId: z.string().min(1).optional(),
|
||||
description: z.string().min(1).max(5000),
|
||||
companyName: z.string().max(200).optional(),
|
||||
nip: z.string().regex(/^\d{10}$/).optional(),
|
||||
phone: z.string().max(20).optional(),
|
||||
email: z.string().email().max(200).optional(),
|
||||
address: z.string().max(500).optional(),
|
||||
gymName: z.string().min(1).max(200).optional(),
|
||||
gymLocation: z.string().max(500).optional(),
|
||||
gymAvailability: z.string().optional(),
|
||||
gymCapacity: z.coerce.number().int().positive().max(100000).optional(),
|
||||
});
|
||||
|
||||
export const gymInvitationSchema = z.object({
|
||||
gymId: z.string().min(1),
|
||||
userId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const gymInviteeSearchSchema = z.object({
|
||||
gymId: z.string().min(1),
|
||||
firstName: z.string().min(1).max(100),
|
||||
lastName: z.string().min(1).max(100),
|
||||
});
|
||||
|
||||
export const gymExceptionSchema = z.object({
|
||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
availability: z
|
||||
.object({
|
||||
start: z.string().regex(/^\d{2}:\d{2}$/),
|
||||
end: z.string().regex(/^\d{2}:\d{2}$/),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const equipmentSchema = z.object({
|
||||
equipmentId: z.string().min(1),
|
||||
quantity: z.number().int().min(1).max(10000).optional(),
|
||||
});
|
||||
|
||||
export const equipmentQuantitySchema = z.object({
|
||||
quantity: z.number().int().min(1).max(10000),
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
178
api/src/services/gyms/claims.ts
Normal file
178
api/src/services/gyms/claims.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Prisma, PrismaClient } from '@prisma/client';
|
||||
import { AppError, badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
|
||||
import { logger } from '../../lib/logger.js';
|
||||
import { claimUploadDir, removeClaimFiles, storedFileName } from '../../lib/uploads.js';
|
||||
import { toPrismaAvailability, type Availability } from '../me.js';
|
||||
|
||||
export interface GymClaimInput {
|
||||
/** Set = verification of that virtual gym; absent = claim for a NEW real gym. */
|
||||
gymId?: string;
|
||||
description: string;
|
||||
companyName?: string;
|
||||
nip?: string;
|
||||
phone?: string;
|
||||
email?: string;
|
||||
/** Verification claims only: overrides gym.location on approval. */
|
||||
address?: string;
|
||||
/** New-real claims only: */
|
||||
gymName?: string;
|
||||
gymLocation?: string;
|
||||
gymAvailability?: Availability | null;
|
||||
gymCapacity?: number;
|
||||
}
|
||||
|
||||
export interface UploadedClaimFile {
|
||||
originalName: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
/** Temp path (multer) — moved into the per-claim directory. */
|
||||
path: string;
|
||||
}
|
||||
|
||||
type ClaimWithRelations = Prisma.GymClaimGetPayload<{
|
||||
include: {
|
||||
gym: { select: { id: true; name: true; kind: true; isPrivate: true } };
|
||||
documents: {
|
||||
select: { id: true; originalName: true; mimeType: true; sizeBytes: true; createdAt: true };
|
||||
};
|
||||
};
|
||||
}>;
|
||||
|
||||
export function claimToDto(c: ClaimWithRelations) {
|
||||
return {
|
||||
id: c.id,
|
||||
gymId: c.gymId,
|
||||
type: c.gymId ? ('verification' as const) : ('new' as const),
|
||||
gym: c.gym
|
||||
? { id: c.gym.id, name: c.gym.name, kind: c.gym.kind, isPrivate: c.gym.isPrivate }
|
||||
: null,
|
||||
gymName: c.gymName,
|
||||
gymLocation: c.gymLocation,
|
||||
gymAvailability: c.gymAvailability,
|
||||
gymCapacity: c.gymCapacity,
|
||||
description: c.description,
|
||||
companyName: c.companyName,
|
||||
nip: c.nip,
|
||||
phone: c.phone,
|
||||
email: c.email,
|
||||
address: c.address,
|
||||
status: c.status,
|
||||
rejectReason: c.rejectReason,
|
||||
createdAt: c.createdAt.toISOString(),
|
||||
updatedAt: c.updatedAt.toISOString(),
|
||||
documents: c.documents.map((d) => ({
|
||||
id: d.id,
|
||||
originalName: d.originalName,
|
||||
mimeType: d.mimeType,
|
||||
sizeBytes: d.sizeBytes,
|
||||
createdAt: d.createdAt.toISOString(),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a gym claim (multipart). gymId set → verification of a virtual gym;
|
||||
* absent → claim for a new real gym (gymName/gymLocation required).
|
||||
* Files are moved from the temp dir into UPLOAD_DIR/<claimId>/.
|
||||
*/
|
||||
export async function createGymClaim(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
data: GymClaimInput,
|
||||
files: UploadedClaimFile[],
|
||||
) {
|
||||
if (data.gymId) {
|
||||
const gym = await prisma.gym.findUnique({ where: { id: data.gymId } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
if (gym.kind !== 'VIRTUAL') throw conflict('Only virtual gyms can be verified');
|
||||
const pending = await prisma.gymClaim.findFirst({
|
||||
where: { gymId: data.gymId, userId, status: 'PENDING' },
|
||||
select: { id: true },
|
||||
});
|
||||
if (pending) throw conflict('You already have a pending claim for this gym');
|
||||
} else {
|
||||
if (!data.gymName?.trim()) throw badRequest('Gym name is required');
|
||||
if (!data.gymLocation?.trim()) throw badRequest('Gym location is required');
|
||||
}
|
||||
|
||||
const claim = await prisma.gymClaim.create({
|
||||
data: {
|
||||
gymId: data.gymId ?? null,
|
||||
userId,
|
||||
gymName: data.gymId ? null : data.gymName?.trim() ?? null,
|
||||
gymLocation: data.gymId ? null : data.gymLocation?.trim() ?? null,
|
||||
gymAvailability: data.gymId ? undefined : toPrismaAvailability(data.gymAvailability ?? null),
|
||||
gymCapacity: data.gymId ? null : data.gymCapacity ?? null,
|
||||
description: data.description,
|
||||
companyName: data.companyName ?? null,
|
||||
nip: data.nip ?? null,
|
||||
phone: data.phone ?? null,
|
||||
email: data.email ?? null,
|
||||
address: data.address ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
if (files.length > 0) {
|
||||
const claimDir = claimUploadDir(claim.id);
|
||||
try {
|
||||
fs.mkdirSync(claimDir, { recursive: true });
|
||||
for (const f of files) {
|
||||
const storedName = storedFileName(f.mimeType);
|
||||
fs.renameSync(f.path, path.join(claimDir, storedName));
|
||||
await prisma.gymClaimDocument.create({
|
||||
data: {
|
||||
claimId: claim.id,
|
||||
originalName: f.originalName,
|
||||
storedName,
|
||||
mimeType: f.mimeType,
|
||||
sizeBytes: f.sizeBytes,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
// storage failure: roll the claim back and clean up moved/temp files
|
||||
await prisma.gymClaim.delete({ where: { id: claim.id } }).catch(() => undefined);
|
||||
removeClaimFiles(claim.id);
|
||||
logger.error({ err: e, claimId: claim.id }, 'Failed to store claim files');
|
||||
throw new AppError(500, 'UPLOAD_FAILED', 'Failed to store uploaded files');
|
||||
}
|
||||
}
|
||||
|
||||
const created = await prisma.gymClaim.findUnique({
|
||||
where: { id: claim.id },
|
||||
include: {
|
||||
gym: { select: { id: true, name: true, kind: true, isPrivate: true } },
|
||||
documents: {
|
||||
select: { id: true, originalName: true, mimeType: true, sizeBytes: true, createdAt: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
return { claim: claimToDto(created!) };
|
||||
}
|
||||
|
||||
/** The user's own claims (all statuses, newest first). */
|
||||
export async function listMyGymClaims(prisma: PrismaClient, userId: string) {
|
||||
const claims = await prisma.gymClaim.findMany({
|
||||
where: { userId },
|
||||
include: {
|
||||
gym: { select: { id: true, name: true, kind: true, isPrivate: true } },
|
||||
documents: {
|
||||
select: { id: true, originalName: true, mimeType: true, sizeBytes: true, createdAt: true },
|
||||
},
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
return { claims: claims.map(claimToDto) };
|
||||
}
|
||||
|
||||
/** Withdraw the user's own PENDING claim (files removed best-effort). */
|
||||
export async function withdrawGymClaim(prisma: PrismaClient, userId: string, claimId: string) {
|
||||
const claim = await prisma.gymClaim.findUnique({ where: { id: claimId } });
|
||||
if (!claim) throw notFound('Claim not found');
|
||||
if (claim.userId !== userId) throw forbidden('Only the claim author can withdraw it');
|
||||
if (claim.status !== 'PENDING') throw conflict('Only pending claims can be withdrawn');
|
||||
await prisma.gymClaim.delete({ where: { id: claimId } });
|
||||
removeClaimFiles(claimId);
|
||||
}
|
||||
266
api/src/services/gyms/core.ts
Normal file
266
api/src/services/gyms/core.ts
Normal file
@@ -0,0 +1,266 @@
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
|
||||
import { isPrismaNotFound } from '../../lib/prisma.js';
|
||||
import { removeGymClaimFiles, removeGymPhotoFiles } from '../../lib/uploads.js';
|
||||
import { toPrismaAvailability, type Availability } from '../me.js';
|
||||
import { gymCoverInclude, gymEquipmentInclude } from './includes.js';
|
||||
import { coverUrlOf } from './photos.js';
|
||||
|
||||
export type GymKind = 'VIRTUAL' | 'REAL';
|
||||
|
||||
export interface CreateGymInput {
|
||||
name: string;
|
||||
location?: string | null;
|
||||
availability?: Availability | null;
|
||||
capacity?: number | null;
|
||||
kind?: GymKind;
|
||||
isPrivate?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateGymInput {
|
||||
name?: string;
|
||||
location?: string | null;
|
||||
availability?: Availability | null;
|
||||
capacity?: number | null;
|
||||
isPrivate?: boolean;
|
||||
}
|
||||
|
||||
export async function listUserGyms(prisma: PrismaClient, userId: string) {
|
||||
const memberships = await prisma.gymMembership.findMany({
|
||||
where: { userId },
|
||||
include: { gym: { include: { ...gymEquipmentInclude, ...gymCoverInclude } } },
|
||||
orderBy: { gym: { name: 'asc' } },
|
||||
});
|
||||
return {
|
||||
gyms: memberships.map((m) => {
|
||||
const { photos, ...gym } = m.gym;
|
||||
return { ...gym, coverPhoto: coverUrlOf(gym.id, photos), roles: m.roles };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** All REAL gyms in the system (for selecting an existing gym). */
|
||||
export async function listAllGyms(prisma: PrismaClient) {
|
||||
const gyms = await prisma.gym.findMany({
|
||||
where: { kind: 'REAL' },
|
||||
include: { ...gymEquipmentInclude, ...gymCoverInclude },
|
||||
orderBy: { name: 'asc' },
|
||||
});
|
||||
return {
|
||||
gyms: gyms.map((g) => {
|
||||
const { photos, ...rest } = g;
|
||||
return { ...rest, coverPhoto: coverUrlOf(g.id, photos) };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Public virtual gyms (with rating counts, the caller's vote and claim status)
|
||||
* plus the caller's own private virtual gyms (no rating fields).
|
||||
* Public: score (up-down) desc, then name asc; own private last, by name.
|
||||
*/
|
||||
export async function listVirtualGyms(prisma: PrismaClient, userId: string) {
|
||||
const [publicGyms, privateGyms, claims, myRatings] = await Promise.all([
|
||||
prisma.gym.findMany({
|
||||
where: { kind: 'VIRTUAL', isPrivate: false },
|
||||
include: { ...gymEquipmentInclude, ratings: true, _count: { select: { memberships: true } } },
|
||||
}),
|
||||
prisma.gym.findMany({
|
||||
where: {
|
||||
kind: 'VIRTUAL',
|
||||
isPrivate: true,
|
||||
memberships: { some: { userId, roles: { has: 'OWNER' } } },
|
||||
},
|
||||
include: { ...gymEquipmentInclude, _count: { select: { memberships: true } } },
|
||||
}),
|
||||
prisma.gymClaim.findMany({
|
||||
where: { userId, status: { in: ['PENDING', 'REJECTED'] } },
|
||||
select: { gymId: true, status: true, rejectReason: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
}),
|
||||
prisma.gymRating.findMany({
|
||||
where: { userId },
|
||||
select: { gymId: true, vote: true },
|
||||
}),
|
||||
]);
|
||||
const myVoteByGym = new Map(myRatings.map((r) => [r.gymId, r.vote]));
|
||||
const claimByGym = new Map<string, { status: string; rejectReason: string | null }>();
|
||||
for (const c of claims) {
|
||||
if (c.gymId && !claimByGym.has(c.gymId)) claimByGym.set(c.gymId, c);
|
||||
}
|
||||
|
||||
const publicList = publicGyms.map((g) => {
|
||||
const up = g.ratings.filter((r) => r.vote === 'UP').length;
|
||||
const down = g.ratings.filter((r) => r.vote === 'DOWN').length;
|
||||
const claim = claimByGym.get(g.id);
|
||||
return {
|
||||
id: g.id,
|
||||
name: g.name,
|
||||
location: g.location,
|
||||
availability: g.availability,
|
||||
capacity: g.capacity,
|
||||
kind: g.kind,
|
||||
isPrivate: g.isPrivate,
|
||||
equipment: g.equipment,
|
||||
memberCount: g._count.memberships,
|
||||
up,
|
||||
down,
|
||||
myVote: myVoteByGym.get(g.id) ?? null,
|
||||
claimStatus: claim?.status ?? null,
|
||||
rejectReason: claim?.status === 'REJECTED' ? claim.rejectReason ?? null : null,
|
||||
};
|
||||
});
|
||||
publicList.sort(
|
||||
(a, b) => b.up - b.down - (a.up - a.down) || a.name.localeCompare(b.name, 'pl'),
|
||||
);
|
||||
|
||||
const privateList = privateGyms
|
||||
.map((g) => ({ ...g, isPrivate: true, memberCount: g._count.memberships }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name, 'pl'));
|
||||
|
||||
return { gyms: [...publicList, ...privateList] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Thumb vote on a public virtual gym (how well it mirrors the real one).
|
||||
* Upsert with toggle: the same vote again removes it. The owner cannot vote.
|
||||
*/
|
||||
export async function rateGym(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
gymId: string,
|
||||
vote: 'UP' | 'DOWN',
|
||||
) {
|
||||
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
if (gym.kind !== 'VIRTUAL' || gym.isPrivate)
|
||||
throw conflict('Only public virtual gyms can be rated');
|
||||
const isOwner = await prisma.gymMembership.findFirst({
|
||||
where: { gymId, userId, roles: { has: 'OWNER' } },
|
||||
});
|
||||
if (isOwner) throw forbidden('The gym owner cannot rate their own gym');
|
||||
const existing = await prisma.gymRating.findUnique({
|
||||
where: { gymId_userId: { gymId, userId } },
|
||||
});
|
||||
if (existing?.vote === vote) {
|
||||
await prisma.gymRating.delete({ where: { id: existing.id } });
|
||||
} else {
|
||||
await prisma.gymRating.upsert({
|
||||
where: { gymId_userId: { gymId, userId } },
|
||||
update: { vote },
|
||||
create: { gymId, userId, vote },
|
||||
});
|
||||
}
|
||||
const [up, down] = await Promise.all([
|
||||
prisma.gymRating.count({ where: { gymId, vote: 'UP' } }),
|
||||
prisma.gymRating.count({ where: { gymId, vote: 'DOWN' } }),
|
||||
]);
|
||||
return { vote: existing?.vote === vote ? null : vote, up, down };
|
||||
}
|
||||
|
||||
/** Join an existing gym (creates a MEMBER membership). */
|
||||
export async function joinGym(prisma: PrismaClient, userId: string, gymId: string) {
|
||||
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
const existing = await prisma.gymMembership.findUnique({
|
||||
where: { userId_gymId: { userId, gymId } },
|
||||
});
|
||||
if (existing) throw conflict('Already a member of this gym');
|
||||
const membership = await prisma.gymMembership.create({
|
||||
data: { userId, gymId, roles: ['MEMBER'] },
|
||||
});
|
||||
return { membership: { gymId, name: gym.name, roles: membership.roles } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a gym; the creator becomes its OWNER.
|
||||
* Non-admins can only create VIRTUAL gyms (location required); passing REAL → 403.
|
||||
* Admins pick the kind (default VIRTUAL); isPrivate is only allowed for VIRTUAL.
|
||||
*/
|
||||
export async function createGym(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
data: CreateGymInput,
|
||||
isAdmin: boolean,
|
||||
) {
|
||||
let kind: GymKind = data.kind ?? 'VIRTUAL';
|
||||
if (!isAdmin) {
|
||||
if (kind === 'REAL') throw forbidden('Only admins can create real gyms');
|
||||
kind = 'VIRTUAL';
|
||||
}
|
||||
if (kind === 'VIRTUAL' && !data.location?.trim())
|
||||
throw badRequest('Location is required for virtual gyms');
|
||||
const isPrivate = data.isPrivate ?? false;
|
||||
if (kind === 'REAL' && isPrivate) throw badRequest('Real gyms are always public');
|
||||
const gym = await prisma.gym.create({
|
||||
data: {
|
||||
name: data.name,
|
||||
location: data.location ?? null,
|
||||
availability: toPrismaAvailability(data.availability ?? null),
|
||||
capacity: data.capacity ?? null,
|
||||
kind,
|
||||
isPrivate,
|
||||
},
|
||||
});
|
||||
await prisma.gymMembership.create({
|
||||
data: { userId, gymId: gym.id, roles: ['OWNER'] },
|
||||
});
|
||||
return { gym: { ...gym, roles: ['OWNER'] } };
|
||||
}
|
||||
|
||||
export async function assertGymOwner(prisma: PrismaClient, gymId: string, userId: string) {
|
||||
const gym = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { memberships: { where: { userId } }, equipment: true },
|
||||
});
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
const isOwner = gym.memberships.some((m) => m.roles.includes('OWNER'));
|
||||
if (!isOwner) throw forbidden('Only the gym owner can manage this gym');
|
||||
return gym;
|
||||
}
|
||||
|
||||
/** Update a gym's data (owner only). isPrivate is only allowed for VIRTUAL gyms. */
|
||||
export async function updateOwnedGym(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
data: UpdateGymInput,
|
||||
) {
|
||||
const gym = await assertGymOwner(prisma, gymId, userId);
|
||||
if (data.isPrivate === true && gym.kind === 'REAL')
|
||||
throw badRequest('Real gyms are always public');
|
||||
try {
|
||||
const { availability, ...rest } = data;
|
||||
const updated = await prisma.gym.update({
|
||||
where: { id: gymId },
|
||||
data: { ...rest, availability: toPrismaAvailability(availability) },
|
||||
});
|
||||
return { gym: updated };
|
||||
} catch (e) {
|
||||
if (isPrismaNotFound(e)) throw notFound('Gym not found');
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Delete a gym (owner only). Memberships are removed; user plans are kept. */
|
||||
export async function deleteOwnedGym(prisma: PrismaClient, gymId: string, userId: string) {
|
||||
const gym = await assertGymOwner(prisma, gymId, userId);
|
||||
const claimIds = await listGymClaimIds(prisma, gymId);
|
||||
try {
|
||||
await prisma.gym.delete({ where: { id: gymId } });
|
||||
} catch (e) {
|
||||
if (isPrismaNotFound(e)) throw notFound('Gym not found');
|
||||
throw e;
|
||||
}
|
||||
await removeGymClaimFiles(claimIds);
|
||||
removeGymPhotoFiles(gymId);
|
||||
return { name: gym.name };
|
||||
}
|
||||
|
||||
export async function listGymClaimIds(prisma: PrismaClient, gymId: string): Promise<string[]> {
|
||||
const claims = await prisma.gymClaim.findMany({
|
||||
where: { gymId },
|
||||
select: { id: true },
|
||||
});
|
||||
return claims.map((c) => c.id);
|
||||
}
|
||||
175
api/src/services/gyms/exceptions.ts
Normal file
175
api/src/services/gyms/exceptions.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { badRequest, conflict, notFound } from '../../lib/errors.js';
|
||||
import { isPrismaUnique } from '../../lib/prisma.js';
|
||||
import { toPrismaJson, type DayAvailability } from '../me.js';
|
||||
import { assertGymOwner } from './core.js';
|
||||
import { gymEquipmentInclude } from './includes.js';
|
||||
|
||||
export interface CreateGymExceptionInput {
|
||||
/** ISO date (YYYY-MM-DD) the exception applies to. */
|
||||
date: string;
|
||||
/** null = closed, { start, end } = different hours. */
|
||||
availability: DayAvailability | null;
|
||||
}
|
||||
|
||||
/** List a gym's upcoming schedule exceptions (owner only). */
|
||||
export async function listOwnedGymExceptions(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
) {
|
||||
await assertGymOwner(prisma, gymId, userId);
|
||||
const exceptions = await prisma.gymException.findMany({
|
||||
where: { gymId },
|
||||
orderBy: { date: 'asc' },
|
||||
});
|
||||
return { exceptions };
|
||||
}
|
||||
|
||||
/** Add a one-off schedule exception for a specific date (owner only). */
|
||||
export async function createOwnedGymException(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
data: CreateGymExceptionInput,
|
||||
) {
|
||||
await assertGymOwner(prisma, gymId, userId);
|
||||
const date = new Date(data.date);
|
||||
if (Number.isNaN(date.getTime())) throw badRequest('Invalid date');
|
||||
try {
|
||||
const exception = await prisma.gymException.create({
|
||||
data: {
|
||||
gymId,
|
||||
date,
|
||||
availability: toPrismaJson(data.availability),
|
||||
},
|
||||
});
|
||||
return { exception };
|
||||
} catch (e) {
|
||||
if (isPrismaUnique(e)) throw conflict('An exception already exists for this date');
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove a schedule exception (owner only). */
|
||||
export async function deleteOwnedGymException(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
exceptionId: string,
|
||||
) {
|
||||
await assertGymOwner(prisma, gymId, userId);
|
||||
const exception = await prisma.gymException.findUnique({ where: { id: exceptionId } });
|
||||
if (!exception || exception.gymId !== gymId) throw notFound('Exception not found');
|
||||
await prisma.gymException.delete({ where: { id: exceptionId } });
|
||||
}
|
||||
|
||||
/** Add a catalog equipment item to a gym with a quantity (owner only). */
|
||||
export async function addEquipment(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
equipmentId: string,
|
||||
quantity = 1,
|
||||
) {
|
||||
const gym = await assertGymOwner(prisma, gymId, userId);
|
||||
const item = await prisma.equipment.findUnique({ where: { id: equipmentId } });
|
||||
if (!item) throw notFound('Equipment not found');
|
||||
if (gym.equipment.some((e) => e.equipmentId === equipmentId))
|
||||
throw conflict('Equipment already exists in this gym — update its quantity instead');
|
||||
try {
|
||||
await prisma.gymEquipment.create({ data: { gymId, equipmentId, quantity } });
|
||||
} catch (e) {
|
||||
if (isPrismaUnique(e)) throw conflict('Equipment already exists in this gym — update its quantity instead');
|
||||
throw e;
|
||||
}
|
||||
const updated = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: gymEquipmentInclude,
|
||||
});
|
||||
return { gym: updated };
|
||||
}
|
||||
|
||||
/** Change the quantity of a gym's equipment item (owner only). */
|
||||
export async function updateEquipmentQuantity(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
equipmentId: string,
|
||||
quantity: number,
|
||||
) {
|
||||
const gym = await assertGymOwner(prisma, gymId, userId);
|
||||
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
|
||||
if (!link) throw badRequest('Equipment not found in this gym');
|
||||
await prisma.gymEquipment.update({ where: { id: link.id }, data: { quantity } });
|
||||
const updated = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: gymEquipmentInclude,
|
||||
});
|
||||
return { gym: updated };
|
||||
}
|
||||
|
||||
/** Remove a catalog equipment item from a gym (owner only). */
|
||||
export async function removeEquipment(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
equipmentId: string,
|
||||
) {
|
||||
const gym = await assertGymOwner(prisma, gymId, userId);
|
||||
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
|
||||
if (!link) throw badRequest('Equipment not found in this gym');
|
||||
await prisma.gymEquipment.delete({ where: { id: link.id } });
|
||||
const updated = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: gymEquipmentInclude,
|
||||
});
|
||||
return { gym: updated };
|
||||
}
|
||||
|
||||
/** List a gym's upcoming schedule exceptions. */
|
||||
export async function listGymExceptions(prisma: PrismaClient, gymId: string) {
|
||||
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
const exceptions = await prisma.gymException.findMany({
|
||||
where: { gymId },
|
||||
orderBy: { date: 'asc' },
|
||||
});
|
||||
return { exceptions };
|
||||
}
|
||||
|
||||
/** Add a one-off schedule exception for a specific date. */
|
||||
export async function createGymException(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
data: CreateGymExceptionInput,
|
||||
) {
|
||||
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
const date = new Date(data.date);
|
||||
if (Number.isNaN(date.getTime())) throw badRequest('Invalid date');
|
||||
try {
|
||||
const exception = await prisma.gymException.create({
|
||||
data: {
|
||||
gymId,
|
||||
date,
|
||||
availability: toPrismaJson(data.availability),
|
||||
},
|
||||
});
|
||||
return { exception };
|
||||
} catch (e) {
|
||||
if (isPrismaUnique(e)) throw conflict('An exception already exists for this date');
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove a schedule exception. */
|
||||
export async function deleteGymException(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
exceptionId: string,
|
||||
) {
|
||||
const exception = await prisma.gymException.findUnique({ where: { id: exceptionId } });
|
||||
if (!exception || exception.gymId !== gymId) throw notFound('Exception not found');
|
||||
await prisma.gymException.delete({ where: { id: exceptionId } });
|
||||
}
|
||||
20
api/src/services/gyms/includes.ts
Normal file
20
api/src/services/gyms/includes.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/** Gym equipment links with the catalog item, ordered by equipment name. */
|
||||
export const gymEquipmentInclude = {
|
||||
equipment: {
|
||||
include: { equipment: true },
|
||||
orderBy: { equipment: { name: 'asc' as const } },
|
||||
},
|
||||
};
|
||||
|
||||
/** Gallery photos, cover first (smallest order, tie → oldest). */
|
||||
export const gymPhotosInclude = {
|
||||
photos: { orderBy: [{ order: 'asc' as const }, { createdAt: 'asc' as const }] },
|
||||
};
|
||||
|
||||
/** Only the cover photo (for lists). */
|
||||
export const gymCoverInclude = {
|
||||
photos: {
|
||||
orderBy: [{ order: 'asc' as const }, { createdAt: 'asc' as const }],
|
||||
take: 1,
|
||||
},
|
||||
};
|
||||
199
api/src/services/gyms/invitations.ts
Normal file
199
api/src/services/gyms/invitations.ts
Normal file
@@ -0,0 +1,199 @@
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { AppError, badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
|
||||
import { INVITATION_TTL_DAYS } from '../trainer.js';
|
||||
|
||||
async function assertGymOwnerOf(prisma: PrismaClient, gymId: string, userId: string): Promise<void> {
|
||||
const membership = await prisma.gymMembership.findFirst({
|
||||
where: { gymId, userId, roles: { has: 'OWNER' } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!membership) throw forbidden('Only the gym owner can do this');
|
||||
}
|
||||
|
||||
/**
|
||||
* Invite a user to a PRIVATE virtual gym. Owner only. A re-invite after DECLINED
|
||||
* updates the existing row (new invitedAt/expiresAt/invitedBy).
|
||||
*/
|
||||
export async function sendGymInvitation(
|
||||
prisma: PrismaClient,
|
||||
ownerId: string,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
) {
|
||||
if (ownerId === userId) throw badRequest('Cannot invite yourself');
|
||||
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
if (gym.kind !== 'VIRTUAL' || !gym.isPrivate)
|
||||
throw conflict('Only private virtual gyms can receive invitations');
|
||||
await assertGymOwnerOf(prisma, gymId, ownerId);
|
||||
const target = await prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!target) throw notFound('User not found');
|
||||
const member = await prisma.gymMembership.findUnique({
|
||||
where: { userId_gymId: { userId, gymId } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (member) throw conflict('User is already a member of this gym');
|
||||
const existing = await prisma.gymInvitation.findFirst({ where: { gymId, userId } });
|
||||
if (existing?.status === 'PENDING') throw conflict('Invitation already exists');
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(now.getTime() + INVITATION_TTL_DAYS * 24 * 60 * 60 * 1000);
|
||||
const invitation = existing
|
||||
? await prisma.gymInvitation.update({
|
||||
where: { id: existing.id },
|
||||
data: { status: 'PENDING', invitedAt: now, expiresAt, invitedById: ownerId },
|
||||
})
|
||||
: await prisma.gymInvitation.create({
|
||||
data: { gymId, userId, invitedById: ownerId, expiresAt },
|
||||
});
|
||||
return { invitation };
|
||||
}
|
||||
|
||||
/** Pending, not-expired gym invitations of the user — sent and received. */
|
||||
export async function listGymInvitations(prisma: PrismaClient, userId: string) {
|
||||
const now = new Date();
|
||||
const invitations = await prisma.gymInvitation.findMany({
|
||||
where: {
|
||||
status: 'PENDING',
|
||||
expiresAt: { gt: now },
|
||||
OR: [{ userId }, { invitedById: userId }],
|
||||
},
|
||||
include: {
|
||||
gym: { select: { id: true, name: true, location: true, kind: true, isPrivate: true } },
|
||||
user: { select: { id: true, firstName: true, lastName: true, email: true } },
|
||||
invitedBy: { select: { id: true, firstName: true, lastName: true, email: true } },
|
||||
},
|
||||
orderBy: { invitedAt: 'desc' },
|
||||
});
|
||||
return {
|
||||
invitations: invitations.map((i) => {
|
||||
const direction = i.invitedById === userId ? ('sent' as const) : ('received' as const);
|
||||
return {
|
||||
id: i.id,
|
||||
direction,
|
||||
gym: {
|
||||
id: i.gym.id,
|
||||
name: i.gym.name,
|
||||
location: i.gym.location,
|
||||
kind: i.gym.kind,
|
||||
isPrivate: i.gym.isPrivate,
|
||||
},
|
||||
user:
|
||||
direction === 'sent'
|
||||
? {
|
||||
id: i.user.id,
|
||||
firstName: i.user.firstName,
|
||||
lastName: i.user.lastName,
|
||||
email: i.user.email,
|
||||
}
|
||||
: null,
|
||||
invitedBy:
|
||||
direction === 'received'
|
||||
? {
|
||||
id: i.invitedBy.id,
|
||||
firstName: i.invitedBy.firstName,
|
||||
lastName: i.invitedBy.lastName,
|
||||
email: i.invitedBy.email,
|
||||
}
|
||||
: null,
|
||||
invitedAt: i.invitedAt.toISOString(),
|
||||
expiresAt: i.expiresAt.toISOString(),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Search users to invite to a private virtual gym (owner only).
|
||||
* Excludes the owner, current members and users with a pending invitation.
|
||||
*/
|
||||
export async function searchGymInvitees(
|
||||
prisma: PrismaClient,
|
||||
ownerId: string,
|
||||
gymId: string,
|
||||
firstName: string,
|
||||
lastName: string,
|
||||
) {
|
||||
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
await assertGymOwnerOf(prisma, gymId, ownerId);
|
||||
const [members, pending] = await Promise.all([
|
||||
prisma.gymMembership.findMany({ where: { gymId }, select: { userId: true } }),
|
||||
prisma.gymInvitation.findMany({ where: { gymId, status: 'PENDING' }, select: { userId: true } }),
|
||||
]);
|
||||
const excludeIds = new Set([
|
||||
ownerId,
|
||||
...members.map((m) => m.userId),
|
||||
...pending.map((p) => p.userId),
|
||||
]);
|
||||
const users = await prisma.user.findMany({
|
||||
where: {
|
||||
firstName: { contains: firstName, mode: 'insensitive' },
|
||||
lastName: { contains: lastName, mode: 'insensitive' },
|
||||
NOT: { id: { in: [...excludeIds] } },
|
||||
},
|
||||
select: { id: true, firstName: true, lastName: true, email: true, phone: true },
|
||||
take: 20,
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
return { users };
|
||||
}
|
||||
|
||||
async function loadPendingGymInvitation(prisma: PrismaClient, invitationId: string) {
|
||||
const invitation = await prisma.gymInvitation.findUnique({ where: { id: invitationId } });
|
||||
if (!invitation) throw notFound('Invitation not found');
|
||||
if (invitation.status !== 'PENDING') throw conflict('Invitation is not pending');
|
||||
if (invitation.expiresAt <= new Date()) throw new AppError(410, 'GONE', 'Invitation expired');
|
||||
return invitation;
|
||||
}
|
||||
|
||||
/** Accept a gym invitation (invited user only) → MEMBER membership (idempotent). */
|
||||
export async function acceptGymInvitation(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
invitationId: string,
|
||||
) {
|
||||
const invitation = await loadPendingGymInvitation(prisma, invitationId);
|
||||
if (invitation.userId !== userId) throw forbidden('You are not the invited user');
|
||||
const existing = await prisma.gymMembership.findUnique({
|
||||
where: { userId_gymId: { userId, gymId: invitation.gymId } },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!existing) {
|
||||
await prisma.gymMembership.create({
|
||||
data: { userId, gymId: invitation.gymId, roles: ['MEMBER'] },
|
||||
});
|
||||
}
|
||||
const updated = await prisma.gymInvitation.update({
|
||||
where: { id: invitationId },
|
||||
data: { status: 'ACCEPTED' },
|
||||
});
|
||||
return { invitation: updated };
|
||||
}
|
||||
|
||||
/** Decline a gym invitation (invited user only). */
|
||||
export async function declineGymInvitation(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
invitationId: string,
|
||||
) {
|
||||
const invitation = await loadPendingGymInvitation(prisma, invitationId);
|
||||
if (invitation.userId !== userId) throw forbidden('You are not the invited user');
|
||||
const updated = await prisma.gymInvitation.update({
|
||||
where: { id: invitationId },
|
||||
data: { status: 'DECLINED' },
|
||||
});
|
||||
return { invitation: updated };
|
||||
}
|
||||
|
||||
/** Withdraw a pending gym invitation (sender only) — removes the row. */
|
||||
export async function withdrawGymInvitation(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
invitationId: string,
|
||||
) {
|
||||
const invitation = await prisma.gymInvitation.findUnique({ where: { id: invitationId } });
|
||||
if (!invitation) throw notFound('Invitation not found');
|
||||
if (invitation.status !== 'PENDING') throw conflict('Invitation is not pending');
|
||||
if (invitation.invitedById !== userId) throw forbidden('Only the sender can withdraw the invitation');
|
||||
await prisma.gymInvitation.delete({ where: { id: invitationId } });
|
||||
}
|
||||
200
api/src/services/gyms/photos.ts
Normal file
200
api/src/services/gyms/photos.ts
Normal file
@@ -0,0 +1,200 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { Prisma, PrismaClient } from '@prisma/client';
|
||||
import { AppError, badRequest, conflict, forbidden, notFound } from '../../lib/errors.js';
|
||||
import { logger } from '../../lib/logger.js';
|
||||
import {
|
||||
MAX_GYM_PHOTOS,
|
||||
photoUploadDir,
|
||||
removeGymPhotoFile,
|
||||
storedFileName,
|
||||
} from '../../lib/uploads.js';
|
||||
import { gymEquipmentInclude, gymPhotosInclude } from './includes.js';
|
||||
|
||||
export interface GymPhotoDto {
|
||||
id: string;
|
||||
url: string;
|
||||
order: number;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
/** Public photo URL (served by GET /gyms/:gymId/photos/:photoId). */
|
||||
export function gymPhotoUrl(gymId: string, photoId: string): string {
|
||||
return `/gyms/${gymId}/photos/${photoId}`;
|
||||
}
|
||||
|
||||
export function coverUrlOf(gymId: string, photos: { id: string }[]): string | null {
|
||||
return photos[0] ? gymPhotoUrl(gymId, photos[0].id) : null;
|
||||
}
|
||||
|
||||
type GymWithPhotos = Prisma.GymGetPayload<{
|
||||
include: {
|
||||
equipment: { include: { equipment: true } };
|
||||
photos: true;
|
||||
};
|
||||
}>;
|
||||
|
||||
function gymToDto(g: GymWithPhotos) {
|
||||
const photos: GymPhotoDto[] = g.photos.map((p) => ({
|
||||
id: p.id,
|
||||
url: gymPhotoUrl(g.id, p.id),
|
||||
order: p.order,
|
||||
createdAt: p.createdAt.toISOString(),
|
||||
}));
|
||||
return {
|
||||
id: g.id,
|
||||
name: g.name,
|
||||
location: g.location,
|
||||
availability: g.availability,
|
||||
capacity: g.capacity,
|
||||
kind: g.kind,
|
||||
isPrivate: g.isPrivate,
|
||||
equipment: g.equipment,
|
||||
photos,
|
||||
coverPhoto: coverUrlOf(g.id, g.photos),
|
||||
};
|
||||
}
|
||||
|
||||
async function loadGymDto(prisma: PrismaClient, gymId: string) {
|
||||
const gym = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { ...gymEquipmentInclude, ...gymPhotosInclude },
|
||||
});
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
return gymToDto(gym);
|
||||
}
|
||||
|
||||
/** True when the user may manage the gym: an admin or a member with the OWNER role. */
|
||||
export async function canManageGym(
|
||||
prisma: PrismaClient,
|
||||
gymId: string,
|
||||
userId: string,
|
||||
isAdmin: boolean,
|
||||
): Promise<boolean> {
|
||||
if (isAdmin) return true;
|
||||
const membership = await prisma.gymMembership.findUnique({
|
||||
where: { userId_gymId: { userId, gymId } },
|
||||
select: { roles: true },
|
||||
});
|
||||
return !!membership?.roles.includes('OWNER');
|
||||
}
|
||||
|
||||
/**
|
||||
* Public gym detail. REAL gyms are visible to any logged-in user; VIRTUAL gyms
|
||||
* only to their managers (owner or admin). Includes the photo gallery.
|
||||
*/
|
||||
export async function getGymPublic(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
isAdmin: boolean,
|
||||
gymId: string,
|
||||
) {
|
||||
const gym = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { ...gymEquipmentInclude, ...gymPhotosInclude },
|
||||
});
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
if (gym.kind !== 'REAL' && !(await canManageGym(prisma, gymId, userId, isAdmin)))
|
||||
throw forbidden('You do not have access to this gym');
|
||||
const membership = await prisma.gymMembership.findUnique({
|
||||
where: { userId_gymId: { userId, gymId } },
|
||||
});
|
||||
return { gym: gymToDto(gym), roles: membership?.roles ?? [], isAdmin };
|
||||
}
|
||||
|
||||
export interface UploadedPhotoFile {
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
/** Temp path (multer) — moved into the per-gym directory. */
|
||||
path: string;
|
||||
}
|
||||
|
||||
/** Add photos to a REAL gym's gallery (owner or admin). */
|
||||
export async function addGymPhotos(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
isAdmin: boolean,
|
||||
gymId: string,
|
||||
files: UploadedPhotoFile[],
|
||||
) {
|
||||
const gym = await prisma.gym.findUnique({
|
||||
where: { id: gymId },
|
||||
include: { photos: { select: { order: true } } },
|
||||
});
|
||||
if (!gym) throw notFound('Gym not found');
|
||||
if (gym.kind !== 'REAL') throw conflict('Only real gyms have a gallery');
|
||||
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
|
||||
throw forbidden('Only the gym owner or an admin can manage photos');
|
||||
if (gym.photos.length + files.length > MAX_GYM_PHOTOS)
|
||||
throw badRequest(`A gym can have at most ${MAX_GYM_PHOTOS} photos`);
|
||||
const maxOrder = gym.photos.reduce((m, p) => Math.max(m, p.order), -1);
|
||||
const dir = photoUploadDir(gymId);
|
||||
const moved: string[] = [];
|
||||
try {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const f = files[i];
|
||||
const storedName = storedFileName(f.mimeType);
|
||||
fs.renameSync(f.path, path.join(dir, storedName));
|
||||
moved.push(path.join(dir, storedName));
|
||||
await prisma.gymPhoto.create({
|
||||
data: {
|
||||
gymId,
|
||||
storedName,
|
||||
mimeType: f.mimeType,
|
||||
sizeBytes: f.sizeBytes,
|
||||
order: maxOrder + 1 + i,
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
for (const p of moved) fs.rmSync(p, { force: true });
|
||||
logger.error({ err: e, gymId }, 'Failed to store gym photos');
|
||||
throw new AppError(500, 'UPLOAD_FAILED', 'Failed to store uploaded photos');
|
||||
}
|
||||
return { gym: await loadGymDto(prisma, gymId) };
|
||||
}
|
||||
|
||||
/** Remove a photo from a gym's gallery (owner or admin). */
|
||||
export async function deleteGymPhoto(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
isAdmin: boolean,
|
||||
gymId: string,
|
||||
photoId: string,
|
||||
) {
|
||||
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
|
||||
throw forbidden('Only the gym owner or an admin can manage photos');
|
||||
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
|
||||
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
|
||||
await prisma.gymPhoto.delete({ where: { id: photoId } });
|
||||
removeGymPhotoFile(gymId, photo.storedName);
|
||||
return { gym: await loadGymDto(prisma, gymId) };
|
||||
}
|
||||
|
||||
/** Make a photo the gallery cover (order 0; the rest shift by +1). Owner or admin. */
|
||||
export async function setGymPhotoCover(
|
||||
prisma: PrismaClient,
|
||||
userId: string,
|
||||
isAdmin: boolean,
|
||||
gymId: string,
|
||||
photoId: string,
|
||||
) {
|
||||
if (!(await canManageGym(prisma, gymId, userId, isAdmin)))
|
||||
throw forbidden('Only the gym owner or an admin can manage photos');
|
||||
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
|
||||
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
|
||||
if (photo.order !== 0) {
|
||||
await prisma.$transaction(async (tx) => {
|
||||
await tx.gymPhoto.update({ where: { id: photoId }, data: { order: 0 } });
|
||||
const others = await tx.gymPhoto.findMany({
|
||||
where: { gymId, id: { not: photoId } },
|
||||
select: { id: true, order: true },
|
||||
});
|
||||
for (const p of others) {
|
||||
await tx.gymPhoto.update({ where: { id: p.id }, data: { order: p.order + 1 } });
|
||||
}
|
||||
});
|
||||
}
|
||||
return { gym: await loadGymDto(prisma, gymId) };
|
||||
}
|
||||
@@ -363,7 +363,7 @@ export async function assertActiveTrainee(prisma: PrismaClient, trainerId: strin
|
||||
* Restricted trainee detail: training metrics only (no body parameters, no profile).
|
||||
*/
|
||||
export async function getTraineeDetail(prisma: PrismaClient, trainerId: string, userId: string) {
|
||||
await assertActiveTrainee(prisma, trainerId, userId);
|
||||
const coaching = await assertActiveTrainee(prisma, trainerId, userId);
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
@@ -381,6 +381,7 @@ export async function getTraineeDetail(prisma: PrismaClient, trainerId: string,
|
||||
computeTraineeMetrics(prisma, userId),
|
||||
]);
|
||||
return {
|
||||
coachingId: coaching.id,
|
||||
user: {
|
||||
id: user.id,
|
||||
firstName: user.firstName,
|
||||
|
||||
Reference in New Issue
Block a user