diff --git a/api/prisma/migrations/20261106010507_add_plan_kind_and_source_template/migration.sql b/api/prisma/migrations/20261106010507_add_plan_kind_and_source_template/migration.sql new file mode 100644 index 0000000..769858b --- /dev/null +++ b/api/prisma/migrations/20261106010507_add_plan_kind_and_source_template/migration.sql @@ -0,0 +1,15 @@ +-- CreateEnum +CREATE TYPE "PlanKind" AS ENUM ('PLAN', 'TEMPLATE'); + +-- AlterTable +ALTER TABLE "TrainingPlan" ADD COLUMN "kind" "PlanKind" NOT NULL DEFAULT 'PLAN', +ADD COLUMN "sourceTemplateId" TEXT; + +-- CreateIndex +CREATE INDEX "TrainingPlan_userId_kind_idx" ON "TrainingPlan"("userId", "kind"); + +-- CreateIndex +CREATE INDEX "TrainingPlan_sourceTemplateId_idx" ON "TrainingPlan"("sourceTemplateId"); + +-- AddForeignKey +ALTER TABLE "TrainingPlan" ADD CONSTRAINT "TrainingPlan_sourceTemplateId_fkey" FOREIGN KEY ("sourceTemplateId") REFERENCES "TrainingPlan"("id") ON DELETE SET NULL ON UPDATE CASCADE; diff --git a/api/prisma/schema.prisma b/api/prisma/schema.prisma index 64f5acc..b6a1ad9 100644 --- a/api/prisma/schema.prisma +++ b/api/prisma/schema.prisma @@ -23,6 +23,13 @@ enum DayStatus { SKIPPED } +/// PLAN = zwykły plan; TEMPLATE = szablon (nigdy nieaktywowalny, wykluczany +/// centralnie z list/kalendarza/statystyk; dni bez dat, startDate null). +enum PlanKind { + PLAN + TEMPLATE +} + enum SessionStatus { IN_PROGRESS COMPLETED @@ -696,26 +703,34 @@ model TrainingPlan { /// unikalny `TrainingPlan_userId_active_key` ("userId") WHERE status='ACTIVE' /// — utworzony w migracji 20260904120000 (Prisma nie wspiera indeksów /// częściowych w schemacie, patrz README „Kluczowe decyzje (MVP)”). - id String @id @default(cuid()) - title String - userId String - creatorId String? - status PlanStatus @default(DRAFT) - weeksCount Int - startDate DateTime? + id String @id @default(cuid()) + title String + userId String + creatorId String? + status PlanStatus @default(DRAFT) + /// PLAN = zwykły plan; TEMPLATE = szablon (status zawsze DRAFT, dni bez dat). + kind PlanKind @default(PLAN) + /// Atrybucja klonu: plan utworzony z szablonu (snapshot — edycja szablonu nie propaguje się). + sourceTemplateId String? + weeksCount Int + startDate DateTime? /// Informacyjna — siłownia, w której realizowany jest plan (bez wpływu na scheduler). - gymId String? - createdAt DateTime @default(now()) - updatedAt DateTime @updatedAt + gymId String? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt - user User @relation(fields: [userId], references: [id], onDelete: Cascade) - creator User? @relation("PlanCreator", fields: [creatorId], references: [id], onDelete: SetNull) - gym Gym? @relation(fields: [gymId], references: [id], onDelete: SetNull) - weeks PlanWeek[] - shares PlanShare[] - edits PlanEdit[] + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + creator User? @relation("PlanCreator", fields: [creatorId], references: [id], onDelete: SetNull) + gym Gym? @relation(fields: [gymId], references: [id], onDelete: SetNull) + sourceTemplate TrainingPlan? @relation("PlanFromTemplate", fields: [sourceTemplateId], references: [id], onDelete: SetNull) + templateDerivations TrainingPlan[] @relation("PlanFromTemplate") + weeks PlanWeek[] + shares PlanShare[] + edits PlanEdit[] @@index([userId, status]) + @@index([userId, kind]) + @@index([sourceTemplateId]) @@index([gymId]) } diff --git a/api/src/routes/plans-schemas.ts b/api/src/routes/plans-schemas.ts index a8bccac..1f48065 100644 --- a/api/src/routes/plans-schemas.ts +++ b/api/src/routes/plans-schemas.ts @@ -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() diff --git a/api/src/routes/plans.ts b/api/src/routes/plans.ts index c1f9cc0..101f03c 100644 --- a/api/src/routes/plans.ts +++ b/api/src/routes/plans.ts @@ -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: diff --git a/api/src/routes/trainer.ts b/api/src/routes/trainer.ts index 7dbb034..2efb1e0 100644 --- a/api/src/routes/trainer.ts +++ b/api/src/routes/trainer.ts @@ -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}: diff --git a/api/src/services/dashboard.ts b/api/src/services/dashboard.ts index a91b42e..95b3453 100644 --- a/api/src/services/dashboard.ts +++ b/api/src/services/dashboard.ts @@ -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: { diff --git a/api/src/services/feed.ts b/api/src/services/feed.ts index b5d4c05..4a82e9f 100644 --- a/api/src/services/feed.ts +++ b/api/src/services/feed.ts @@ -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; diff --git a/api/src/services/focusChain.ts b/api/src/services/focusChain.ts index df1f981..d80c633 100644 --- a/api/src/services/focusChain.ts +++ b/api/src/services/focusChain.ts @@ -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: { diff --git a/api/src/services/planVolume.ts b/api/src/services/planVolume.ts new file mode 100644 index 0000000..2e1b4f2 --- /dev/null +++ b/api/src/services/planVolume.ts @@ -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 { + const planned = new Map(); + 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; + extra: Map; +} { + const actual = new Map(); + const extra = new Map(); + 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, + actual: Map, + extra: Map, + rangeByMuscle: Map, + 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> { + 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 { + 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 { + 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, + ); +} diff --git a/api/src/services/plans.ts b/api/src/services/plans.ts index 4f29679..c0100f8 100644 --- a/api/src/services/plans.ts +++ b/api/src/services/plans.ts @@ -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, + }, + }; + }), + }; +} diff --git a/api/src/services/scheduler.ts b/api/src/services/scheduler.ts index 568892c..fb59e5b 100644 --- a/api/src/services/scheduler.ts +++ b/api/src/services/scheduler.ts @@ -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) { diff --git a/api/src/services/trainer.ts b/api/src/services/trainer.ts index 1fb9c73..b6bfe1b 100644 --- a/api/src/services/trainer.ts +++ b/api/src/services/trainer.ts @@ -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 { 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 { 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(); // kolejność pierwszego wystąpienia ćwiczenia w planie — sortowanie szczegółów const planExerciseOrder = new Map(); 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(); - const extra = new Map(); - 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(); @@ -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: { diff --git a/api/src/services/userStats.ts b/api/src/services/userStats.ts index 0366476..9d8857c 100644 --- a/api/src/services/userStats.ts +++ b/api/src/services/userStats.ts @@ -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 } } }, }), diff --git a/api/src/swagger.ts b/api/src/swagger.ts index 2f5a786..9145f72 100644 --- a/api/src/swagger.ts +++ b/api/src/swagger.ts @@ -1369,6 +1369,12 @@ export const openapi: Record = { 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 = { 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 = { }, }, }, + '/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 = { }, }, }, + '/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'], diff --git a/api/test/integration/plans-templates.test.ts b/api/test/integration/plans-templates.test.ts new file mode 100644 index 0000000..d28eab2 --- /dev/null +++ b/api/test/integration/plans-templates.test.ts @@ -0,0 +1,629 @@ +import { describe, it, expect, beforeAll } from 'vitest'; +import { prisma } from '../../src/lib/prisma.js'; +import { + buildApp, + createExercise, + createUser, + createUserWithToken, + loginViaApi, + rand, + seedPlan, + seedSession, + PASSWORD, +} from '../helpers.js'; + +/** Poniedziałek bieżącego tygodnia 00:00 czasu lokalnego. */ +function mondayThisWeek(): Date { + const now = new Date(); + return new Date(now.getFullYear(), now.getMonth(), now.getDate() - ((now.getDay() + 6) % 7)); +} + +function localDate(daysFromMondayThisWeek: number): Date { + const d = mondayThisWeek(); + d.setDate(d.getDate() + daysFromMondayThisWeek); + return d; +} + +const daysAgo = (n: number) => localDate(-n); +const daysAhead = (n: number) => localDate(n); + +describe('plan templates (kind=TEMPLATE)', () => { + let app: ReturnType; + let owner: { id: string; token: string }; + let stranger: { id: string; token: string }; + let trainer: { id: string; token: string }; + let trainee: { id: string; token: string }; + let exerciseId: string; + let gymId: string; + + beforeAll(async () => { + app = buildApp(); + const o = await createUserWithToken({ firstName: 'Ola', lastName: 'Właściciel' }); + const s = await createUserWithToken({ firstName: 'Stefan', lastName: 'Obcy' }); + const t = await createUser({ firstName: 'Tomasz', lastName: 'Trener' }); + const tr = await createUser({ firstName: 'Anna', lastName: 'Podopieczna' }); + owner = { id: o.user.id, token: o.token }; + stranger = { id: s.user.id, token: s.token }; + const gym = await prisma.gym.create({ data: { name: `Templates Gym ${rand()}` } }); + gymId = gym.id; + await prisma.gymMembership.create({ data: { userId: t.user.id, gymId, roles: ['TRAINER'] } }); + await prisma.gymMembership.create({ data: { userId: tr.user.id, gymId, roles: ['MEMBER'] } }); + await prisma.coaching.create({ + data: { + trainerId: t.user.id, + userId: tr.user.id, + status: 'ACTIVE', + invitedBy: t.user.id, + expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), + }, + }); + trainer = { id: t.user.id, token: (await loginViaApi(t.user.email, PASSWORD)).token }; + trainee = { id: tr.user.id, token: (await loginViaApi(tr.user.email, PASSWORD)).token }; + exerciseId = (await createExercise()).id; + }); + + const templateBody = (title: string) => ({ + title, + kind: 'TEMPLATE', + weeksCount: 2, + weeks: [ + { + index: 0, + customName: 'Baza', + days: [ + { + dayOfWeek: 1, + exercises: [ + { + exerciseId, + order: 0, + sets: [ + { index: 0, reps: 10, loadKg: 60, restSec: 90, rir: 2 }, + { index: 1, reps: 8, loadKg: 62.5 }, + ], + }, + ], + }, + { dayOfWeek: 3, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 12 }] }] }, + ], + }, + { + index: 1, + days: [ + { + dayOfWeek: 2, + exercises: [ + { exerciseId, order: 0, sets: [{ index: 0, reps: 12, cardioBpm: 140, timeSec: 600, speed: 7.5 }] }, + ], + }, + ], + }, + ], + }); + + async function createTemplateViaApi(token: string, title: string) { + const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(templateBody(title)); + expect(res.status).toBe(201); + return res.body.plan as { id: string; kind: string; status: string }; + } + + describe('creation', () => { + it('creates a TEMPLATE (status DRAFT, no start date) with kind returned', async () => { + const tpl = await createTemplateViaApi(owner.token, `Szablon ${rand()}`); + expect(tpl.kind).toBe('TEMPLATE'); + expect(tpl.status).toBe('DRAFT'); + }); + + it('rejects startDate for templates with 400', async () => { + const body = { ...templateBody(`Szablon start ${rand()}`), startDate: '2030-01-07' }; + const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${owner.token}`).send(body); + expect(res.status).toBe(400); + }); + + it('excludes templates from GET /plans', async () => { + const tpl = await createTemplateViaApi(owner.token, `Szablon listy ${rand()}`); + const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${owner.token}`); + expect(res.status).toBe(200); + expect(res.body.plans.some((p: { id: string }) => p.id === tpl.id)).toBe(false); + }); + + it('lists templates in GET /plans/templates with counters and usedCount', async () => { + const title = `Szablon licznik ${rand()}`; + const tpl = await createTemplateViaApi(owner.token, title); + const res = await app.get('/api/v1/plans/templates').set('Authorization', `Bearer ${owner.token}`); + expect(res.status).toBe(200); + const row = res.body.templates.find((t: { id: string }) => t.id === tpl.id); + expect(row).toMatchObject({ title, weeksCount: 2, daysCount: 3, exercisesCount: 3, usedCount: 0 }); + }); + + it('templates library is private to the author', async () => { + const tpl = await createTemplateViaApi(owner.token, `Szablon prywatny ${rand()}`); + const res = await app.get('/api/v1/plans/templates').set('Authorization', `Bearer ${stranger.token}`); + expect(res.status).toBe(200); + expect(res.body.templates.some((t: { id: string }) => t.id === tpl.id)).toBe(false); + const detail = await app.get(`/api/v1/plans/templates/${tpl.id}`).set('Authorization', `Bearer ${stranger.token}`); + expect(detail.status).toBe(404); + }); + + it('hides templates behind GET /plans/:id for non-authors (even the trainee trainer)', async () => { + const tpl = await createTemplateViaApi(trainee.token, `Szablon podopiecznej ${rand()}`); + const asTrainer = await app + .get(`/api/v1/plans/${tpl.id}`) + .set('Authorization', `Bearer ${trainer.token}`); + expect(asTrainer.status).toBe(404); + const asStranger = await app.get(`/api/v1/plans/${tpl.id}`).set('Authorization', `Bearer ${stranger.token}`); + expect(asStranger.status).toBe(404); + }); + + it('replaces the full template structure on PATCH without startDate/gym', async () => { + const tpl = await createTemplateViaApi(owner.token, `Szablon edycja ${rand()}`); + const edited = templateBody(`Szablon edycja v2 ${rand()}`); + edited.weeks[1].days = []; + const res = await app + .patch(`/api/v1/plans/${tpl.id}`) + .set('Authorization', `Bearer ${owner.token}`) + .send({ ...edited, title: edited.title }); + expect(res.status).toBe(200); + const detail = await app.get(`/api/v1/plans/${tpl.id}`).set('Authorization', `Bearer ${owner.token}`); + expect(detail.status).toBe(200); + expect(detail.body.plan.title).toBe(edited.title); + expect(detail.body.plan.weeks[1].days).toHaveLength(0); + const withStart = await app + .patch(`/api/v1/plans/${tpl.id}`) + .set('Authorization', `Bearer ${owner.token}`) + .send({ ...edited, startDate: '2030-01-07' }); + expect(withStart.status).toBe(400); + }); + }); + + describe('lifecycle guards (TEMPLATE_NOT_PLAN)', () => { + let tplId: string; + beforeAll(async () => { + tplId = (await createTemplateViaApi(owner.token, `Szablon blokady ${rand()}`)).id; + }); + + const blocked = (path: string, send?: unknown) => + app.post(`/api/v1/plans/${tplId}/${path}`).set('Authorization', `Bearer ${owner.token}`).send(send ?? {}); + + it('blocks activate with code TEMPLATE_NOT_PLAN', async () => { + const res = await blocked('activate', { startDate: '2030-01-07' }); + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('TEMPLATE_NOT_PLAN'); + }); + + it('blocks abandon/complete/suspend', async () => { + for (const action of ['abandon', 'complete', 'suspend']) { + const res = await blocked(action); + expect(res.status, action).toBe(400); + expect(res.body.error.code, action).toBe('TEMPLATE_NOT_PLAN'); + } + }); + + it('blocks share of a template', async () => { + const res = await blocked('share', { userId: trainee.id }); + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('TEMPLATE_NOT_PLAN'); + }); + + it('GET /plans/:id/volume rejects templates', async () => { + const res = await app.get(`/api/v1/plans/${tplId}/volume`).set('Authorization', `Bearer ${owner.token}`); + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('TEMPLATE_NOT_PLAN'); + }); + }); + + describe('clone (use template for myself)', () => { + it('clones 1:1 into a new DRAFT plan with sourceTemplateId and bumps usedCount', async () => { + const tpl = await createTemplateViaApi(owner.token, `Szablon klon ${rand()}`); + const res = await app.post(`/api/v1/plans/${tpl.id}/clone`).set('Authorization', `Bearer ${owner.token}`); + expect(res.status).toBe(201); + expect(res.body.plan).toMatchObject({ kind: 'PLAN', status: 'DRAFT', sourceTemplateId: tpl.id }); + + const detail = await app.get(`/api/v1/plans/${res.body.plan.id}`).set('Authorization', `Bearer ${owner.token}`); + expect(detail.status).toBe(200); + const src = await app.get(`/api/v1/plans/templates/${tpl.id}`).set('Authorization', `Bearer ${owner.token}`); + const srcWeeks = src.body.plan.weeks; + const cloneWeeks = detail.body.plan.weeks; + expect(cloneWeeks.map((w: { index: number; customName: string | null }) => [w.index, w.customName])) + .toEqual(srcWeeks.map((w: { index: number; customName: string | null }) => [w.index, w.customName])); + const flattenDays = (weeks: { days: { dayOfWeek: number; date: string | null; exercises: unknown[] }[] }[]) => + weeks.flatMap((w) => w.days.map((d) => ({ dayOfWeek: d.dayOfWeek, date: d.date, n: d.exercises.length }))); + expect(flattenDays(cloneWeeks)).toEqual( + flattenDays(srcWeeks).map((d) => ({ ...d, date: null })), + ); + const cloneSet = cloneWeeks[0].days[0].exercises[0].sets[0]; + expect(cloneSet).toMatchObject({ reps: 10, loadKg: 60, restSec: 90, rir: 2 }); + const cardioSet = cloneWeeks[1].days[0].exercises[0].sets[0]; + expect(cardioSet).toMatchObject({ cardioBpm: 140, timeSec: 600, speed: 7.5 }); + + const tplRes = await app.get('/api/v1/plans/templates').set('Authorization', `Bearer ${owner.token}`); + expect(tplRes.body.templates.find((t: { id: string }) => t.id === tpl.id).usedCount).toBe(1); + }); + + it('rejects cloning a non-template with TEMPLATE_NOT_PLAN', async () => { + const planRes = await app + .post('/api/v1/plans') + .set('Authorization', `Bearer ${owner.token}`) + .send({ title: `Zwykly ${rand()}`, weeksCount: 1, weeks: [{ index: 0, days: [{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 5 }] }] }] }] }); + const res = await app.post(`/api/v1/plans/${planRes.body.plan.id}/clone`).set('Authorization', `Bearer ${owner.token}`); + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('TEMPLATE_NOT_PLAN'); + }); + + it('rejects cloning another user template with 403 and missing with 404', async () => { + const tpl = await createTemplateViaApi(owner.token, `Szablon obcy ${rand()}`); + const res = await app.post(`/api/v1/plans/${tpl.id}/clone`).set('Authorization', `Bearer ${stranger.token}`); + expect(res.status).toBe(403); + const missing = await app.post('/api/v1/plans/no-such-template/clone').set('Authorization', `Bearer ${stranger.token}`); + expect(missing.status).toBe(404); + }); + }); + + describe('save plan as template (owner or creator)', () => { + it('owner saves own plan as template', async () => { + const planRes = await app + .post('/api/v1/plans') + .set('Authorization', `Bearer ${trainee.token}`) + .send({ title: `Plan Oli ${rand()}`, weeksCount: 1, weeks: [{ index: 0, days: [{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 5 }] }] }] }] }); + const res = await app + .post(`/api/v1/plans/${planRes.body.plan.id}/as-template`) + .set('Authorization', `Bearer ${trainee.token}`); + expect(res.status).toBe(201); + expect(res.body.plan.kind).toBe('TEMPLATE'); + }); + + it('trainer (creator) saves their trainee plan into their own library', async () => { + const created = await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans`) + .set('Authorization', `Bearer ${trainer.token}`) + .send({ title: `Plan trenera ${rand()}`, weeksCount: 1, weeks: [{ index: 0, days: [{ dayOfWeek: 2, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 6 }] }] }] }] }); + expect(created.status).toBe(201); + const res = await app + .post(`/api/v1/plans/${created.body.plan.id}/as-template`) + .set('Authorization', `Bearer ${trainer.token}`); + expect(res.status).toBe(201); + const tpl = res.body.plan; + const lib = await app.get('/api/v1/plans/templates').set('Authorization', `Bearer ${trainer.token}`); + expect(lib.body.templates.some((t: { id: string }) => t.id === tpl.id)).toBe(true); + // szablon należy do trenera, nie do podopiecznej + const traineeLib = await app.get('/api/v1/plans/templates').set('Authorization', `Bearer ${trainee.token}`); + expect(traineeLib.body.templates.some((t: { id: string }) => t.id === tpl.id)).toBe(false); + }); + + it('rejects a stranger with 403 and a template source with TEMPLATE_NOT_PLAN', async () => { + const planRes = await app + .post('/api/v1/plans') + .set('Authorization', `Bearer ${owner.token}`) + .send({ title: `Plan blokady ${rand()}`, weeksCount: 1, weeks: [{ index: 0, days: [{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 5 }] }] }] }] }); + const forbiddenRes = await app + .post(`/api/v1/plans/${planRes.body.plan.id}/as-template`) + .set('Authorization', `Bearer ${stranger.token}`); + expect(forbiddenRes.status).toBe(403); + const tpl = await createTemplateViaApi(owner.token, `Szablon ponowny ${rand()}`); + const again = await app + .post(`/api/v1/plans/${tpl.id}/as-template`) + .set('Authorization', `Bearer ${owner.token}`); + expect(again.status).toBe(400); + expect(again.body.error.code).toBe('TEMPLATE_NOT_PLAN'); + }); + }); + + describe('from-template for trainee (trainer flow)', () => { + it('clones the trainer template as a trainee-owned DRAFT plan with notification', async () => { + const tplRes = await app + .post('/api/v1/plans') + .set('Authorization', `Bearer ${trainer.token}`) + .send(templateBody(`Szablon trenera ${rand()}`)); + const tplId = tplRes.body.plan.id; + const res = await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans/from-template/${tplId}`) + .set('Authorization', `Bearer ${trainer.token}`); + expect(res.status).toBe(201); + const planId = res.body.plan.id; + const row = await prisma.trainingPlan.findUnique({ where: { id: planId } }); + expect(row).toMatchObject({ userId: trainee.id, creatorId: trainer.id, kind: 'PLAN', status: 'DRAFT', sourceTemplateId: tplId }); + const notif = await prisma.notification.findFirst({ + where: { + userId: trainee.id, + type: 'PLAN_READY', + payload: { path: ['planId'], equals: planId }, + }, + }); + expect(notif).toBeTruthy(); + const traineeList = await app.get('/api/v1/plans').set('Authorization', `Bearer ${trainee.token}`); + expect(traineeList.body.plans.some((p: { id: string }) => p.id === planId)).toBe(true); + }); + + it('rejects templates not owned by the trainer with 403', async () => { + const tpl = await createTemplateViaApi(owner.token, `Szablon nie mój ${rand()}`); + const res = await app + .post(`/api/v1/trainer/trainees/${trainee.id}/plans/from-template/${tpl.id}`) + .set('Authorization', `Bearer ${trainer.token}`); + expect(res.status).toBe(403); + }); + + it('excludes templates from the trainee plan list (trainer route)', async () => { + const tpl = await seedTemplateDirect(trainee.id, `Szablon seed ${rand()}`); + const res = await app + .get(`/api/v1/trainer/trainees/${trainee.id}/plans`) + .set('Authorization', `Bearer ${trainer.token}`); + expect(res.status).toBe(200); + expect(res.body.plans.some((p: { id: string }) => p.id === tpl.id)).toBe(false); + }); + }); + + describe('template usage list (derived visibility)', () => { + it('shows only own and active-trainee derivations; usedCount is the total', async () => { + const tpl = await seedTemplateDirect(trainer.id, `Szablon uzycia ${rand()}`); + // własne pochodne + const ownDerived = await seedDerivedPlan(trainer.id, tpl.id); + // podopieczny w ACTIVE coaching + const traineeDerived = await seedDerivedPlan(trainee.id, tpl.id); + // obcy — widoczność zablokowana, licznik pełny + const strangerDerived = await seedDerivedPlan(stranger.id, tpl.id); + + const res = await app + .get(`/api/v1/plans/templates/${tpl.id}`) + .set('Authorization', `Bearer ${trainer.token}`); + expect(res.status).toBe(200); + expect(res.body.usedCount).toBe(3); + const ids = res.body.derived.map((d: { id: string }) => d.id); + expect(ids).toContain(ownDerived.id); + expect(ids).toContain(traineeDerived.id); + expect(ids).not.toContain(strangerDerived.id); + const traineeRow = res.body.derived.find((d: { id: string }) => d.id === traineeDerived.id); + expect(traineeRow).toMatchObject({ ownerId: trainee.id, status: 'DRAFT' }); + expect(traineeRow.ownerName).toContain('Anna'); + // struktura szablonu zwracana w pełnym kształcie + expect(res.body.plan.weeks.length).toBeGreaterThan(0); + }); + }); + + describe('exclusions from stats/dashboard/shares', () => { + it('templates do not count in dashboard completed plans or user stats', async () => { + const statsUser = await createUserWithToken(); + const before = await app.get('/api/v1/me/stats').set('Authorization', `Bearer ${statsUser.token}`); + await seedPlan({ userId: statsUser.user.id, status: 'COMPLETED' }); + // szablon w stanie COMPLETED (normalnie niemożliwy — sprawdzamy filtr kind) + const tpl = await seedTemplateDirect(statsUser.user.id, `Szablon COMPLETED ${rand()}`, 'COMPLETED'); + const after = await app.get('/api/v1/me/stats').set('Authorization', `Bearer ${statsUser.token}`); + expect(after.body.plans.completed).toBe(before.body.plans.completed + 1); + const dash = await app.get('/api/v1/dashboard').set('Authorization', `Bearer ${statsUser.token}`); + expect(dash.body.history.completedPlans).toBe(1); + expect(dash.body.activePlan).toBeNull(); + await prisma.trainingPlan.delete({ where: { id: tpl.id } }); + }); + + it('share of a template (seeded legacy row) stays out of shared-with-me and shared-by-me', async () => { + const tpl = await seedTemplateDirect(owner.id, `Szablon share ${rand()}`); + await prisma.planShare.create({ data: { planId: tpl.id, sharedById: owner.id, sharedWithId: trainee.id } }); + const withMe = await app.get('/api/v1/plans/shared-with-me').set('Authorization', `Bearer ${trainee.token}`); + expect(withMe.body.plans.some((p: { id: string }) => p.id === tpl.id)).toBe(false); + const byMe = await app.get('/api/v1/plans/shared-by-me').set('Authorization', `Bearer ${owner.token}`); + expect(byMe.body.plans.some((p: { id: string }) => p.id === tpl.id)).toBe(false); + }); + + it('shared-by-me lists plans shared by the user with recipients', async () => { + const plan = await seedPlan({ userId: owner.id, title: `Plan shared ${rand()}` }); + await prisma.planShare.create({ data: { planId: plan.id, sharedById: owner.id, sharedWithId: trainee.id } }); + const res = await app.get('/api/v1/plans/shared-by-me').set('Authorization', `Bearer ${owner.token}`); + expect(res.status).toBe(200); + const row = res.body.plans.find((p: { id: string }) => p.id === plan.id); + expect(row).toBeTruthy(); + expect(row.sharedWith).toMatchObject({ id: trainee.id }); + }); + }); + + describe('GET /plans/:id/volume (shared core with trainee report)', () => { + it('returns the same per-muscle numbers as the trainer report', async () => { + // Dedykowana partia i fokus — bez kolizji z równoległymi plikami testów. + const muscle = `vol-muscle-${rand()}`; + const volExercise = await createExercise(); + await prisma.exercise.update({ where: { id: volExercise.id }, data: { primaryMuscle: muscle } }); + await prisma.focusArea.create({ + data: { name: `Focus ${rand()}`, muscle, description: null, setsMin: 8, setsMax: 20 }, + }); + const volUser = await createUser({ firstName: 'Wiktoria' }); + const volToken = (await loginViaApi(volUser.user.email, PASSWORD)).token; + const active = await seedPlan({ + userId: volUser.user.id, + status: 'ACTIVE', + startDate: mondayThisWeek(), + weeks: [ + { + index: 0, + days: [ + { + dayOfWeek: 1, + status: 'COMPLETED', + date: localDate(0), + exercises: [ + { exerciseId: volExercise.id, order: 0, sets: [{ index: 0, reps: 10 }, { index: 1, reps: 8 }, { index: 2, reps: 8 }] }, + ], + }, + ], + }, + { index: 1, days: [{ dayOfWeek: 1, status: 'PLANNED', date: localDate(7) }] }, + ], + }); + const day = active.weeks[0].days[0]; + const planEx = day.exercises[0]; + await seedSession(day.id, { + status: 'COMPLETED', + exercises: [ + { + exerciseId: volExercise.id, + planExerciseId: planEx.id, + order: 0, + sets: [ + { planSetId: planEx.sets[0].id, reps: 10 }, + { planSetId: planEx.sets[1].id, reps: 8 }, + { planSetId: null, reps: 6 }, + ], + }, + ], + }); + // wykonanie części planu + seria ponad plan — porównanie obu tras + await prisma.coaching.create({ + data: { + trainerId: trainer.id, + userId: volUser.user.id, + status: 'ACTIVE', + invitedBy: trainer.id, + expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), + }, + }); + const report = await app + .get(`/api/v1/trainer/trainees/${volUser.user.id}/report`) + .set('Authorization', `Bearer ${trainer.token}`); + expect(report.status).toBe(200); + const volume = await app + .get(`/api/v1/plans/${active.id}/volume`) + .set('Authorization', `Bearer ${volToken}`); + expect(volume.status).toBe(200); + expect(volume.body.plan).toMatchObject({ id: active.id }); + expect(volume.body.muscles).toEqual(report.body.muscles); + const chest = volume.body.muscles.find((m: { muscle: string }) => m.muscle === muscle); + expect(chest.planned.sets).toBe(3); + expect(chest.actual.sets).toBe(2); + expect(chest.extra.sets).toBe(1); + // zakres tygodniowy przeskalowany do 2 tygodni planu + expect(chest.recommendedRange).toEqual({ setsMin: 16, setsMax: 40 }); + }); + + it('volume is owner-only', async () => { + const plan = await seedPlan({ userId: owner.id, title: `Plan volume ${rand()}` }); + const res = await app.get(`/api/v1/plans/${plan.id}/volume`).set('Authorization', `Bearer ${stranger.token}`); + expect(res.status).toBe(404); + }); + }); + + describe('listPlans hero fields (currentWeek / nextDay)', () => { + it('nextDay = first PLANNED day today or later; currentWeek = nearest unresolved dated day', async () => { + const heroUser = await createUserWithToken(); + const today = new Date(); + today.setHours(0, 0, 0, 0); + const at = (offsetDays: number) => { + const d = new Date(today); + d.setDate(d.getDate() + offsetDays); + return d; + }; + await seedPlan({ + userId: heroUser.user.id, + status: 'ACTIVE', + startDate: at(-2), + weeks: [ + { + index: 0, + days: [ + { dayOfWeek: 1, status: 'COMPLETED', date: at(-2) }, + { dayOfWeek: 3, status: 'PLANNED', date: at(1), exercises: [{ exerciseId, order: 0 }] }, + ], + }, + { + index: 1, + days: [{ dayOfWeek: 1, status: 'PLANNED', date: at(8), exercises: [{ exerciseId, order: 0 }, { exerciseId, order: 1 }] }], + }, + ], + }); + const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${heroUser.token}`); + const plan = res.body.plans[0]; + expect(plan.currentWeek).toBe(0); + expect(plan.nextDay).toBeTruthy(); + expect(new Date(plan.nextDay.date).getTime()).toBe(at(1).getTime()); + expect(plan.nextDay.dayOfWeek).toBe(3); + expect(plan.nextDay.exerciseCount).toBe(1); + }); + + it('PLANNED today counts as nextDay', async () => { + const todayUser = await createUserWithToken(); + const today = new Date(); + today.setHours(0, 0, 0, 0); + await seedPlan({ + userId: todayUser.user.id, + status: 'ACTIVE', + startDate: today, + weeks: [{ index: 0, days: [{ dayOfWeek: 1, status: 'PLANNED', date: today }] }], + }); + const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${todayUser.token}`); + const plan = res.body.plans[0]; + expect(plan.currentWeek).toBe(0); + expect(new Date(plan.nextDay.date).getTime()).toBe(today.getTime()); + }); + + it('all days resolved -> currentWeek null, nextDay null', async () => { + const doneUser = await createUserWithToken(); + await seedPlan({ + userId: doneUser.user.id, + status: 'ACTIVE', + startDate: daysAgo(21), + weeks: [ + { + index: 0, + days: [ + { dayOfWeek: 1, status: 'COMPLETED', date: daysAgo(21) }, + { dayOfWeek: 3, status: 'SKIPPED', date: daysAgo(19) }, + ], + }, + ], + }); + const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${doneUser.token}`); + expect(res.body.plans[0]).toMatchObject({ currentWeek: null, nextDay: null }); + }); + + it('draft without dated days -> null/null', async () => { + const draftUser = await createUserWithToken(); + await seedPlan({ userId: draftUser.user.id, weeks: [{ index: 0, days: [{ dayOfWeek: 1 }] }] }); + const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${draftUser.token}`); + expect(res.body.plans[0]).toMatchObject({ currentWeek: null, nextDay: null }); + }); + }); +}); + +async function seedTemplateDirect(userId: string, title: string, status?: 'DRAFT' | 'COMPLETED') { + const exercise = await createExercise(); + return prisma.trainingPlan.create({ + data: { + title, + userId, + creatorId: userId, + status: status ?? 'DRAFT', + kind: 'TEMPLATE', + weeksCount: 1, + weeks: { + create: [ + { + index: 0, + days: { + create: [ + { + dayOfWeek: 1, + exercises: { + create: [ + { exerciseId: exercise.id, order: 0, sets: { create: [{ index: 0, reps: 8 }] } }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + }); +} + +async function seedDerivedPlan(userId: string, templateId: string) { + return prisma.trainingPlan.create({ + data: { + title: `Pochodna ${rand()}`, + userId, + creatorId: userId, + status: 'DRAFT', + kind: 'PLAN', + sourceTemplateId: templateId, + weeksCount: 1, + weeks: { create: [{ index: 0, days: { create: [{ dayOfWeek: 1 }] } }] }, + }, + }); +} diff --git a/api/test/unit/services-plans.test.ts b/api/test/unit/services-plans.test.ts index f67c271..628d47b 100644 --- a/api/test/unit/services-plans.test.ts +++ b/api/test/unit/services-plans.test.ts @@ -976,16 +976,36 @@ describe('listPlans', () => { ]); const result = await listPlans(prisma, 'u1'); expect(prisma.trainingPlan.findMany).toHaveBeenCalledWith({ - where: { userId: 'u1' }, + where: { userId: 'u1', 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 } }, + }, + }, + }, + }, }, }); expect(result).toEqual({ - plans: [{ id: 'p1', progress: { completed: 1, total: 2, percent: 50 } }], + plans: [ + { + id: 'p1', + progress: { completed: 1, total: 2, percent: 50 }, + currentWeek: null, + nextDay: null, + }, + ], }); }); }); diff --git a/app/src/App.tsx b/app/src/App.tsx index c72ec33..cf86ef6 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -8,7 +8,11 @@ import TvShell from './components/TvShell'; import Login from './pages/Login'; import Register from './pages/Register'; import Dashboard from './pages/Dashboard'; -import Plans from './pages/plans/Plans'; +import PlansHub from './pages/plans/PlansHub'; +import PlansActive from './pages/plans/PlansActive'; +import PlansArchive from './pages/plans/PlansArchive'; +import PlansShared from './pages/plans/PlansShared'; +import PlanTemplates from './pages/plans/PlanTemplates'; import PlanEditor from './pages/plans/PlanEditor'; import PlanDetail from './pages/plans/PlanDetail'; import Calendar from './pages/Calendar'; @@ -69,7 +73,14 @@ export default function App() { : } /> : }> } /> - } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> + } /> } /> } /> } /> diff --git a/app/src/api/queries.ts b/app/src/api/queries.ts index 2da5307..ed4a2b4 100644 --- a/app/src/api/queries.ts +++ b/app/src/api/queries.ts @@ -27,11 +27,15 @@ import type { GymRole, Message, Plan, + PlanTemplateDetailResponse, + PlanTemplateListItem, + PlanVolume, Exercise, PresenceSource, PresenceStats, PresenceVisit, Session, + SharedByMePlan, User, GymMembership, WeightPoint, @@ -625,6 +629,40 @@ export function useSharedWithMe() { }); } +/** Plany udostępnione przeze mnie (właściciel) wraz z odbiorcami. */ +export function useSharedByMe() { + return useQuery({ + queryKey: ['plans', 'shared-by-me'], + queryFn: () => api<{ plans: SharedByMePlan[] }>('/plans/shared-by-me'), + }); +} + +/** Biblioteka szablonów zalogowanego (kind=TEMPLATE, prywatne). */ +export function usePlanTemplates() { + return useQuery({ + queryKey: ['plans', 'templates'], + queryFn: () => api<{ templates: PlanTemplateListItem[] }>('/plans/templates'), + }); +} + +/** Detal szablonu: pełna struktura + pełna liczba użyć + lista planów z atrybucją. */ +export function usePlanTemplate(id: string) { + return useQuery({ + queryKey: ['plans', 'templates', id], + queryFn: () => api(`/plans/templates/${id}`), + enabled: !!id, + }); +} + +/** Kokpit objętości planu: planowane vs zrealizowane w seriach (partie priorytetów). */ +export function usePlanVolume(id: string, enabled = true) { + return useQuery({ + queryKey: ['plans', id, 'volume'], + queryFn: () => api(`/plans/${id}/volume`), + enabled: !!id && enabled, + }); +} + /** Moi trenerzy (ACTIVE coachings, gdzie ja jestem podopiecznym). */ export function useMyTrainers() { return useQuery({ @@ -692,6 +730,8 @@ export interface PlanWeekInput { export interface PlanBody { title: string; weeksCount: number; + /** PLAN = zwykły plan; TEMPLATE = szablon. Domyślnie PLAN. */ + kind?: 'PLAN' | 'TEMPLATE'; /** Informacyjna — siłownia planu; null/brak = bez siłowni. */ gymId?: string | null; weeks: PlanWeekInput[]; @@ -785,6 +825,22 @@ export function updatePlanGym(planId: string, gymId: string | null) { ); } +/** + * Klon szablonu (kind=TEMPLATE) do własnego szkicu planu (snapshot pełnej + * struktury, atrybucja sourceTemplateId). POST /plans/:id/clone. + */ +export function clonePlan(planId: string) { + return api<{ plan: { id: string } }>(`/plans/${planId}/clone`, { method: 'POST' }); +} + +/** + * Zapis planu jako szablon (kopia struktury, kind=TEMPLATE, autor = sprawca). + * POST /plans/:id/as-template. + */ +export function savePlanAsTemplate(planId: string) { + return api<{ plan: { id: string } }>(`/plans/${planId}/as-template`, { method: 'POST' }); +} + // ---------- sessions ---------- export function useSession(id: string) { return useQuery({ @@ -868,11 +924,12 @@ export function useIsTrainer() { return (data?.memberships ?? []).some((m) => m.roles.includes('TRAINER')); } -export function useTrainees(gymId?: string) { +export function useTrainees(gymId?: string, enabled = true) { return useQuery({ queryKey: ['trainees', gymId ?? 'all'], queryFn: () => api<{ trainees: Trainee[] }>(`/trainer/trainees${gymId ? `?gymId=${gymId}` : ''}`), + enabled, }); } @@ -1087,6 +1144,14 @@ export function createTraineePlan(userId: string, body: PlanBody) { }); } +/** Klon szablonu trenera do szkicu planu dla podopiecznego (właściciel = podopieczny). */ +export function createTraineePlanFromTemplate(userId: string, templateId: string) { + return api<{ plan: { id: string } }>( + `/trainer/trainees/${userId}/plans/from-template/${templateId}`, + { method: 'POST' }, + ); +} + export function updateTraineePlan(userId: string, planId: string, body: PlanBody) { return api<{ ok: boolean }>(`/trainer/trainees/${userId}/plans/${planId}`, { method: 'PATCH', diff --git a/app/src/api/types.ts b/app/src/api/types.ts index 07b9cf0..80bbd50 100644 --- a/app/src/api/types.ts +++ b/app/src/api/types.ts @@ -43,6 +43,9 @@ export interface FocusArea { nameEn?: string | null; muscle: string; description: string | null; + /** Zalecana tygodniowa objętość w seriach (decyzja 13); null = brak zakresu. */ + setsMin: number | null; + setsMax: number | null; createdAt: string; updatedAt: string; } @@ -524,6 +527,10 @@ export interface Plan { userId: string; title: string; status: 'DRAFT' | 'ACTIVE' | 'SUSPENDED' | 'COMPLETED' | 'ABANDONED'; + /** PLAN = zwykły plan; TEMPLATE = szablon (prywatny, nigdy nieaktywowalny). */ + kind?: 'PLAN' | 'TEMPLATE'; + /** Atrybucja klonu: id szablonu, z którego utworzono plan; null = bez szablonu. */ + sourceTemplateId?: string | null; weeksCount: number; startDate: string | null; /** Informacyjna — siłownia, w której realizowany jest plan; null = bez siłowni. */ @@ -541,11 +548,56 @@ export interface Plan { canManage?: boolean; /** Podsumowanie postępu (lista planów); brak = dane niedostępne. */ progress?: { completed: number; total: number; percent: number }; + /** Hero listy: indeks tygodnia najbliższego nierozstrzygniętego dnia z datą (lista). */ + currentWeek?: number | null; + /** Hero listy: pierwszy dzień PLANNED z datą od dziś w górę (lista). */ + nextDay?: { date: string; dayOfWeek: number; exerciseCount: number } | null; /** Historia edycji aktywnego planu (detal, newest first); brak = plan nieaktywny. */ edits?: PlanEdit[]; weeks: PlanWeek[]; } +/** Wiersz biblioteki szablonów (GET /plans/templates). */ +export interface PlanTemplateListItem { + id: string; + title: string; + weeksCount: number; + daysCount: number; + exercisesCount: number; + /** Liczba planów utworzonych z tego szablonu (pełna, bezwzględna). */ + usedCount: number; + createdAt: string; + updatedAt: string; +} + +/** Plan utworzony z szablonu, widoczny sprawcy (sekcja „Użycia" w detalu szablonu). */ +export interface PlanTemplateDerived { + id: string; + title: string; + status: Plan['status']; + ownerId: string; + ownerName: string; + progress: { completed: number; total: number; percent: number }; +} + +/** Odpowiedź GET /plans/templates/:id — pełna struktura + lista użyć. */ +export interface PlanTemplateDetailResponse { + plan: Plan; + usedCount: number; + derived: PlanTemplateDerived[]; +} + +/** Kokpit objętości planu (GET /plans/:id/volume) — te same partie co w raporcie trenera. */ +export interface PlanVolume { + plan: { id: string; title: string; weeksCount: number; startDate: string | null; status: string }; + muscles: MuscleReport[]; +} + +/** Plan udostępniony przeze mnie (GET /plans/shared-by-me) — plan + odbiorca. */ +export interface SharedByMePlan extends Plan { + sharedWith: { id: string; firstName: string | null; lastName: string | null }; +} + export interface SessionSet { id: string; planSetId: string | null; diff --git a/app/src/components/plans/ActivePlanHero.tsx b/app/src/components/plans/ActivePlanHero.tsx new file mode 100644 index 0000000..2ca259e --- /dev/null +++ b/app/src/components/plans/ActivePlanHero.tsx @@ -0,0 +1,101 @@ +import { Link } from 'react-router-dom'; +import { useTranslation } from 'react-i18next'; +import { CalendarDays, ChevronRight, Layers, MapPin } from 'lucide-react'; +import { PLAN_STATUS } from '../../lib/labels'; +import { dayName, fmtDate } from '../../lib/format'; +import { Badge } from '../ui'; +import type { Plan } from '../../api/types'; + +/** Dziś w lokalnej dacie jako YYYY-MM-DD (porównanie z `nextDay.date`). */ +function todayIso(): string { + const d = new Date(); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String( + d.getDate(), + ).padStart(2, '0')}`; +} + +/** + * Hero zakładki „Aktualne”: wyeksponowana karta jedynego aktywnego planu — + * postęp dni, „Tydzień X z Y”, następny trening, siłownia i autor. + * Klik całej karty → szczegóły planu. Bez killstreaka i bez CTA startu dnia. + */ +export function ActivePlanHero({ + plan, + creatorLabel, +}: { + plan: Plan; + creatorLabel: string | null; +}) { + const { t } = useTranslation('plans'); + const st = PLAN_STATUS.ACTIVE; + const progress = plan.progress; + const percent = progress?.percent ?? 0; + const next = plan.nextDay ?? null; + const nextIsToday = next != null && next.date.slice(0, 10) === todayIso(); + return ( + +