Plany: szablony i przebudowa sekcji - hub kafelkow kategorii zamiast listy wszystkich stanow (podstrony Aktualne/Archiwum/Szablony/Udostepnione), zapis planu jako szablon i klonowanie z atrybucja, licznik objetosci tygodnia w edytorze i detalu (backend: kind TEMPLATE, clone/as-template, GET templates i shared-by-me, volume; swagger; i18n pl/en; testy unit + integracyjne + e2e)

This commit is contained in:
tisachi
2026-11-06 02:59:12 +01:00
parent 8c259269f8
commit 57fd8e3aa6
50 changed files with 4294 additions and 564 deletions

View File

@@ -70,6 +70,9 @@ function weeksIndexShapeOk(d: { weeksCount: number; weeks: { index: number }[] }
export const createPlanSchema = planBaseSchema
.extend({
// PLAN (domyślnie) albo TEMPLATE — szablon: status wymuszony DRAFT,
// bez startDate i bez siłowni; nigdy nieaktywowalny.
kind: z.enum(['PLAN', 'TEMPLATE']).optional(),
// Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku.
startDate: z
.string()

View File

@@ -8,15 +8,21 @@ import {
acceptSkippedDay,
activatePlan,
assertPlanOwner,
clonePlanTemplate,
completePlan,
createPlan,
deletePlan,
getPlan,
getPlanTemplate,
getPlanVolume,
listPlans,
listPlanTemplates,
listSharedByMe,
listSharedWithMe,
movePlanDay,
reopenPlan,
resumePlan,
savePlanAsTemplate,
sharePlan,
suspendPlan,
unsharePlan,
@@ -63,7 +69,8 @@ export function createPlanRoutes({ prisma }: AppDeps) {
* exercises -> sets. Optional startDate (a Monday, current or future week) is
* stored as the planned start; activation is a separate action
* (POST /plans/{id}/activate). Days that would fall before today under the
* marked start are rejected.
* marked start are rejected. Optional kind=TEMPLATE creates a reusable plan
* template (private to its author; startDate rejected, no gym, never activatable).
* tags: [Plans]
* responses:
* 201: { description: Created }
@@ -103,6 +110,61 @@ export function createPlanRoutes({ prisma }: AppDeps) {
}),
);
/**
* @openapi
* /plans/shared-by-me:
* get:
* summary: Plans the user has shared with others (with the recipients)
* tags: [Plans]
* responses:
* 200: { description: OK }
*/
router.get(
'/shared-by-me',
asyncHandler(async (req, res) => {
const result = await listSharedByMe(prisma, req.user!.id);
res.json(result);
}),
);
/**
* @openapi
* /plans/templates:
* get:
* summary: The user's plan templates (private library): per-template counters
* (weeks, days, exercises) and usedCount (plans cloned from the template).
* tags: [Plans]
* responses:
* 200: { description: OK }
*/
router.get(
'/templates',
asyncHandler(async (req, res) => {
const result = await listPlanTemplates(prisma, req.user!.id);
res.json(result);
}),
);
/**
* @openapi
* /plans/templates/{id}:
* get:
* summary: Full template structure + usage list. The derived list is limited to
* plans visible to the caller (their own or active trainees' plans);
* usedCount is the total count. Templates are private to their author.
* tags: [Plans]
* responses:
* 200: { description: OK }
* 404: { description: Not found (missing, not a template, or not the author) }
*/
router.get(
'/templates/:id',
asyncHandler(async (req, res) => {
const result = await getPlanTemplate(prisma, req.params.id, req.user!.id);
res.json(result);
}),
);
/**
* @openapi
* /plans/{id}:
@@ -306,6 +368,84 @@ export function createPlanRoutes({ prisma }: AppDeps) {
}),
);
/**
* @openapi
* /plans/{id}/clone:
* post:
* summary: Clone the user's plan TEMPLATE into a new DRAFT plan (kind=PLAN) with
* sourceTemplateId attribution. Deep copy of weeks -> days -> exercises -> sets;
* template days carry no dates.
* tags: [Plans]
* responses:
* 201: { description: Cloned (returns { plan }) }
* 400: { description: Code TEMPLATE_NOT_PLAN when the source is not a template }
* 403: { description: The caller does not own the template }
* 404: { description: Template not found }
*/
router.post(
'/:id/clone',
asyncHandler(async (req, res) => {
const result = await clonePlanTemplate(prisma, req.params.id, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.template.cloned',
entityType: 'plan',
entityId: result.plan.id,
details: { templateId: req.params.id, title: result.plan.title },
});
res.status(201).json(result);
}),
);
/**
* @openapi
* /plans/{id}/as-template:
* post:
* summary: Save a regular plan as a reusable TEMPLATE owned by the actor — allowed
* for the plan owner OR its creator (a trainer pulling their own trainee plans
* into their library). Snapshot of the structure; the source plan is untouched.
* tags: [Plans]
* responses:
* 201: { description: Template created (returns { plan }) }
* 400: { description: Code TEMPLATE_NOT_PLAN when the source is already a template }
* 403: { description: The actor is neither the owner nor the creator }
* 404: { description: Plan not found }
*/
router.post(
'/:id/as-template',
asyncHandler(async (req, res) => {
const result = await savePlanAsTemplate(prisma, req.params.id, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.template.saved',
entityType: 'plan',
entityId: result.plan.id,
details: { sourcePlanId: req.params.id, title: result.plan.title },
});
res.status(201).json(result);
}),
);
/**
* @openapi
* /plans/{id}/volume:
* get:
* summary: Volume cockpit of the owner's plan — planned vs. actual weekly sets per
* muscle with the recommended FocusArea ranges (same core as the trainer report).
* tags: [Plans]
* responses:
* 200: { description: OK }
* 400: { description: Code TEMPLATE_NOT_PLAN for templates }
* 404: { description: Plan not found or caller is not the owner }
*/
router.get(
'/:id/volume',
asyncHandler(async (req, res) => {
const result = await getPlanVolume(prisma, req.params.id, req.user!.id);
res.json(result);
}),
);
/**
* @openapi
* /plans/{id}/activate:

View File

@@ -28,6 +28,7 @@ import {
import {
abandonPlan,
activatePlan,
clonePlanTemplate,
completePlan,
createPlan,
deletePlan,
@@ -465,6 +466,44 @@ export function createTrainerRoutes({ prisma }: AppDeps) {
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/from-template/{templateId}:
* post:
* summary: Clone the TRAINER's own template into a new DRAFT plan for the trainee
* (owner = trainee, creator = trainer, sourceTemplateId = template). Deep copy;
* activation stays a separate action. The trainee gets the PLAN_READY notification.
* tags: [Trainer]
* responses:
* 201: { description: Created (returns { plan }) }
* 400: { description: Code TEMPLATE_NOT_PLAN when the source is not a template }
* 403: { description: Trainer role required / template not owned by the trainer }
* 404: { description: Trainee or template not found }
*/
router.post(
'/trainees/:userId/plans/from-template/:templateId',
trainerOnly,
asyncHandler(async (req, res) => {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await clonePlanTemplate(prisma, req.params.templateId, req.user!.id, {
ownerId: req.params.userId,
creatorId: req.user!.id,
});
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.template.cloned',
entityType: 'plan',
entityId: result.plan.id,
details: {
templateId: req.params.templateId,
title: result.plan.title,
traineeId: req.params.userId,
},
});
res.status(201).json(result);
}),
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}:

View File

@@ -8,7 +8,7 @@ function startOfIsoWeek(now: Date): Date {
export async function getDashboard(prisma: PrismaClient, userId: string) {
const activePlan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
where: { userId, status: 'ACTIVE', kind: 'PLAN' },
});
// Killstreak liczy dni także ze skończonych i wstrzymanych planów — sam brak
@@ -17,7 +17,7 @@ export async function getDashboard(prisma: PrismaClient, userId: string) {
const planHistory = activePlan
? true
: !!(await prisma.trainingPlan.findFirst({
where: { userId, status: { in: ['COMPLETED', 'SUSPENDED'] } },
where: { userId, status: { in: ['COMPLETED', 'SUSPENDED'] }, kind: 'PLAN' },
select: { id: true },
}));
// Okno kropek killstreaka: 30 ostatnich dni (włącznie z dziś).
@@ -119,7 +119,7 @@ export async function getDashboard(prisma: PrismaClient, userId: string) {
// Historia — globalna (ponad wszystkimi planami), w kontrze do progress/extra/missing,
// które dotyczą wyłącznie aktywnego planu.
const [completedPlans, historySessions, historySets] = await Promise.all([
prisma.trainingPlan.count({ where: { userId, status: 'COMPLETED' } }),
prisma.trainingPlan.count({ where: { userId, status: 'COMPLETED', kind: 'PLAN' } }),
prisma.trainingSession.count({ where: completedSessionWhere }),
prisma.sessionSet.count({
where: {

View File

@@ -28,7 +28,7 @@ export async function createNotification(prisma: PrismaClient, input: CreateNoti
export async function notifyGymDeleted(prisma: PrismaClient, gymId: string, gymName: string) {
const [members, planOwners] = await Promise.all([
prisma.gymMembership.findMany({ where: { gymId }, select: { userId: true } }),
prisma.trainingPlan.findMany({ where: { gymId }, select: { userId: true } }),
prisma.trainingPlan.findMany({ where: { gymId, kind: 'PLAN' }, select: { userId: true } }),
]);
const userIds = [...new Set([...members, ...planOwners].map((r) => r.userId))];
if (userIds.length === 0) return;

View File

@@ -19,7 +19,7 @@ export async function getFocusChain(prisma: PrismaClient, userId: string) {
if (!user) throw notFound('User not found');
const activePlan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
where: { userId, status: 'ACTIVE', kind: 'PLAN' },
include: {
weeks: {
include: {

View File

@@ -0,0 +1,189 @@
import type { PrismaClient } from '@prisma/client';
/**
* Wspólne rdzenie liczenia objętości (plan vs. realizacja per partia).
* Single Source of Mutation: te same reguły agregacji i progów używa
* raport trenera (`getTraineeReport`) i kokpit objętości planu
* (`GET /plans/:id/volume`) — jedna implementacja, dwa miejsca użycia.
*/
export interface MuscleReport {
muscle: string;
planned: { sets: number; reps: number };
actual: { sets: number; reps: number };
extra: { sets: number };
missing: { sets: number };
completionPct: number;
/** Zakres tygodniowy FocusArea przeskalowany do długości planu (null gdy partia bez zakresu). */
recommendedRange: { setsMin: number; setsMax: number } | null;
outOfRange: boolean;
}
interface PlannedDaySource {
exercises: {
exercise: { primaryMuscle: string };
sets: { reps: number | null }[];
}[];
}
/** Czyste: planowana objętość per partia; kolejność = pierwsze wystąpienie w planie. */
export function aggregatePlannedByMuscle(
days: PlannedDaySource[],
): Map<string, { sets: number; reps: number }> {
const planned = new Map<string, { sets: number; reps: number }>();
for (const day of days) {
for (const pe of day.exercises) {
const acc = planned.get(pe.exercise.primaryMuscle) ?? { sets: 0, reps: 0 };
for (const s of pe.sets) {
acc.sets += 1;
if (s.reps != null) acc.reps += s.reps;
}
planned.set(pe.exercise.primaryMuscle, acc);
}
}
return planned;
}
interface SessionVolumeSource {
exercises: {
removed: boolean;
hidden: boolean;
exercise: { primaryMuscle: string };
sets: { reps: number | null; planSetId: string | null }[];
}[];
}
/** Czyste: zrealizowane serie planowe + ponadplanowe per partia. */
export function aggregateActualByMuscle(sessions: SessionVolumeSource[]): {
actual: Map<string, { sets: number; reps: number }>;
extra: Map<string, number>;
} {
const actual = new Map<string, { sets: number; reps: number }>();
const extra = new Map<string, number>();
for (const session of sessions) {
for (const ex of session.exercises) {
if (ex.removed || ex.hidden) continue;
const muscle = ex.exercise.primaryMuscle;
for (const st of ex.sets) {
if (st.reps == null) continue;
if (st.planSetId != null) {
const acc = actual.get(muscle) ?? { sets: 0, reps: 0 };
acc.sets += 1;
acc.reps += st.reps;
actual.set(muscle, acc);
} else {
extra.set(muscle, (extra.get(muscle) ?? 0) + 1);
}
}
}
}
return { actual, extra };
}
/** Czyste: raport per partia + progi zakresu (tygodniowy FocusArea * weeksCount). */
export function buildMuscleReports(
planned: Map<string, { sets: number; reps: number }>,
actual: Map<string, { sets: number; reps: number }>,
extra: Map<string, number>,
rangeByMuscle: Map<string, { setsMin: number | null; setsMax: number | null }>,
weeksCount: number,
): MuscleReport[] {
return [...planned.entries()].map(([muscle, p]) => {
const a = actual.get(muscle) ?? { sets: 0, reps: 0 };
const e = extra.get(muscle) ?? 0;
const missing = Math.max(0, p.sets - a.sets);
const completionPct = p.sets > 0 ? Math.min(100, Math.round((a.sets / p.sets) * 100)) : 0;
const fa = rangeByMuscle.get(muscle);
const recommendedRange =
fa && fa.setsMin != null && fa.setsMax != null
? { setsMin: fa.setsMin * weeksCount, setsMax: fa.setsMax * weeksCount }
: null;
const outOfRange =
recommendedRange != null &&
(a.sets < recommendedRange.setsMin || a.sets > recommendedRange.setsMax);
return {
muscle,
planned: p,
actual: a,
extra: { sets: e },
missing: { sets: missing },
completionPct,
recommendedRange,
outOfRange,
};
});
}
/** Zakresy zalecanej objętości tygodniowej per partia (FocusArea). */
export async function loadFocusRanges(
prisma: PrismaClient,
): Promise<Map<string, { setsMin: number | null; setsMax: number | null }>> {
const focusAreas = await prisma.focusArea.findMany({
select: { muscle: true, setsMin: true, setsMax: true },
});
return new Map(focusAreas.map((f) => [f.muscle, { setsMin: f.setsMin, setsMax: f.setsMax }]));
}
/** Ukończone sesje dni planu w minimalnym kształcie do agregacji objętości. */
export async function loadCompletedSessions(
prisma: PrismaClient,
dayIds: string[],
): Promise<SessionVolumeSource[]> {
return prisma.trainingSession.findMany({
where: { status: 'COMPLETED', dayId: { in: dayIds } },
select: {
exercises: {
select: {
removed: true,
hidden: true,
exercise: { select: { primaryMuscle: true } },
sets: { select: { reps: true, planSetId: true } },
},
},
},
});
}
/**
* Kokpit objętości pojedynczego planu (identyczna logika co sekcja partii
* w raporcie trenera). Zakłada, że plan został już zwalidowany przez trasę.
*/
export async function computePlanVolume(
prisma: PrismaClient,
planId: string,
weeksCount: number,
): Promise<MuscleReport[]> {
const weeks = await prisma.planWeek.findMany({
where: { planId },
select: {
days: {
where: { removedAt: null },
select: {
id: true,
exercises: {
select: {
exercise: { select: { primaryMuscle: true } },
sets: { select: { reps: true } },
},
},
},
},
},
});
const days = weeks.flatMap((w) => w.days);
const [rangeByMuscle, sessions] = await Promise.all([
loadFocusRanges(prisma),
loadCompletedSessions(
prisma,
days.map((d) => d.id),
),
]);
const { actual, extra } = aggregateActualByMuscle(sessions);
return buildMuscleReports(
aggregatePlannedByMuscle(days),
actual,
extra,
rangeByMuscle,
weeksCount,
);
}

View File

@@ -2,6 +2,7 @@ import type { Prisma, PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
import { isPrismaUnique } from '../lib/prisma.js';
import { createNotification } from './feed.js';
import { computePlanVolume } from './planVolume.js';
export interface PlanSetInput {
/** Istniejące id serii — pozwala zachować wiersz (i jego powiązania) przy edycji planu ACTIVE. */
@@ -46,6 +47,8 @@ export interface CreatePlanInput {
weeks: PlanWeekInput[];
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
startDate?: string;
/** TEMPLATE = szablon wielokrotnego użytku (nigdy nieaktywowalny); domyślnie PLAN. */
kind?: 'PLAN' | 'TEMPLATE';
}
export interface UpdatePlanInput extends CreatePlanInput {
@@ -94,6 +97,20 @@ export async function assertPlanOwner(prisma: PrismaClient, planId: string, user
return plan;
}
/**
* Szablon (kind=TEMPLATE) nie jest planem do realizacji — wszystkie akcje
* cyklu życia (activate/abandon/complete/suspend/resume/reopen/move day/share)
* są dla niego zablokowane jednym guardem.
*/
export function assertRegularPlan(plan: { kind: string }) {
if (plan.kind === 'TEMPLATE')
throw new AppError(
400,
'TEMPLATE_NOT_PLAN',
'This action is not available for a plan template',
);
}
async function validateExercises(prisma: PrismaClient, weeks: PlanWeekInput[]) {
const exerciseIds = new Set(
weeks.flatMap((w) => w.days.flatMap((d) => d.exercises.map((e) => e.exerciseId))),
@@ -142,20 +159,43 @@ function weekData(weeks: PlanWeekInput[]) {
export async function listPlans(prisma: PrismaClient, userId: string) {
const plans = await prisma.trainingPlan.findMany({
where: { userId },
where: { userId, kind: 'PLAN' },
orderBy: { createdAt: 'desc' },
include: {
creator: { select: { id: true, firstName: true, lastName: true } },
gym: { select: { id: true, name: true } },
weeks: { select: { days: { where: { removedAt: null }, select: { status: true } } } },
weeks: {
select: {
index: true,
days: {
where: { removedAt: null },
select: {
status: true,
date: true,
dayOfWeek: true,
_count: { select: { exercises: true } },
},
},
},
},
},
});
const startOfToday = new Date();
startOfToday.setHours(0, 0, 0, 0);
return {
plans: plans.map((p) => {
const days = (p.weeks ?? []).flatMap((w) => w.days);
const days = (p.weeks ?? []).flatMap((w) =>
w.days.map((d) => ({ ...d, weekIndex: w.index })),
);
const completed = days.filter((d) => d.status === 'COMPLETED').length;
const total = days.length;
const { weeks: _weeks, ...rest } = p;
// Hero listy: currentWeek = tydzień najbliższego nierozstrzygniętego dnia
// z datą; nextDay = pierwszy dzień PLANNED z datą od dzisiaj w górę.
const pending = days
.filter((d) => d.status === 'PLANNED' && d.date)
.sort((a, b) => a.date!.getTime() - b.date!.getTime());
const next = pending.find((d) => d.date!.getTime() >= startOfToday.getTime());
return {
...rest,
progress: {
@@ -163,6 +203,14 @@ export async function listPlans(prisma: PrismaClient, userId: string) {
total,
percent: total > 0 ? Math.round((completed / total) * 100) : 0,
},
currentWeek: pending.length > 0 ? pending[0].weekIndex : null,
nextDay: next
? {
date: next.date!.toISOString(),
dayOfWeek: next.dayOfWeek,
exerciseCount: next._count.exercises,
}
: null,
};
}),
};
@@ -174,11 +222,18 @@ export async function createPlan(
data: CreatePlanInput,
creatorId?: string,
) {
const isTemplate = data.kind === 'TEMPLATE';
// Szablon należy wyłącznie do autora i nigdy nie ma startu ani siłowni.
if (isTemplate) {
if (creatorId && creatorId !== userId)
throw badRequest('Plan templates must belong to their author');
if (data.startDate) throw badRequest('Plan templates have no start date');
}
await validateExercises(prisma, data.weeks);
await validateGymMembership(prisma, data.gymId, userId);
if (!isTemplate) await validateGymMembership(prisma, data.gymId, userId);
// Data startu: walidacja (poniedziałek, tydzień bieżący lub przyszły) przed
// utworzeniem planu + dni nie mogą wypadać w przeszłości względem startu.
const startOfStart = data.startDate ? parseStartMonday(data.startDate) : null;
const startOfStart = !isTemplate && data.startDate ? parseStartMonday(data.startDate) : null;
if (startOfStart) assertDaysNotInPast(startOfStart, data.weeks);
const plan = await prisma.trainingPlan.create({
data: {
@@ -186,8 +241,9 @@ export async function createPlan(
userId,
creatorId: creatorId ?? userId,
status: 'DRAFT',
kind: isTemplate ? 'TEMPLATE' : 'PLAN',
weeksCount: data.weeksCount,
gymId: data.gymId ?? null,
gymId: isTemplate ? null : (data.gymId ?? null),
// Zaznaczony start = planowany start szkicu; aktywacja to osobna akcja
// (POST /plans/:id/activate) — tworzenie NIGDY nie aktywuje planu.
startDate: startOfStart,
@@ -213,6 +269,7 @@ export async function createPlan(
id: updated!.id,
title: updated!.title,
status: updated!.status,
kind: updated!.kind,
weeksCount: updated!.weeksCount,
startDate: updated!.startDate,
gym: updated!.gym,
@@ -233,9 +290,10 @@ export async function updatePlanGym(
) {
const plan = await prisma.trainingPlan.findUnique({
where: { id: planId },
select: { id: true, userId: true },
select: { id: true, userId: true, kind: true },
});
if (!plan || plan.userId !== userId) throw notFound('Plan not found');
assertRegularPlan(plan);
await validateGymMembership(prisma, gymId, userId);
const updated = await prisma.trainingPlan.update({
where: { id: plan.id },
@@ -247,6 +305,10 @@ export async function updatePlanGym(
export async function getPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
// Szablon jest prywatny — widzi go wyłącznie autor (trener podopiecznego
// i odbiorca share'a nie mają do niego dostępu; share szablonu jest
// zablokowany guardem w sharePlan).
if (plan.kind === 'TEMPLATE' && plan.userId !== userId) throw notFound('Plan not found');
// `shares` eksponowane tylko dla właściciela (lista odbiorców do dialogu
// „Udostępnij”); trener i odbiorca share'a dostają ten sam widok bez tej sekcji.
const isOwner = plan.userId === userId;
@@ -312,6 +374,26 @@ export async function updatePlan(
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status !== 'DRAFT' && plan.status !== 'ACTIVE')
throw badRequest('Only a draft or an active plan can be edited');
// Szablon: zawsze pełna wymiana struktury (jak DRAFT), bez startu i siłowni —
// bez logiki rozliczania różnic i bez notatki audytowej.
if (plan.kind === 'TEMPLATE') {
if (data.startDate) throw badRequest('Plan templates have no start date');
await validateExercises(prisma, data.weeks);
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,
gymId: null,
startDate: null,
weeks: { create: weekData(data.weeks) },
},
});
});
return { ok: true };
}
await validateExercises(prisma, data.weeks);
await validateGymMembership(prisma, data.gymId, plan.userId);
// Plan w trakcie realizacji: zmiany rozliczamy wiersz po wierszu (bez rekolekcji),
@@ -817,6 +899,7 @@ export async function movePlanDay(
input: MoveDayInput,
) {
const plan = await assertPlanOwner(prisma, planId, userId);
assertRegularPlan(plan);
if (plan.status !== 'ACTIVE') throw badRequest('Only active plans have movable training days');
if (!plan.startDate) throw badRequest('An active plan must have a start date');
const day = await prisma.planDay.findFirst({
@@ -923,6 +1006,7 @@ export async function activatePlan(
rawStartDate: string,
) {
const plan = await assertPlanAccess(prisma, planId, userId);
assertRegularPlan(plan);
if (plan.status !== 'DRAFT') throw badRequest('Only draft plans can be activated');
// Walidacja daty (poniedziałek) przed sprawdzeniem aktywnego planu.
const startOfStart = parseStartMonday(rawStartDate);
@@ -952,7 +1036,7 @@ function parseStartMonday(rawStartDate: string): Date {
async function assertNoActivePlan(prisma: PrismaClient, userId: string) {
const existingActive = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
where: { userId, status: 'ACTIVE', kind: 'PLAN' },
});
if (existingActive) throw conflict('User already has an active plan');
}
@@ -978,7 +1062,7 @@ async function applyStartDate(
try {
await prisma.$transaction(async (tx) => {
const existingActive = await tx.trainingPlan.findFirst({
where: { userId: ownerId, status: 'ACTIVE' },
where: { userId: ownerId, status: 'ACTIVE', kind: 'PLAN' },
});
if (existingActive) throw conflict('User already has an active plan');
for (const week of weeks) {
@@ -1003,6 +1087,7 @@ async function applyStartDate(
export async function abandonPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
assertRegularPlan(plan);
// Tylko aktywny plan można porzucić — DRAFT kończy się przez edycję/usunięcie.
if (plan.status !== 'ACTIVE') throw badRequest('Only an active plan can be abandoned');
await prisma.trainingPlan.update({
@@ -1022,6 +1107,7 @@ export async function abandonPlan(prisma: PrismaClient, planId: string, userId:
*/
export async function suspendPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
assertRegularPlan(plan);
if (plan.status !== 'ACTIVE') throw badRequest('Only an active plan can be suspended');
const running = await prisma.trainingSession.count({
where: { status: 'IN_PROGRESS', day: { week: { planId: plan.id } } },
@@ -1045,6 +1131,7 @@ export async function suspendPlan(prisma: PrismaClient, planId: string, userId:
*/
export async function resumePlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanOwner(prisma, planId, userId);
assertRegularPlan(plan);
if (plan.status !== 'SUSPENDED') throw badRequest('Only a suspended plan can be resumed');
// Pre-check; rozstrzygnięcie jest atomowo w transakcji + częściowy indeks
// unikalny (TrainingPlan_userId_active_key) jako ostatnia linia obrony.
@@ -1074,7 +1161,7 @@ export async function resumePlan(prisma: PrismaClient, planId: string, userId: s
try {
await prisma.$transaction(async (tx) => {
const existingActive = await tx.trainingPlan.findFirst({
where: { userId: plan.userId, status: 'ACTIVE', id: { not: plan.id } },
where: { userId: plan.userId, status: 'ACTIVE', id: { not: plan.id }, kind: 'PLAN' },
});
if (existingActive) throw conflict('User already has an active plan');
for (const m of moves) {
@@ -1098,13 +1185,14 @@ export async function resumePlan(prisma: PrismaClient, planId: string, userId: s
/** Wersja assertNoActivePlan dla wznowienia: ignoruje sam wznowiony plan. */
async function assertNoOtherActivePlan(prisma: PrismaClient, ownerId: string, planId: string) {
const otherActive = await prisma.trainingPlan.findFirst({
where: { userId: ownerId, status: 'ACTIVE', id: { not: planId } },
where: { userId: ownerId, status: 'ACTIVE', id: { not: planId }, kind: 'PLAN' },
});
if (otherActive) throw conflict('User already has an active plan');
}
export async function completePlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
assertRegularPlan(plan);
// Tylko aktywny plan można ukończyć — DRAFT nie zaczął się jeszcze realizować.
if (plan.status !== 'ACTIVE') throw badRequest('Only an active plan can be completed');
// Ręczne ukończenie tylko po domknięciu wszystkich dni (completed/skipped —
@@ -1131,13 +1219,14 @@ export async function completePlan(prisma: PrismaClient, planId: string, userId:
*/
export async function reopenPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanOwner(prisma, planId, userId);
assertRegularPlan(plan);
if (plan.status !== 'COMPLETED' && plan.status !== 'ABANDONED')
throw badRequest('Only a completed or abandoned plan can be reopened');
// Jeden aktywny plan dotyczy właściciela.
// Pre-check + częściowy indeks unikalny (TrainingPlan_userId_active_key)
// rozstrzyga równoległe wznowienia/aktywacje.
const otherActive = await prisma.trainingPlan.findFirst({
where: { userId: plan.userId, status: 'ACTIVE', id: { not: plan.id } },
where: { userId: plan.userId, status: 'ACTIVE', id: { not: plan.id }, kind: 'PLAN' },
});
if (otherActive) throw conflict('User already has an active plan');
try {
@@ -1164,6 +1253,7 @@ export async function sharePlan(
userId: string,
) {
const plan = await assertPlanAccess(prisma, planId, requesterId);
assertRegularPlan(plan);
if (plan.userId !== requesterId) throw forbidden('Only the plan owner can share the plan');
if (userId === requesterId) throw badRequest('Cannot share a plan with yourself');
const coaching =
@@ -1211,7 +1301,7 @@ export async function unsharePlan(
/** Plans explicitly shared with the user (read-only), with the sharer's name. */
export async function listSharedWithMe(prisma: PrismaClient, userId: string) {
const shares = await prisma.planShare.findMany({
where: { sharedWithId: userId },
where: { sharedWithId: userId, plan: { kind: 'PLAN' } },
include: {
sharedBy: { select: { id: true, firstName: true, lastName: true } },
plan: {
@@ -1260,3 +1350,292 @@ export async function getMyTrainers(prisma: PrismaClient, userId: string) {
})),
};
}
/* ---------------------------------------------------------------------------
* Szablony planów (kind=TEMPLATE): snapshot-klon, atrybucja, licznik użyć
* ------------------------------------------------------------------------- */
/**
* Głęboki snapshot struktury planu: tygodnie (index, customName) -> dni
* (dayOfWeek BEZ dat) -> ćwiczenia (order) -> serie (pełne parametry).
* Używany przez klon szablonu i „zapisz jako szablon" (w obie strony).
*/
async function planStructureForClone(prisma: PrismaClient, sourcePlanId: string) {
const weeks = await prisma.planWeek.findMany({
where: { planId: sourcePlanId },
orderBy: { index: 'asc' },
include: {
days: {
orderBy: { dayOfWeek: 'asc' },
include: {
exercises: {
orderBy: { order: 'asc' },
include: { sets: { orderBy: { index: 'asc' } } },
},
},
},
},
});
return weeks.map((w) => ({
index: w.index,
customName: w.customName,
days: {
create: w.days.map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: {
create: d.exercises.map((e) => ({
exerciseId: e.exerciseId,
order: e.order,
sets: {
create: e.sets.map((s) => ({
index: s.index,
reps: s.reps,
loadKg: s.loadKg,
restSec: s.restSec,
rir: s.rir,
cardioBpm: s.cardioBpm,
timeSec: s.timeSec,
speed: s.speed,
})),
},
})),
},
})),
},
}));
}
/**
* Klon szablonu do nowego DRAFT (kind=PLAN) ze `sourceTemplateId` (atrybucja).
* Domyślnie klonuje sobie zalogowany (użycie szablonu); trener może sklonować
* WŁASNY szablon dla podopiecznego (ownerId = podopieczny, creatorId = trener).
*/
export async function clonePlanTemplate(
prisma: PrismaClient,
templateId: string,
actorId: string,
opts?: { ownerId?: string; creatorId?: string },
) {
const template = await prisma.trainingPlan.findUnique({ where: { id: templateId } });
if (!template) throw notFound('Plan template not found');
if (template.kind !== 'TEMPLATE')
throw new AppError(400, 'TEMPLATE_NOT_PLAN', 'Source plan is not a template');
if (template.userId !== actorId) throw forbidden('You do not own this template');
const ownerId = opts?.ownerId ?? actorId;
const weeks = await planStructureForClone(prisma, template.id);
const plan = await prisma.trainingPlan.create({
data: {
title: template.title,
userId: ownerId,
creatorId: opts?.creatorId ?? actorId,
status: 'DRAFT',
kind: 'PLAN',
sourceTemplateId: template.id,
weeksCount: template.weeksCount,
weeks: { create: weeks },
},
select: {
id: true,
title: true,
status: true,
kind: true,
weeksCount: true,
sourceTemplateId: true,
},
});
// Klon trenera dla podopiecznego = powiadomienie jak przy zwykłym planie trenera.
if (ownerId !== actorId) {
await createNotification(prisma, {
userId: ownerId,
type: 'PLAN_READY',
title: `Trener utworzył dla Ciebie plan: ${plan.title}`,
payload: { planId: plan.id, planTitle: plan.title },
});
}
return { plan };
}
/**
* „Zapisz plan jako szablon": snapshot struktury planu (kind=PLAN) do nowego
* TEMPLATE należącego do SPRAWCY — właściciel planu albo jego autor (trener,
* który sam zrobił plan dla podopiecznego, wciąga go do własnej biblioteki).
*/
export async function savePlanAsTemplate(prisma: PrismaClient, planId: string, actorId: string) {
const plan = await prisma.trainingPlan.findUnique({ where: { id: planId } });
if (!plan) throw notFound('Plan not found');
if (plan.kind !== 'PLAN')
throw new AppError(400, 'TEMPLATE_NOT_PLAN', 'Only a regular plan can be saved as a template');
if (plan.userId !== actorId && plan.creatorId !== actorId)
throw forbidden('Only the plan owner or its author can save a template');
const weeks = await planStructureForClone(prisma, plan.id);
const template = await prisma.trainingPlan.create({
data: {
title: plan.title,
userId: actorId,
creatorId: actorId,
status: 'DRAFT',
kind: 'TEMPLATE',
weeksCount: plan.weeksCount,
weeks: { create: weeks },
},
select: { id: true, title: true, status: true, kind: true, weeksCount: true },
});
return { plan: template };
}
/** Biblioteka szablonów zalogowanego (prywatna): licznik dni/ćwiczeń/użyć. */
export async function listPlanTemplates(prisma: PrismaClient, userId: string) {
const templates = await prisma.trainingPlan.findMany({
where: { userId, kind: 'TEMPLATE' },
orderBy: { updatedAt: 'desc' },
select: {
id: true,
title: true,
weeksCount: true,
createdAt: true,
updatedAt: true,
weeks: {
select: { days: { select: { _count: { select: { exercises: true } } } } },
},
_count: { select: { templateDerivations: true } },
},
});
return {
templates: templates.map((t) => {
const days = (t.weeks ?? []).flatMap((w) => w.days);
return {
id: t.id,
title: t.title,
weeksCount: t.weeksCount,
daysCount: days.length,
exercisesCount: days.reduce((n, d) => n + d._count.exercises, 0),
usedCount: t._count.templateDerivations,
createdAt: t.createdAt,
updatedAt: t.updatedAt,
};
}),
};
}
/**
* Pełna struktura szablonu + lista planów z niego utworzonych, ale TYLKO
* widoczne sprawcy (jego własne albo podopieczni w ACTIVE coaching) —
* użyć planów obcych nie pokazujemy; `usedCount` to pełna liczba bezwzględna.
*/
export async function getPlanTemplate(prisma: PrismaClient, templateId: string, userId: string) {
const meta = await prisma.trainingPlan.findUnique({ where: { id: templateId } });
if (!meta || meta.kind !== 'TEMPLATE' || meta.userId !== userId)
throw notFound('Plan template not found');
const traineeIds = (
await prisma.coaching.findMany({
where: { trainerId: userId, status: 'ACTIVE' },
select: { userId: true },
})
).map((c) => c.userId);
const visibleOr: Prisma.TrainingPlanWhereInput[] = [{ userId }];
if (traineeIds.length > 0) visibleOr.push({ userId: { in: traineeIds } });
const [full, usedCount, derived] = await Promise.all([
prisma.trainingPlan.findUnique({
where: { id: templateId },
include: {
weeks: {
orderBy: { index: 'asc' },
include: {
days: {
orderBy: { dayOfWeek: 'asc' },
include: {
exercises: {
orderBy: { order: 'asc' },
include: { exercise: true, sets: { orderBy: { index: 'asc' } } },
},
},
},
},
},
},
}),
prisma.trainingPlan.count({ where: { sourceTemplateId: templateId } }),
prisma.trainingPlan.findMany({
where: { sourceTemplateId: templateId, OR: visibleOr },
orderBy: { createdAt: 'desc' },
include: {
user: { select: { id: true, firstName: true, lastName: true } },
weeks: { select: { days: { where: { removedAt: null }, select: { status: true } } } },
},
}),
]);
return {
plan: { ...full!, canManage: true },
usedCount,
derived: derived.map((d) => {
const days = (d.weeks ?? []).flatMap((w) => w.days);
const completed = days.filter((x) => x.status === 'COMPLETED').length;
const total = days.length;
const { weeks: _weeks, user, ...rest } = d;
return {
...rest,
ownerId: user.id,
ownerName: [user.firstName, user.lastName].filter(Boolean).join(' '),
progress: {
completed,
total,
percent: total > 0 ? Math.round((completed / total) * 100) : 0,
},
};
}),
};
}
/**
* Kokpit objętości właściciela: plan vs. realizacja per partia + zalecane
* zakresy FocusArea. Ten sam rdzeń liczący co raport trenera (planVolume).
*/
export async function getPlanVolume(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanOwner(prisma, planId, userId);
assertRegularPlan(plan);
const muscles = await computePlanVolume(prisma, plan.id, plan.weeksCount);
return {
plan: {
id: plan.id,
title: plan.title,
weeksCount: plan.weeksCount,
startDate: plan.startDate,
status: plan.status,
},
muscles,
};
}
/** Plany udostępnione przeze mnie (do zakładki „Udostępnione"). */
export async function listSharedByMe(prisma: PrismaClient, userId: string) {
const shares = await prisma.planShare.findMany({
where: { sharedById: userId, plan: { kind: 'PLAN' } },
include: {
sharedWith: { select: { id: true, firstName: true, lastName: true } },
plan: {
include: {
gym: { select: { id: true, name: true } },
weeks: { select: { days: { where: { removedAt: null }, select: { status: true } } } },
},
},
},
orderBy: { createdAt: 'desc' },
});
return {
plans: shares.map((s) => {
const days = (s.plan.weeks ?? []).flatMap((w) => w.days);
const completed = days.filter((d) => d.status === 'COMPLETED').length;
const total = days.length;
const { weeks: _weeks, ...rest } = s.plan;
return {
...rest,
sharedWith: s.sharedWith,
progress: {
completed,
total,
percent: total > 0 ? Math.round((completed / total) * 100) : 0,
},
};
}),
};
}

View File

@@ -78,7 +78,7 @@ export function startScheduler(prisma: PrismaClient): void {
}
const activePlans = await prisma.trainingPlan.findMany({
where: { status: 'ACTIVE' },
where: { status: 'ACTIVE', kind: 'PLAN' },
include: { weeks: { include: { days: { where: { removedAt: null } } } } },
});
for (const plan of activePlans) {

View File

@@ -5,6 +5,13 @@ import { getKillstreak } from './killstreak.js';
import { getDashboard } from './dashboard.js';
import { getHistory } from './me.js';
import { getCalendar } from './calendar.js';
import {
aggregateActualByMuscle,
aggregatePlannedByMuscle,
buildMuscleReports,
loadFocusRanges,
type MuscleReport,
} from './planVolume.js';
export const INVITATION_TTL_DAYS = 7;
export const MAX_PENDING_INVITATIONS = 10;
@@ -60,7 +67,7 @@ export async function computeTraineeMetrics(
userId: string,
): Promise<TraineeMetrics> {
const activePlan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
where: { userId, status: 'ACTIVE', kind: 'PLAN' },
select: {
id: true,
title: true,
@@ -463,17 +470,7 @@ export async function getTraineeHistory(prisma: PrismaClient, trainerId: string,
return getHistory(prisma, userId);
}
export interface MuscleReport {
muscle: string;
planned: { sets: number; reps: number };
actual: { sets: number; reps: number };
extra: { sets: number };
missing: { sets: number };
completionPct: number;
/** Weekly FocusArea range scaled to the plan duration (null when the muscle has no range). */
recommendedRange: { setsMin: number; setsMax: number } | null;
outOfRange: boolean;
}
export type { MuscleReport };
/** Pojedyncza seria ćwiczenia w raporcie: plan vs. wykonane. */
export interface ExerciseReportSet {
@@ -526,7 +523,7 @@ export async function getTraineeReport(
): Promise<TraineeReport> {
await assertActiveTrainee(prisma, trainerId, userId);
const plan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
where: { userId, status: 'ACTIVE', kind: 'PLAN' },
select: {
id: true,
title: true,
@@ -555,12 +552,8 @@ export async function getTraineeReport(
});
if (!plan) return { plan: null, muscles: [], days: [], exercises: [] };
const focusAreas = await prisma.focusArea.findMany({
select: { muscle: true, setsMin: true, setsMax: true },
});
const rangeByMuscle = new Map(focusAreas.map((f) => [f.muscle, f]));
const rangeByMuscle = await loadFocusRanges(prisma);
const planned = new Map<string, { sets: number; reps: number }>();
// kolejność pierwszego wystąpienia ćwiczenia w planie — sortowanie szczegółów
const planExerciseOrder = new Map<string, number>();
const dayIds: string[] = [];
@@ -571,15 +564,10 @@ export async function getTraineeReport(
if (!planExerciseOrder.has(pe.exercise.id)) {
planExerciseOrder.set(pe.exercise.id, planExerciseOrder.size);
}
const acc = planned.get(pe.exercise.primaryMuscle) ?? { sets: 0, reps: 0 };
for (const s of pe.sets) {
acc.sets += 1;
if (s.reps != null) acc.reps += s.reps;
}
planned.set(pe.exercise.primaryMuscle, acc);
}
}
}
const planned = aggregatePlannedByMuscle(plan.weeks.flatMap((w) => w.days));
const sessions = await prisma.trainingSession.findMany({
where: { status: 'COMPLETED', dayId: { in: dayIds } },
@@ -608,25 +596,7 @@ export async function getTraineeReport(
},
},
});
const actual = new Map<string, { sets: number; reps: number }>();
const extra = new Map<string, number>();
for (const session of sessions) {
for (const ex of session.exercises) {
if (ex.removed || ex.hidden) continue;
const muscle = ex.exercise.primaryMuscle;
for (const st of ex.sets) {
if (st.reps == null) continue;
if (st.planSetId != null) {
const acc = actual.get(muscle) ?? { sets: 0, reps: 0 };
acc.sets += 1;
acc.reps += st.reps;
actual.set(muscle, acc);
} else {
extra.set(muscle, (extra.get(muscle) ?? 0) + 1);
}
}
}
}
const { actual, extra } = aggregateActualByMuscle(sessions);
// agregacja per ćwiczenie (plan vs. wykonane per seria) po zakończonych sesjach
const detail = new Map<string, ExerciseReport>();
@@ -679,30 +649,7 @@ export async function getTraineeReport(
return oa - ob;
});
const muscles: MuscleReport[] = [...planned.entries()].map(([muscle, p]) => {
const a = actual.get(muscle) ?? { sets: 0, reps: 0 };
const e = extra.get(muscle) ?? 0;
const missing = Math.max(0, p.sets - a.sets);
const completionPct = p.sets > 0 ? Math.min(100, Math.round((a.sets / p.sets) * 100)) : 0;
const fa = rangeByMuscle.get(muscle);
const recommendedRange =
fa && fa.setsMin != null && fa.setsMax != null
? { setsMin: fa.setsMin * plan.weeksCount, setsMax: fa.setsMax * plan.weeksCount }
: null;
const outOfRange =
recommendedRange != null &&
(a.sets < recommendedRange.setsMin || a.sets > recommendedRange.setsMax);
return {
muscle,
planned: p,
actual: a,
extra: { sets: e },
missing: { sets: missing },
completionPct,
recommendedRange,
outOfRange,
};
});
const muscles = buildMuscleReports(planned, actual, extra, rangeByMuscle, plan.weeksCount);
const days = plan.weeks
.flatMap((w) => w.days)
@@ -729,7 +676,7 @@ export async function getTraineeReport(
export async function getTraineeMoves(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
const plan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
where: { userId, status: 'ACTIVE', kind: 'PLAN' },
select: {
weeks: {
select: {

View File

@@ -349,8 +349,8 @@ export async function getUserStats(prisma: PrismaClient, userId: string, rangeDa
orderBy: { date: 'asc' },
select: { value: true, date: true },
}),
prisma.trainingPlan.count({ where: { userId, status: 'COMPLETED' } }),
prisma.trainingPlan.count({ where: { userId, status: 'ABANDONED' } }),
prisma.trainingPlan.count({ where: { userId, status: 'COMPLETED', kind: 'PLAN' } }),
prisma.trainingPlan.count({ where: { userId, status: 'ABANDONED', kind: 'PLAN' } }),
prisma.planDay.count({
where: { removedAt: null, status: 'COMPLETED', week: { plan: { userId } } },
}),

View File

@@ -1369,6 +1369,12 @@ export const openapi: Record<string, unknown> = {
properties: {
title: { type: 'string' },
weeksCount: { type: 'integer', minimum: 1, maximum: 52 },
kind: {
type: 'string',
enum: ['PLAN', 'TEMPLATE'],
description:
'TEMPLATE = reusable private template: status forced DRAFT, startDate rejected, no gym, never activatable',
},
gymId: {
type: 'string',
nullable: true,
@@ -1463,6 +1469,29 @@ export const openapi: Record<string, unknown> = {
security: [{ bearerAuth: [] }],
},
},
'/plans/shared-by-me': {
get: {
tags: ['Plans'],
summary: 'Plans the user has shared with others (with the recipients)',
security: [{ bearerAuth: [] }],
},
},
'/plans/templates': {
get: {
tags: ['Plans'],
summary:
"The user's plan templates (private library): weeks/days/exercises counters and usedCount (plans cloned from the template)",
security: [{ bearerAuth: [] }],
},
},
'/plans/templates/{id}': {
get: {
tags: ['Plans'],
summary:
'Full template structure + derived-plan usage list (only plans visible to the caller; usedCount is the total). Templates are private to their author',
security: [{ bearerAuth: [] }],
},
},
'/plans/{id}': {
get: {
tags: ['Plans'],
@@ -1598,6 +1627,52 @@ export const openapi: Record<string, unknown> = {
},
},
},
'/plans/{id}/clone': {
post: {
tags: ['Plans'],
summary:
"Clone the user's plan TEMPLATE into a new DRAFT plan (kind=PLAN, sourceTemplateId). Deep copy weeks -> days -> exercises -> sets; template days carry no dates",
description: 'Writes an ActivityLog entry: plan.template.cloned.',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
201: { description: 'Cloned, returns { plan }' },
400: { description: 'Code TEMPLATE_NOT_PLAN when the source is not a template' },
403: { description: 'The caller does not own the template' },
404: { description: 'Template not found' },
},
},
},
'/plans/{id}/as-template': {
post: {
tags: ['Plans'],
summary:
'Save a regular plan as a reusable TEMPLATE owned by the actor — plan owner OR its creator (trainer). Structure snapshot; the source plan is untouched',
description: 'Writes an ActivityLog entry: plan.template.saved.',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
201: { description: 'Template created, returns { plan }' },
400: { description: 'Code TEMPLATE_NOT_PLAN when the source is already a template' },
403: { description: 'The actor is neither the owner nor the creator' },
404: { description: 'Plan not found' },
},
},
},
'/plans/{id}/volume': {
get: {
tags: ['Plans'],
summary:
'Volume cockpit of the owner plan: planned vs. actual sets per muscle with the recommended FocusArea ranges (same core as the trainee report)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
200: { description: 'OK, returns { plan, muscles }' },
400: { description: 'Code TEMPLATE_NOT_PLAN for templates' },
404: { description: 'Plan not found or caller is not the owner' },
},
},
},
'/plans/{id}/activate': {
post: {
tags: ['Plans'],
@@ -2461,6 +2536,25 @@ export const openapi: Record<string, unknown> = {
},
},
},
'/trainer/trainees/{userId}/plans/from-template/{templateId}': {
post: {
tags: ['Trainer'],
summary:
"Clone the trainer's own template into a new DRAFT plan for the trainee (owner = trainee, creator = trainer, sourceTemplateId). Deep copy; activation stays separate; the trainee gets a PLAN_READY notification (trainer only)",
description: 'Writes an ActivityLog entry: plan.template.cloned.',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'userId', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'templateId', in: 'path', required: true, schema: { type: 'string' } },
],
responses: {
201: { description: 'Created, returns { plan }' },
400: { description: 'Code TEMPLATE_NOT_PLAN when the source is not a template' },
403: { description: 'Trainer role required / template not owned by the trainer' },
404: { description: 'Trainee or template not found' },
},
},
},
'/trainer/trainees/{userId}/report': {
get: {
tags: ['Trainer'],