Files
FitOS/api/src/routes/trainer.ts

700 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate, requireTrainer } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import { badRequest } from '../lib/errors.js';
import {
acceptInvitation,
archiveTrainee,
assertActiveTrainee,
declineInvitation,
getTraineeCalendar,
getTraineeDetail,
getTraineeHistory,
getTraineeMoves,
getTraineeReport,
listInvitations,
listTrainees,
searchUsers,
sendInvitation,
withdrawInvitation,
} from '../services/trainer.js';
import { addTraineeComment, deleteTraineeComment } from '../services/comments.js';
import {
getTraineeExerciseProgress,
getTraineeLatestResults,
} from '../services/exerciseProgress.js';
import {
abandonPlan,
activatePlan,
completePlan,
createPlan,
deletePlan,
getPlan,
listPlans,
updatePlan,
} from '../services/plans.js';
import { activateSchema, createPlanSchema, updatePlanSchema } from './plans-schemas.js';
import { logActivity } from '../services/audit.js';
import { asyncHandler } from '../lib/asyncHandler.js';
const invitationSchema = z.object({
userId: z.string().min(1),
});
const commentSchema = z.object({
body: z.string().min(1).max(1000),
sessionId: z.string().min(1).optional(),
sessionExerciseId: z.string().min(1).optional(),
});
const searchQuerySchema = z.object({
firstName: z.string().min(1).max(100),
lastName: z.string().min(1).max(100),
});
const calendarQuerySchema = z.object({
month: z
.string()
.regex(/^\d{4}-(0[1-9]|1[0-2])$/, 'Expected YYYY-MM')
.optional(),
});
export function createTrainerRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
const trainerOnly = requireTrainer(prisma);
/**
* @openapi
* /trainer/invitations:
* get:
* summary: My pending coaching invitations (sent + received, not expired)
* tags: [Trainer]
* responses:
* 200: { description: OK }
*/
router.get(
'/invitations',
asyncHandler(async (req, res) => {
const result = await listInvitations(prisma, req.user!.id);
res.json(result);
}),
);
/**
* @openapi
* /trainer/invitations:
* post:
* summary: Send a coaching invitation (at least one party must be a trainer)
* tags: [Trainer]
* responses:
* 201: { description: Created }
* 400: { description: Self-invite or no trainer role }
* 404: { description: User not found }
* 409: { description: Invitation exists or pending limit reached }
*/
router.post(
'/invitations',
validate(invitationSchema),
asyncHandler(async (req, res) => {
const { userId } = req.body as z.infer<typeof invitationSchema>;
const result = await sendInvitation(prisma, req.user!.id, userId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.invited',
entityType: 'coaching',
entityId: result.coaching.id,
details: { targetEmail: result.targetEmail },
});
res.status(201).json(result);
}),
);
/**
* @openapi
* /trainer/invitations/{id}/accept:
* post:
* summary: Accept a coaching invitation (invited party only)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Sender cannot accept own invitation }
* 404: { description: Invitation not found }
* 409: { description: Invitation is not pending }
* 410: { description: Invitation expired }
*/
router.post(
'/invitations/:id/accept',
asyncHandler(async (req, res) => {
const result = await acceptInvitation(prisma, req.user!.id, req.params.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.accepted',
entityType: 'coaching',
entityId: result.coaching.id,
});
res.json(result);
}),
);
/**
* @openapi
* /trainer/invitations/{id}/decline:
* post:
* summary: Decline a coaching invitation (invited party only)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Sender cannot decline own invitation }
* 404: { description: Invitation not found }
* 409: { description: Invitation is not pending }
* 410: { description: Invitation expired }
*/
router.post(
'/invitations/:id/decline',
asyncHandler(async (req, res) => {
const result = await declineInvitation(prisma, req.user!.id, req.params.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.declined',
entityType: 'coaching',
entityId: result.coaching.id,
});
res.json(result);
}),
);
/**
* @openapi
* /trainer/invitations/{id}:
* delete:
* summary: Withdraw a pending coaching invitation (sender only)
* tags: [Trainer]
* responses:
* 204: { description: Withdrawn }
* 403: { description: Only the sender can withdraw }
* 404: { description: Invitation not found }
* 409: { description: Invitation is not pending }
*/
router.delete(
'/invitations/:id',
asyncHandler(async (req, res) => {
await withdrawInvitation(prisma, req.user!.id, req.params.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.withdrawn',
entityType: 'coaching',
entityId: req.params.id,
});
res.status(204).end();
}),
);
/**
* @openapi
* /trainer/search:
* get:
* summary: Search users by first + last name (trainer only; excludes own trainees)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Missing query parameters }
* 403: { description: Trainer role required }
*/
router.get(
'/search',
trainerOnly,
asyncHandler(async (req, res) => {
const parsed = searchQuerySchema.safeParse(req.query);
if (!parsed.success) throw badRequest('firstName and lastName query parameters are required');
const result = await searchUsers(
prisma,
req.user!.id,
parsed.data.firstName,
parsed.data.lastName,
);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees:
* get:
* summary: Active trainees with metrics (trainer only; optional ?gymId= filter)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Trainer role required }
*/
router.get(
'/trainees',
trainerOnly,
asyncHandler(async (req, res) => {
const gymId = typeof req.query.gymId === 'string' ? req.query.gymId : undefined;
const result = await listTrainees(prisma, req.user!.id, gymId);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}:
* delete:
* summary: Archive the trainer–trainee relation (trainer only)
* tags: [Trainer]
* responses:
* 204: { description: Archived }
* 404: { description: Trainee not found }
*/
router.delete(
'/trainees/:userId',
trainerOnly,
asyncHandler(async (req, res) => {
await archiveTrainee(prisma, req.user!.id, req.params.userId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.archived',
entityType: 'coaching',
details: { traineeId: req.params.userId },
});
res.status(204).end();
}),
);
/**
* @openapi
* /trainer/trainees/{userId}:
* get:
* summary: Restricted trainee detail — training metrics only (no body parameters/profile).
* Gyms include equipment (limits exercises in the trainee plan editor)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 404: { description: Trainee not found }
*/
router.get(
'/trainees/:userId',
trainerOnly,
asyncHandler(async (req, res) => {
const result = await getTraineeDetail(prisma, req.user!.id, req.params.userId);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/history:
* get:
* summary: Trainee session history with plan vs. actual (trainer only)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 404: { description: Trainee not found }
*/
router.get(
'/trainees/:userId/history',
trainerOnly,
asyncHandler(async (req, res) => {
const result = await getTraineeHistory(prisma, req.user!.id, req.params.userId);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/report:
* get:
* summary: Plan vs. actual per muscle group + recommended volume range + plan days
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 404: { description: Trainee not found }
*/
router.get(
'/trainees/:userId/report',
trainerOnly,
asyncHandler(async (req, res) => {
const result = await getTraineeReport(prisma, req.user!.id, req.params.userId);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/moves:
* get:
* summary: Moved-day log (DayMove) for the trainee's active plan
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 404: { description: Trainee not found }
*/
router.get(
'/trainees/:userId/moves',
trainerOnly,
asyncHandler(async (req, res) => {
const result = await getTraineeMoves(prisma, req.user!.id, req.params.userId);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/calendar:
* get:
* summary: Trainee calendar — training days of the trainee's active plan in a month
* (?month=YYYY-MM, default: current) (trainer only)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Invalid month format }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.get(
'/trainees/:userId/calendar',
trainerOnly,
asyncHandler(async (req, res) => {
const parsed = calendarQuerySchema.safeParse(req.query);
if (!parsed.success) throw badRequest('month must be in YYYY-MM format');
const result = await getTraineeCalendar(
prisma,
req.user!.id,
req.params.userId,
parsed.data.month,
);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/exercise-progress:
* get:
* summary: Per-exercise progress (1RM Epley + volume per completed session)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.get(
'/trainees/:userId/exercise-progress',
trainerOnly,
asyncHandler(async (req, res) => {
const result = await getTraineeExerciseProgress(prisma, req.user!.id, req.params.userId);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/exercise-latest:
* get:
* summary: Most recent COMPLETED session per exercise (sets for plan prefill + 1RM)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.get(
'/trainees/:userId/exercise-latest',
trainerOnly,
asyncHandler(async (req, res) => {
const result = await getTraineeLatestResults(prisma, req.user!.id, req.params.userId);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans:
* get:
* summary: The trainee's plans (with creator)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.get(
'/trainees/:userId/plans',
trainerOnly,
asyncHandler(async (req, res) => {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await listPlans(prisma, req.params.userId);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans:
* post:
* summary: Create a plan for the trainee (owner = trainee, creator = trainer).
* Optional gymId (the trainee must be a gym member) and per-week customName (alias, max 40).
* Creation is always allowed; when the trainee already has an active plan the new
* plan stays a DRAFT and the response carries activationSkipped: true.
* tags: [Trainer]
* responses:
* 201: { description: Created }
* 400: { description: Validation error / start date not a Monday / start week in the past / gym not a trainee membership }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.post(
'/trainees/:userId/plans',
trainerOnly,
validate(createPlanSchema),
asyncHandler(async (req, res) => {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const data = req.body as z.infer<typeof createPlanSchema>;
const result = await createPlan(prisma, req.params.userId, data, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.created',
entityType: 'plan',
entityId: result.plan.id,
details: { title: result.plan.title, traineeId: req.params.userId },
});
res.status(201).json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}:
* get:
* summary: Plan details (weeks -> days -> exercises -> sets)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/
router.get(
'/trainees/:userId/plans/:planId',
trainerOnly,
asyncHandler(async (req, res) => {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await getPlan(prisma, req.params.planId, req.user!.id);
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}:
* patch:
* summary: Update plan structure. DRAFT = full replace (optional startDate = a Monday
* activates the plan in one step); ACTIVE = differential edit requiring changeNote
* (recorded in the plan edit history). Same body as POST (gymId, weeks[].customName,
* forceRemoveDays for soft-removing days that have training history).
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Not a draft/active plan / change note required / gym not a trainee membership / start date not a Monday / start week in the past / PLAN_DAY_HAS_HISTORY }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/
router.patch(
'/trainees/:userId/plans/:planId',
trainerOnly,
validate(updatePlanSchema),
asyncHandler(async (req, res) => {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const data = req.body as z.infer<typeof updatePlanSchema>;
const result = await updatePlan(prisma, req.params.planId, req.user!.id, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.updated',
entityType: 'plan',
entityId: req.params.planId,
details: { title: data.title, traineeId: req.params.userId },
});
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}:
* delete:
* summary: Delete a plan of the trainee (any status; cascades weeks/days/sessions)
* tags: [Trainer]
* responses:
* 204: { description: Deleted }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/
router.delete(
'/trainees/:userId/plans/:planId',
trainerOnly,
asyncHandler(async (req, res) => {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await deletePlan(prisma, req.params.planId, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.deleted',
entityType: 'plan',
entityId: req.params.planId,
details: { title: result.title, traineeId: req.params.userId },
});
res.status(204).end();
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}/activate:
* post:
* summary: Activate the trainee's plan (startDate must be a Monday)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Not a draft / invalid date }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
* 409: { description: Trainee already has an active plan }
*/
router.post(
'/trainees/:userId/plans/:planId/activate',
trainerOnly,
validate(activateSchema),
asyncHandler(async (req, res) => {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const { startDate } = req.body as z.infer<typeof activateSchema>;
const result = await activatePlan(prisma, req.params.planId, req.user!.id, startDate);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.activated',
entityType: 'plan',
entityId: req.params.planId,
details: { title: result.title, startDate, traineeId: req.params.userId },
});
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}/abandon:
* post:
* summary: Abandon the trainee's plan (draft/active)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Plan already closed }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/
router.post(
'/trainees/:userId/plans/:planId/abandon',
trainerOnly,
asyncHandler(async (req, res) => {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await abandonPlan(prisma, req.params.planId, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.abandoned',
entityType: 'plan',
entityId: req.params.planId,
details: { title: result.title, traineeId: req.params.userId },
});
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}/complete:
* post:
* summary: Mark the trainee's plan as completed (only when no training day is still planned)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Plan already closed / plan has pending training days }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/
router.post(
'/trainees/:userId/plans/:planId/complete',
trainerOnly,
asyncHandler(async (req, res) => {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await completePlan(prisma, req.params.planId, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.completed',
entityType: 'plan',
entityId: req.params.planId,
details: { title: result.title, traineeId: req.params.userId },
});
res.json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/comments:
* post:
* summary: Trainer comment on the trainee (anchored to a session / exercise)
* tags: [Trainer]
* responses:
* 201: { description: Created }
* 400: { description: Invalid session anchor }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.post(
'/trainees/:userId/comments',
trainerOnly,
validate(commentSchema),
asyncHandler(async (req, res) => {
const data = req.body as z.infer<typeof commentSchema>;
const result = await addTraineeComment(prisma, req.user!.id, req.params.userId, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'comment.added',
entityType: 'comment',
entityId: result.comment.id,
details: { traineeId: req.params.userId },
});
res.status(201).json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/comments/{commentId}:
* delete:
* summary: Delete the trainer's own comment on the trainee
* tags: [Trainer]
* responses:
* 204: { description: Deleted }
* 403: { description: Trainer role required }
* 404: { description: Comment not found or not the author }
*/
router.delete(
'/trainees/:userId/comments/:commentId',
trainerOnly,
asyncHandler(async (req, res) => {
await deleteTraineeComment(prisma, req.user!.id, req.params.userId, req.params.commentId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'comment.deleted',
entityType: 'comment',
entityId: req.params.commentId,
details: { traineeId: req.params.userId },
});
res.status(204).end();
}),
);
return router;
}