Plany: wizard 3-etapowy tworzenia/edycji, silownia i alias tygodnia (UX + API + migracja)

This commit is contained in:
tisachi
2026-09-12 15:16:13 +02:00
parent a2d31ee46b
commit ef2fa726bb
26 changed files with 1340 additions and 361 deletions

View File

@@ -25,12 +25,16 @@ const planDaySchema = z.object({
const planWeekSchema = z.object({
index: z.number().int().min(0),
// Opcjonalny alias tygodnia (np. „Deload").
customName: z.string().max(40).nullable().optional(),
days: z.array(planDaySchema),
});
const planBaseSchema = z.object({
title: z.string().min(1).max(200),
weeksCount: z.number().int().min(1).max(8),
// Informacyjna — siłownia, w której realizowany jest plan (właściciel musi być jej członkiem).
gymId: z.string().nullable().optional(),
weeks: z.array(planWeekSchema),
});
@@ -51,7 +55,5 @@ export const updatePlanSchema = planBaseSchema.refine((d) => d.weeks.length ===
});
export const activateSchema = z.object({
startDate: z
.string()
.refine((v) => !Number.isNaN(new Date(v).getTime()), 'Invalid date'),
startDate: z.string().refine((v) => !Number.isNaN(new Date(v).getTime()), 'Invalid date'),
});

View File

@@ -21,7 +21,10 @@ import {
withdrawInvitation,
} from '../services/trainer.js';
import { addTraineeComment, deleteTraineeComment } from '../services/comments.js';
import { getTraineeExerciseProgress, getTraineeLatestResults } from '../services/exerciseProgress.js';
import {
getTraineeExerciseProgress,
getTraineeLatestResults,
} from '../services/exerciseProgress.js';
import {
abandonPlan,
activatePlan,
@@ -206,7 +209,12 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
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);
const result = await searchUsers(
prisma,
req.user!.id,
parsed.data.firstName,
parsed.data.lastName,
);
res.json(result);
}),
);
@@ -351,7 +359,12 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
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);
const result = await getTraineeCalendar(
prisma,
req.user!.id,
req.params.userId,
parsed.data.month,
);
res.json(result);
}),
);
@@ -421,11 +434,12 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* @openapi
* /trainer/trainees/{userId}/plans:
* post:
* summary: Create a plan for the trainee (owner = trainee, creator = trainer)
* 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)
* tags: [Trainer]
* responses:
* 201: { description: Created }
* 400: { description: Validation error / start date not a Monday / start week in the past }
* 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 }
* 409: { description: Trainee already has an active plan }
@@ -474,11 +488,11 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
* @openapi
* /trainer/trainees/{userId}/plans/{planId}:
* patch:
* summary: Replace plan structure (draft only)
* summary: Replace plan structure (draft only). Same body as POST (gymId, weeks[].customName)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Not a draft }
* 400: { description: Not a draft / gym not a trainee membership }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/

View File

@@ -27,12 +27,16 @@ export interface PlanDayInput {
export interface PlanWeekInput {
index: number;
/** Opcjonalny alias tygodnia (np. „Deload"). */
customName?: string | null;
days: PlanDayInput[];
}
export interface CreatePlanInput {
title: string;
weeksCount: number;
/** Informacyjna — siłownia, w której realizowany jest plan (właściciel musi być jej członkiem). */
gymId?: string | null;
weeks: PlanWeekInput[];
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
startDate?: string;
@@ -63,9 +67,28 @@ async function validateExercises(prisma: PrismaClient, weeks: PlanWeekInput[]) {
if (exercises.length !== exerciseIds.size) throw badRequest('Unknown exerciseId in plan');
}
/**
* Siłownia planu jest informacyjna, ale musi istnieć i właściciel planu
* (podopieczny w trybie trenera) musi być jej członkiem.
*/
async function validateGymMembership(
prisma: PrismaClient,
gymId: string | null | undefined,
ownerId: string,
) {
if (!gymId) return;
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw badRequest('Unknown gymId in plan');
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: ownerId, gymId } },
});
if (!membership) throw badRequest('Plan owner is not a member of the gym');
}
function weekData(weeks: PlanWeekInput[]) {
return weeks.map((w) => ({
index: w.index,
customName: w.customName ?? null,
days: {
create: w.days.map((d) => ({
dayOfWeek: d.dayOfWeek,
@@ -87,6 +110,7 @@ export async function listPlans(prisma: PrismaClient, userId: string) {
orderBy: { createdAt: 'desc' },
include: {
creator: { select: { id: true, firstName: true, lastName: true } },
gym: { select: { id: true, name: true } },
weeks: { select: { days: { select: { status: true } } } },
},
});
@@ -115,6 +139,7 @@ export async function createPlan(
creatorId?: string,
) {
await validateExercises(prisma, data.weeks);
await validateGymMembership(prisma, data.gymId, userId);
// Data startu: walidacja (poniedziałek) przed sprawdzeniem aktywnego planu.
const startOfStart = data.startDate ? parseStartMonday(data.startDate) : null;
if (startOfStart) await assertNoActivePlan(prisma, userId);
@@ -125,11 +150,16 @@ export async function createPlan(
creatorId: creatorId ?? userId,
status: 'DRAFT',
weeksCount: data.weeksCount,
gymId: data.gymId ?? null,
weeks: { create: weekData(data.weeks) },
},
include: { gym: { select: { id: true, name: true } } },
});
if (startOfStart) await applyStartDate(prisma, plan.id, userId, startOfStart);
const updated = await prisma.trainingPlan.findUnique({ where: { id: plan.id } });
const updated = await prisma.trainingPlan.findUnique({
where: { id: plan.id },
include: { gym: { select: { id: true, name: true } } },
});
return {
plan: {
id: updated!.id,
@@ -137,6 +167,7 @@ export async function createPlan(
status: updated!.status,
weeksCount: updated!.weeksCount,
startDate: updated!.startDate,
gym: updated!.gym,
},
};
}
@@ -146,6 +177,7 @@ export async function getPlan(prisma: PrismaClient, planId: string, userId: stri
const full = await prisma.trainingPlan.findUnique({
where: { id: planId },
include: {
gym: { select: { id: true, name: true } },
weeks: {
orderBy: { index: 'asc' },
include: {
@@ -175,11 +207,17 @@ export async function updatePlan(
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status !== 'DRAFT') throw badRequest('Only draft plans can be edited');
await validateExercises(prisma, data.weeks);
await validateGymMembership(prisma, data.gymId, plan.userId);
await prisma.$transaction(async (tx) => {
await tx.planWeek.deleteMany({ where: { planId: plan.id } });
await tx.trainingPlan.update({
where: { id: plan.id },
data: { title: data.title, weeksCount: data.weeksCount, weeks: { create: weekData(data.weeks) } },
data: {
title: data.title,
weeksCount: data.weeksCount,
gymId: data.gymId ?? null,
weeks: { create: weekData(data.weeks) },
},
});
});
return { ok: true };

View File

@@ -364,7 +364,10 @@ export const openapi: Record<string, unknown> = {
schema: {
type: 'object',
required: ['name'],
properties: { name: { type: 'string' }, description: { type: 'string', nullable: true } },
properties: {
name: { type: 'string' },
description: { type: 'string', nullable: true },
},
},
},
},
@@ -457,7 +460,7 @@ export const openapi: Record<string, unknown> = {
post: {
tags: ['Plans'],
summary:
'Create plan: weeks -> days (dayOfWeek) -> exercises -> sets. Optional startDate (a Monday) creates and activates the plan in one step',
'Create plan: weeks -> days (dayOfWeek) -> exercises -> sets. Optional startDate (a Monday) creates and activates the plan in one step. Optional gymId (informational; the plan owner must be a gym member) and per-week customName (alias, max 40)',
security: [{ bearerAuth: [] }],
requestBody: {
required: true,
@@ -469,6 +472,11 @@ export const openapi: Record<string, unknown> = {
properties: {
title: { type: 'string' },
weeksCount: { type: 'integer', minimum: 1, maximum: 52 },
gymId: {
type: 'string',
nullable: true,
description: 'Informational gym; the plan owner must be a member of it',
},
startDate: {
type: 'string',
description: 'YYYY-MM-DD, must be a Monday of the current or a future week',
@@ -480,6 +488,7 @@ export const openapi: Record<string, unknown> = {
required: ['index', 'days'],
properties: {
index: { type: 'integer', minimum: 0 },
customName: { type: 'string', nullable: true, maxLength: 40 },
days: {
type: 'array',
items: {
@@ -538,7 +547,8 @@ export const openapi: Record<string, unknown> = {
},
patch: {
tags: ['Plans'],
summary: 'Replace plan structure (draft only)',
summary:
'Replace plan structure (draft only). Same body as POST /plans (gymId and weeks[].customName included)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
@@ -559,7 +569,11 @@ export const openapi: Record<string, unknown> = {
required: true,
content: {
'application/json': {
schema: { type: 'object', required: ['startDate'], properties: { startDate: { type: 'string' } } },
schema: {
type: 'object',
required: ['startDate'],
properties: { startDate: { type: 'string' } },
},
},
},
},
@@ -607,7 +621,11 @@ export const openapi: Record<string, unknown> = {
required: true,
content: {
'application/json': {
schema: { type: 'object', required: ['exerciseId'], properties: { exerciseId: { type: 'string' } } },
schema: {
type: 'object',
required: ['exerciseId'],
properties: { exerciseId: { type: 'string' } },
},
},
},
},
@@ -673,7 +691,8 @@ export const openapi: Record<string, unknown> = {
'/sessions/{id}/abandon': {
post: {
tags: ['Sessions'],
summary: 'Abandon session (data kept, day -> skipped, the training cannot be executed again)',
summary:
'Abandon session (data kept, day -> skipped, the training cannot be executed again)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
@@ -691,7 +710,12 @@ export const openapi: Record<string, unknown> = {
summary: 'Calendar — training days of the active plan in a month',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'month', in: 'query', schema: { type: 'string' }, description: 'YYYY-MM (default: current)' },
{
name: 'month',
in: 'query',
schema: { type: 'string' },
description: 'YYYY-MM (default: current)',
},
],
},
},