1160 lines
33 KiB
TypeScript
1160 lines
33 KiB
TypeScript
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, requireAdmin } from '../middleware/auth.js';
|
|
import { validate } from '../middleware/validate.js';
|
|
import {
|
|
availabilitySchema,
|
|
circumferenceSchema,
|
|
historyQuerySchema,
|
|
socialMediaEntrySchema,
|
|
weightSchema,
|
|
} from './me.js';
|
|
import {
|
|
addCircumference,
|
|
addWeight,
|
|
deleteCircumference,
|
|
deleteWeight,
|
|
getBodyParameters,
|
|
getHistory,
|
|
} from '../services/me.js';
|
|
import { getExerciseProgress } from '../services/exerciseProgress.js';
|
|
import { getKillstreak } from '../services/killstreak.js';
|
|
import {
|
|
addGymEquipment,
|
|
addGymOwner,
|
|
addMembership,
|
|
approveGymClaim,
|
|
createGym,
|
|
createUser,
|
|
deleteGym,
|
|
deleteUser,
|
|
ensureUser,
|
|
getGym,
|
|
getGymClaim,
|
|
listGymClaims,
|
|
listGyms,
|
|
listUsers,
|
|
rejectGymClaim,
|
|
removeGymEquipment,
|
|
removeGymOwner,
|
|
removeMembership,
|
|
updateGym,
|
|
updateGymEquipment,
|
|
updateMembership,
|
|
updateUser,
|
|
} from '../services/admin.js';
|
|
import { config } from '../config.js';
|
|
import { notFound } from '../lib/errors.js';
|
|
import {
|
|
createFocusArea,
|
|
deleteFocusArea,
|
|
listFocusAreasWithUsage,
|
|
updateFocusArea,
|
|
} from '../services/focusAreas.js';
|
|
import { getFocusChain } from '../services/focusChain.js';
|
|
import { createGymException, deleteGymException, listGymExceptions } from '../services/gyms.js';
|
|
import {
|
|
createAnnouncementAsAdmin,
|
|
deleteAnnouncementAsAdmin,
|
|
listAnnouncementsForAdmin,
|
|
updateAnnouncementAsAdmin,
|
|
} from '../services/announcements.js';
|
|
import { listActivityLogs, logActivity } from '../services/audit.js';
|
|
import { asyncHandler } from '../lib/asyncHandler.js';
|
|
|
|
const gymSchema = z.object({
|
|
name: z.string().min(1).max(200),
|
|
availability: availabilitySchema,
|
|
capacity: z.number().int().positive().max(100000).nullable().optional(),
|
|
});
|
|
|
|
// Adres strukturalny (wzorzec Google/UPU) — display string `location` liczony po stronie serwera.
|
|
const postalCodeSchema = z
|
|
.string()
|
|
.trim()
|
|
.regex(/^\d{2}-\d{3}$/, 'Format kodu pocztowego: 00-001');
|
|
const countryCodeSchema = z
|
|
.string()
|
|
.trim()
|
|
.regex(/^[a-zA-Z]{2}$/, 'Kod kraju ISO 3166-1 alpha-2');
|
|
|
|
// Admin tworząc siłownię REAL zawsze wyznacza właściciela i podaje adres (ulica, kod, miasto).
|
|
const createGymSchema = gymSchema.extend({
|
|
ownerId: z.string().min(1),
|
|
addressLine1: z.string().trim().min(1).max(200),
|
|
addressLine2: z.string().trim().max(200).nullable().optional(),
|
|
postalCode: postalCodeSchema,
|
|
city: z.string().trim().min(1).max(100),
|
|
countryCode: countryCodeSchema.default('PL'),
|
|
});
|
|
const updateGymSchema = z.object({
|
|
name: gymSchema.shape.name.optional(),
|
|
availability: gymSchema.shape.availability,
|
|
capacity: gymSchema.shape.capacity,
|
|
addressLine1: z.string().trim().min(1).max(200).nullable().optional(),
|
|
addressLine2: z.string().trim().max(200).nullable().optional(),
|
|
postalCode: postalCodeSchema.nullable().optional(),
|
|
city: z.string().trim().min(1).max(100).nullable().optional(),
|
|
countryCode: countryCodeSchema.nullable().optional(),
|
|
});
|
|
|
|
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 createUserSchema = z.object({
|
|
email: z.string().email(),
|
|
password: z.string().min(8),
|
|
firstName: z.string().min(1).max(100).optional(),
|
|
lastName: z.string().min(1).max(100).optional(),
|
|
age: z.number().int().min(10).max(100).optional(),
|
|
isAdmin: z.boolean().optional(),
|
|
});
|
|
|
|
const muscleArraySchema = z.array(z.string().min(1).max(50)).max(20);
|
|
|
|
const USER_STATUSES = ['ACTIVE', 'SUSPENDED', 'BANNED'] as const;
|
|
|
|
const updateUserSchema = z
|
|
.object({
|
|
email: z.string().email().max(200).optional(),
|
|
firstName: z.string().min(1).max(100).nullable().optional(),
|
|
lastName: z.string().min(1).max(100).nullable().optional(),
|
|
nickname: z.string().min(1).max(50).nullable().optional(),
|
|
socialMedia: z.array(socialMediaEntrySchema).max(20).nullable().optional(),
|
|
age: z.number().int().min(10).max(100).nullable().optional(),
|
|
heightCm: z.number().positive().max(250).nullable().optional(),
|
|
phone: z.string().min(5).max(20).nullable().optional(),
|
|
isAdmin: z.boolean().optional(),
|
|
password: z.string().min(8).optional(),
|
|
availability: availabilitySchema,
|
|
priorities: z.string().max(2000).nullable().optional(),
|
|
exclusions: z.string().max(2000).nullable().optional(),
|
|
developMuscles: muscleArraySchema.optional(),
|
|
canDoMuscles: muscleArraySchema.optional(),
|
|
difficultMuscles: muscleArraySchema.optional(),
|
|
avoidMuscles: muscleArraySchema.optional(),
|
|
status: z.enum(USER_STATUSES).optional(),
|
|
suspensionUntil: z.string().datetime().nullable().optional(),
|
|
restrictionReason: z.string().min(1).max(500).nullable().optional(),
|
|
})
|
|
.superRefine((data, ctx) => {
|
|
// kara musi być zużywalna: zawieszenie z przyszłym terminem, ban z powodem
|
|
if (data.status === 'SUSPENDED') {
|
|
if (!data.suspensionUntil) {
|
|
ctx.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
path: ['suspensionUntil'],
|
|
message: 'suspensionUntil is required when status is SUSPENDED',
|
|
});
|
|
} else if (new Date(data.suspensionUntil) <= new Date()) {
|
|
ctx.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
path: ['suspensionUntil'],
|
|
message: 'suspensionUntil must be in the future',
|
|
});
|
|
}
|
|
}
|
|
if (data.status === 'BANNED' && !(data.restrictionReason ?? '').trim()) {
|
|
ctx.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
path: ['restrictionReason'],
|
|
message: 'restrictionReason is required when status is BANNED',
|
|
});
|
|
}
|
|
});
|
|
|
|
const GYM_ROLES = ['OWNER', 'TRAINER', 'MEMBER'] as const;
|
|
|
|
const membershipSchema = z.object({
|
|
gymId: z.string().min(1),
|
|
roles: z.array(z.enum(GYM_ROLES)).min(1),
|
|
});
|
|
|
|
const updateMembershipSchema = z.object({
|
|
roles: z.array(z.enum(GYM_ROLES)).min(1),
|
|
});
|
|
|
|
export function createAdminRoutes({ prisma }: AppDeps) {
|
|
const router = Router();
|
|
router.use(authenticate(prisma), requireAdmin);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms:
|
|
* get:
|
|
* summary: List gyms (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
*/
|
|
router.get(
|
|
'/gyms',
|
|
asyncHandler(async (_req, res) => {
|
|
const result = await listGyms(prisma);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms:
|
|
* post:
|
|
* summary: Create gym (admin; ownerId becomes OWNER)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 201: { description: Created }
|
|
*/
|
|
router.post(
|
|
'/gyms',
|
|
validate(createGymSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof createGymSchema>;
|
|
const result = await createGym(prisma, data);
|
|
res.status(201).json(result);
|
|
}),
|
|
);
|
|
|
|
const gymOwnerSchema = z.object({ userId: z.string().min(1) });
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}/owners:
|
|
* post:
|
|
* summary: Grant the OWNER role to a user in a gym (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 404: { description: Gym or user not found }
|
|
*/
|
|
router.post(
|
|
'/gyms/:id/owners',
|
|
validate(gymOwnerSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const { userId } = req.body as z.infer<typeof gymOwnerSchema>;
|
|
const result = await addGymOwner(prisma, req.params.id, userId);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}/owners/{userId}:
|
|
* delete:
|
|
* summary: Revoke the OWNER role in a gym (admin; membership removed when no roles left)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 204: { description: Revoked }
|
|
* 404: { description: Owner not found }
|
|
*/
|
|
router.delete(
|
|
'/gyms/:id/owners/:userId',
|
|
asyncHandler(async (req, res) => {
|
|
await removeGymOwner(prisma, req.params.id, req.params.userId);
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}:
|
|
* patch:
|
|
* summary: Update gym (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
*/
|
|
router.patch(
|
|
'/gyms/:id',
|
|
validate(updateGymSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof updateGymSchema>;
|
|
const result = await updateGym(prisma, req.params.id, data);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}:
|
|
* delete:
|
|
* summary: Delete gym (admin). Memberships are removed; user plans are kept.
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 204: { description: Deleted }
|
|
*/
|
|
router.delete(
|
|
'/gyms/:id',
|
|
asyncHandler(async (req, res) => {
|
|
await deleteGym(prisma, req.params.id);
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}/exceptions:
|
|
* get:
|
|
* summary: List a gym's schedule exceptions (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
*/
|
|
router.get(
|
|
'/gyms/:id/exceptions',
|
|
asyncHandler(async (req, res) => {
|
|
const result = await listGymExceptions(prisma, req.params.id);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}/exceptions:
|
|
* post:
|
|
* summary: Add a one-off schedule exception (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 201: { description: Created }
|
|
* 409: { description: Exception already exists for this date }
|
|
*/
|
|
router.post(
|
|
'/gyms/:id/exceptions',
|
|
validate(gymExceptionSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof gymExceptionSchema>;
|
|
const result = await createGymException(prisma, req.params.id, {
|
|
date: data.date,
|
|
availability: data.availability ?? null,
|
|
});
|
|
res.status(201).json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}/exceptions/{exceptionId}:
|
|
* delete:
|
|
* summary: Remove a schedule exception (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 204: { description: Removed }
|
|
*/
|
|
router.delete(
|
|
'/gyms/:id/exceptions/:exceptionId',
|
|
asyncHandler(async (req, res) => {
|
|
await deleteGymException(prisma, req.params.id, req.params.exceptionId);
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
const gymEquipmentSchema = z.object({
|
|
equipmentId: z.string().min(1),
|
|
quantity: z.number().int().min(1).max(10000).optional(),
|
|
spec: z.unknown().optional(),
|
|
});
|
|
|
|
const gymEquipmentInstanceSchema = z.object({
|
|
quantity: z.number().int().min(1).max(10000).optional(),
|
|
spec: z.unknown().optional(),
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}/equipment:
|
|
* post:
|
|
* summary: Create an equipment instance in a gym (admin); repeats of a catalog type are new instances
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK, returns { gym, instance } }
|
|
* 400: { description: Invalid spec for the catalog kind }
|
|
* 404: { description: Gym or equipment not found }
|
|
*/
|
|
router.post(
|
|
'/gyms/:id/equipment',
|
|
validate(gymEquipmentSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const { equipmentId, quantity, spec } = req.body as z.infer<typeof gymEquipmentSchema>;
|
|
const result = await addGymEquipment(prisma, req.params.id, equipmentId, quantity ?? 1, spec);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}/equipment/{instanceId}:
|
|
* patch:
|
|
* summary: Change quantity and/or spec override of an equipment instance (admin); spec:null clears the override
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 400: { description: Equipment not in gym or invalid spec }
|
|
* 404: { description: Gym not found }
|
|
*/
|
|
router.patch(
|
|
'/gyms/:id/equipment/:instanceId',
|
|
validate(gymEquipmentInstanceSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const body = req.body as z.infer<typeof gymEquipmentInstanceSchema>;
|
|
const result = await updateGymEquipment(
|
|
prisma,
|
|
req.params.id,
|
|
req.params.instanceId,
|
|
body,
|
|
Object.hasOwn(body, 'spec'),
|
|
);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}/equipment/{instanceId}:
|
|
* delete:
|
|
* summary: Remove an equipment instance (and its photos) from a gym (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 204: { description: Removed }
|
|
* 400: { description: Equipment not in gym }
|
|
* 404: { description: Gym not found }
|
|
*/
|
|
router.delete(
|
|
'/gyms/:id/equipment/:instanceId',
|
|
asyncHandler(async (req, res) => {
|
|
await removeGymEquipment(prisma, req.params.id, req.params.instanceId);
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
const claimsQuerySchema = z.object({
|
|
status: z.enum(['PENDING', 'APPROVED', 'REJECTED']).optional(),
|
|
userId: z.string().min(1).optional(),
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/claims:
|
|
* get:
|
|
* summary: List gym claims (admin, optional ?status=)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
*/
|
|
router.get(
|
|
'/gyms/claims',
|
|
validate(claimsQuerySchema, 'query'),
|
|
asyncHandler(async (req, res) => {
|
|
const q = req.query as z.infer<typeof claimsQuerySchema>;
|
|
const result = await listGymClaims(prisma, q.status, q.userId);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/claims/{id}:
|
|
* get:
|
|
* summary: Gym claim detail (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 404: { description: Claim not found }
|
|
*/
|
|
router.get(
|
|
'/gyms/claims/:id',
|
|
asyncHandler(async (req, res) => {
|
|
const result = await getGymClaim(prisma, req.params.id);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/claims/{id}/documents/{docId}:
|
|
* get:
|
|
* summary: Download a claim document (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: File (attachment) }
|
|
* 404: { description: Claim or document not found }
|
|
*/
|
|
router.get(
|
|
'/gyms/claims/:id/documents/:docId',
|
|
asyncHandler(async (req, res) => {
|
|
const claim = await prisma.gymClaim.findUnique({
|
|
where: { id: req.params.id },
|
|
include: {
|
|
documents: { select: { id: true, originalName: true, storedName: true } },
|
|
},
|
|
});
|
|
if (!claim) throw notFound('Claim not found');
|
|
const doc = claim.documents.find((d) => d.id === req.params.docId);
|
|
if (!doc) throw notFound('Document not found');
|
|
const filePath = path.join(config.uploadDir, claim.id, doc.storedName);
|
|
if (!fs.existsSync(filePath)) throw notFound('Document file missing');
|
|
const safeName = doc.originalName.replace(/[\\/]/g, '_');
|
|
res.download(filePath, safeName);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/claims/{id}/approve:
|
|
* post:
|
|
* summary: Approve a gym claim (admin) — virtual → REAL or creates a new REAL gym
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: Approved }
|
|
* 404: { description: Claim not found }
|
|
* 409: { description: Claim is not pending }
|
|
*/
|
|
router.post(
|
|
'/gyms/claims/:id/approve',
|
|
asyncHandler(async (req, res) => {
|
|
await approveGymClaim(prisma, req.user!.id, req.params.id);
|
|
await logActivity(prisma, {
|
|
actorId: req.user!.id,
|
|
action: 'gym.claim.approved',
|
|
entityType: 'gym-claim',
|
|
entityId: req.params.id,
|
|
});
|
|
res.json({ ok: true });
|
|
}),
|
|
);
|
|
|
|
const rejectClaimSchema = z.object({
|
|
reason: z.string().max(1000).optional(),
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/claims/{id}/reject:
|
|
* post:
|
|
* summary: Reject a gym claim with an optional reason (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: Rejected }
|
|
* 404: { description: Claim not found }
|
|
* 409: { description: Claim is not pending }
|
|
*/
|
|
router.post(
|
|
'/gyms/claims/:id/reject',
|
|
validate(rejectClaimSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const { reason } = req.body as z.infer<typeof rejectClaimSchema>;
|
|
await rejectGymClaim(prisma, req.user!.id, req.params.id, reason);
|
|
await logActivity(prisma, {
|
|
actorId: req.user!.id,
|
|
action: 'gym.claim.rejected',
|
|
entityType: 'gym-claim',
|
|
entityId: req.params.id,
|
|
details: { reason: reason ?? null },
|
|
});
|
|
res.json({ ok: true });
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/gyms/{id}:
|
|
* get:
|
|
* summary: Get gym detail (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 404: { description: Gym not found }
|
|
*/
|
|
router.get(
|
|
'/gyms/:id',
|
|
asyncHandler(async (req, res) => {
|
|
const gym = await getGym(prisma, req.params.id);
|
|
res.json(gym);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users:
|
|
* get:
|
|
* summary: List users (admin, optional ?search=)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
*/
|
|
router.get(
|
|
'/users',
|
|
asyncHandler(async (req, res) => {
|
|
const search = req.query.search as string | undefined;
|
|
const result = await listUsers(prisma, search);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users:
|
|
* post:
|
|
* summary: Create user (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 201: { description: Created }
|
|
* 409: { description: Email already registered }
|
|
*/
|
|
router.post(
|
|
'/users',
|
|
validate(createUserSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof createUserSchema>;
|
|
const result = await createUser(prisma, data);
|
|
res.status(201).json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}:
|
|
* patch:
|
|
* summary: Update user (admin). Role or status change increments token_version (JWT revocation).
|
|
* Status SUSPENDED requires future suspensionUntil; BANNED requires restrictionReason.
|
|
* Login/refresh of a suspended (until active) or banned account returns 403 ACCOUNT_SUSPENDED / ACCOUNT_BANNED.
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 403: { description: Attempt to remove the last admin role }
|
|
* 404: { description: User not found }
|
|
* 409: { description: Email already registered }
|
|
*/
|
|
router.patch(
|
|
'/users/:id',
|
|
validate(updateUserSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof updateUserSchema>;
|
|
const result = await updateUser(prisma, req.params.id, data, req.user!.id);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}:
|
|
* delete:
|
|
* summary: Delete user (admin). Plans/sessions are cascade-deleted.
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 204: { description: Deleted }
|
|
* 403: { description: Own account or the last admin }
|
|
*/
|
|
router.delete(
|
|
'/users/:id',
|
|
asyncHandler(async (req, res) => {
|
|
await deleteUser(prisma, req.params.id, req.user!.id);
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/memberships:
|
|
* post:
|
|
* summary: Assign gym membership/role (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 201: { description: Created }
|
|
* 409: { description: Membership already exists }
|
|
*/
|
|
router.post(
|
|
'/users/:id/memberships',
|
|
validate(membershipSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const { gymId, roles } = req.body as z.infer<typeof membershipSchema>;
|
|
const result = await addMembership(prisma, req.params.id, gymId, roles);
|
|
res.status(201).json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/memberships/{gymId}:
|
|
* patch:
|
|
* summary: Change gym membership role (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 404: { description: Membership not found }
|
|
*/
|
|
router.patch(
|
|
'/users/:id/memberships/:gymId',
|
|
validate(updateMembershipSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const { roles } = req.body as z.infer<typeof updateMembershipSchema>;
|
|
const result = await updateMembership(prisma, req.params.id, req.params.gymId, roles);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/memberships/{gymId}:
|
|
* delete:
|
|
* summary: Remove gym membership (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 204: { description: Deleted }
|
|
*/
|
|
router.delete(
|
|
'/users/:id/memberships/:gymId',
|
|
asyncHandler(async (req, res) => {
|
|
await removeMembership(prisma, req.params.id, req.params.gymId);
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/focus-chain:
|
|
* get:
|
|
* summary: User's causal chain — priority/exclusion muscles linked to active plan exercises (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 404: { description: User not found }
|
|
*/
|
|
router.get(
|
|
'/users/:id/focus-chain',
|
|
asyncHandler(async (req, res) => {
|
|
const result = await getFocusChain(prisma, req.params.id);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/killstreak:
|
|
* get:
|
|
* summary: User's killstreak (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 404: { description: User not found }
|
|
*/
|
|
router.get(
|
|
'/users/:id/killstreak',
|
|
asyncHandler(async (req, res) => {
|
|
await ensureUser(prisma, req.params.id);
|
|
const killstreak = await getKillstreak(prisma, req.params.id);
|
|
res.json({ killstreak });
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/body-parameters:
|
|
* get:
|
|
* summary: User's body parameters over time (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 404: { description: User not found }
|
|
*/
|
|
router.get(
|
|
'/users/:id/body-parameters',
|
|
asyncHandler(async (req, res) => {
|
|
await ensureUser(prisma, req.params.id);
|
|
const result = await getBodyParameters(prisma, req.params.id);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/body-parameters/weight:
|
|
* post:
|
|
* summary: Add weight measurement for user (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 201: { description: Created }
|
|
* 404: { description: User not found }
|
|
*/
|
|
router.post(
|
|
'/users/:id/body-parameters/weight',
|
|
validate(weightSchema),
|
|
asyncHandler(async (req, res) => {
|
|
await ensureUser(prisma, req.params.id);
|
|
const data = req.body as z.infer<typeof weightSchema>;
|
|
const result = await addWeight(prisma, req.params.id, data);
|
|
await logActivity(prisma, {
|
|
actorId: req.user!.id,
|
|
action: 'weight.added',
|
|
entityType: 'user',
|
|
entityId: req.params.id,
|
|
details: { value: data.value, byAdmin: true },
|
|
});
|
|
res.status(201).json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/body-parameters/weight/{measurementId}:
|
|
* delete:
|
|
* summary: Delete a weight measurement of user (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 204: { description: Deleted }
|
|
* 404: { description: Not found }
|
|
*/
|
|
router.delete(
|
|
'/users/:id/body-parameters/weight/:measurementId',
|
|
asyncHandler(async (req, res) => {
|
|
await ensureUser(prisma, req.params.id);
|
|
const result = await deleteWeight(prisma, req.params.id, req.params.measurementId);
|
|
await logActivity(prisma, {
|
|
actorId: req.user!.id,
|
|
action: 'weight.removed',
|
|
entityType: 'user',
|
|
entityId: req.params.id,
|
|
details: { value: result.value, byAdmin: true },
|
|
});
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/body-parameters/circumference:
|
|
* post:
|
|
* summary: Add circumference measurement for user (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 201: { description: Created }
|
|
* 404: { description: User not found }
|
|
*/
|
|
router.post(
|
|
'/users/:id/body-parameters/circumference',
|
|
validate(circumferenceSchema),
|
|
asyncHandler(async (req, res) => {
|
|
await ensureUser(prisma, req.params.id);
|
|
const data = req.body as z.infer<typeof circumferenceSchema>;
|
|
const result = await addCircumference(prisma, req.params.id, data);
|
|
await logActivity(prisma, {
|
|
actorId: req.user!.id,
|
|
action: 'circumference.added',
|
|
entityType: 'user',
|
|
entityId: req.params.id,
|
|
details: { name: data.name, value: data.value, byAdmin: true },
|
|
});
|
|
res.status(201).json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/body-parameters/circumference/{measurementId}:
|
|
* delete:
|
|
* summary: Delete a circumference measurement of user (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 204: { description: Deleted }
|
|
* 404: { description: Not found }
|
|
*/
|
|
router.delete(
|
|
'/users/:id/body-parameters/circumference/:measurementId',
|
|
asyncHandler(async (req, res) => {
|
|
await ensureUser(prisma, req.params.id);
|
|
const result = await deleteCircumference(prisma, req.params.id, req.params.measurementId);
|
|
await logActivity(prisma, {
|
|
actorId: req.user!.id,
|
|
action: 'circumference.removed',
|
|
entityType: 'user',
|
|
entityId: req.params.id,
|
|
details: { name: result.name, value: result.value, byAdmin: true },
|
|
});
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/history:
|
|
* get:
|
|
* summary: User's training history (admin). Query: month=YYYY-MM.
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 400: { description: Invalid month format }
|
|
* 404: { description: User not found }
|
|
*/
|
|
router.get(
|
|
'/users/:id/history',
|
|
validate(historyQuerySchema, 'query'),
|
|
asyncHandler(async (req, res) => {
|
|
await ensureUser(prisma, req.params.id);
|
|
const { month } = req.query as z.infer<typeof historyQuerySchema>;
|
|
const result = await getHistory(prisma, req.params.id, month);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/users/{id}/exercise-progress:
|
|
* get:
|
|
* summary: User's per-exercise progress — 1RM Epley + volume (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 404: { description: User not found }
|
|
*/
|
|
router.get(
|
|
'/users/:id/exercise-progress',
|
|
asyncHandler(async (req, res) => {
|
|
await ensureUser(prisma, req.params.id);
|
|
const result = await getExerciseProgress(prisma, req.params.id);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
const logsQuerySchema = z.object({
|
|
action: z.string().min(1).max(100).optional(),
|
|
userId: z.string().min(1).max(100).optional(),
|
|
from: z
|
|
.string()
|
|
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
|
.optional(),
|
|
to: z
|
|
.string()
|
|
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
|
.optional(),
|
|
limit: z.coerce.number().int().min(1).max(500).optional(),
|
|
offset: z.coerce.number().int().min(0).optional(),
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/logs:
|
|
* get:
|
|
* summary: Activity log — user actions from the app (admin).
|
|
* Query: action, userId, from/to (YYYY-MM-DD), limit (default 100, max 500), offset (default 0).
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK, returns { logs, total } }
|
|
*/
|
|
router.get(
|
|
'/logs',
|
|
validate(logsQuerySchema, 'query'),
|
|
asyncHandler(async (req, res) => {
|
|
const q = req.query as z.infer<typeof logsQuerySchema>;
|
|
const result = await listActivityLogs(prisma, {
|
|
action: q.action,
|
|
userId: q.userId,
|
|
from: q.from,
|
|
to: q.to,
|
|
limit: q.limit ?? 100,
|
|
offset: q.offset ?? 0,
|
|
});
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
const focusAreaSchema = z
|
|
.object({
|
|
name: z.string().min(1).max(100),
|
|
nameEn: z.string().max(100).nullable().optional(),
|
|
muscle: z.string().min(1).max(50),
|
|
description: z.string().max(500).nullable().optional(),
|
|
setsMin: z.number().int().min(0).max(100).nullable().optional(),
|
|
setsMax: z.number().int().min(0).max(100).nullable().optional(),
|
|
})
|
|
.superRefine((val, ctx) => {
|
|
if (val.setsMin != null && val.setsMax != null && val.setsMin > val.setsMax) {
|
|
ctx.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
message: 'setsMin must be <= setsMax',
|
|
path: ['setsMin'],
|
|
});
|
|
}
|
|
});
|
|
const focusAreaUpdateSchema = z.object({
|
|
name: z.string().min(1).max(100).optional(),
|
|
nameEn: z.string().max(100).nullable().optional(),
|
|
muscle: z.string().min(1).max(50).optional(),
|
|
description: z.string().max(500).nullable().optional(),
|
|
setsMin: z.number().int().min(0).max(100).nullable().optional(),
|
|
setsMax: z.number().int().min(0).max(100).nullable().optional(),
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/focus-areas:
|
|
* get:
|
|
* summary: List focus areas with exercise usage counts (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
*/
|
|
router.get(
|
|
'/focus-areas',
|
|
asyncHandler(async (_req, res) => {
|
|
const result = await listFocusAreasWithUsage(prisma);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/focus-areas:
|
|
* post:
|
|
* summary: Create a focus area (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 201: { description: Created }
|
|
* 409: { description: Muscle already exists }
|
|
*/
|
|
router.post(
|
|
'/focus-areas',
|
|
validate(focusAreaSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof focusAreaSchema>;
|
|
const result = await createFocusArea(prisma, data);
|
|
res.status(201).json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/focus-areas/{id}:
|
|
* patch:
|
|
* summary: Update a focus area (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 404: { description: Not found }
|
|
*/
|
|
router.patch(
|
|
'/focus-areas/:id',
|
|
validate(focusAreaUpdateSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof focusAreaUpdateSchema>;
|
|
const result = await updateFocusArea(prisma, req.params.id, data);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/focus-areas/{id}:
|
|
* delete:
|
|
* summary: Delete a focus area (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 204: { description: Deleted }
|
|
* 404: { description: Not found }
|
|
*/
|
|
router.delete(
|
|
'/focus-areas/:id',
|
|
asyncHandler(async (req, res) => {
|
|
await deleteFocusArea(prisma, req.params.id);
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
const announcementTextSchema = z.object({
|
|
title: z.string().trim().min(1).max(120),
|
|
body: z.string().trim().min(1).max(2000),
|
|
});
|
|
const adminAnnouncementSchema = announcementTextSchema.extend({
|
|
/** null/brak = globalne; ustawione = per-siłownia (awaryjnie w imieniu właściciela). */
|
|
gymId: z.string().min(1).nullable().optional(),
|
|
});
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/announcements:
|
|
* get:
|
|
* summary: List all announcements or those of one gym (?gymId=) (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
*/
|
|
router.get(
|
|
'/announcements',
|
|
asyncHandler(async (req, res) => {
|
|
const gymId = typeof req.query.gymId === 'string' ? req.query.gymId : null;
|
|
const result = await listAnnouncementsForAdmin(prisma, { gymId });
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/announcements:
|
|
* post:
|
|
* summary: Create an announcement — global (gymId null) or for a gym (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 201: { description: Created }
|
|
* 404: { description: Gym not found }
|
|
*/
|
|
router.post(
|
|
'/announcements',
|
|
validate(adminAnnouncementSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof adminAnnouncementSchema>;
|
|
const result = await createAnnouncementAsAdmin(prisma, req.user!.id, data);
|
|
res.status(201).json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/announcements/{id}:
|
|
* patch:
|
|
* summary: Edit a manual announcement (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 200: { description: OK }
|
|
* 400: { description: System announcements cannot be edited }
|
|
* 404: { description: Not found }
|
|
*/
|
|
router.patch(
|
|
'/announcements/:id',
|
|
validate(announcementTextSchema),
|
|
asyncHandler(async (req, res) => {
|
|
const data = req.body as z.infer<typeof announcementTextSchema>;
|
|
const result = await updateAnnouncementAsAdmin(prisma, req.params.id, data);
|
|
res.json(result);
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* @openapi
|
|
* /admin/announcements/{id}:
|
|
* delete:
|
|
* summary: Delete a manual announcement (admin)
|
|
* tags: [Admin]
|
|
* responses:
|
|
* 204: { description: Deleted }
|
|
* 400: { description: System announcements cannot be deleted }
|
|
* 404: { description: Not found }
|
|
*/
|
|
router.delete(
|
|
'/announcements/:id',
|
|
asyncHandler(async (req, res) => {
|
|
await deleteAnnouncementAsAdmin(prisma, req.params.id);
|
|
res.status(204).end();
|
|
}),
|
|
);
|
|
|
|
return router;
|
|
}
|