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

@@ -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;

View File

@@ -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])
}

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'],

View File

@@ -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<typeof buildApp>;
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 }] } }] },
},
});
}

View File

@@ -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,
},
],
});
});
});

View File

@@ -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() {
<Route path="/register" element={user ? <Navigate to="/" replace /> : <Register />} />
<Route element={user ? <Layout /> : <Navigate to="/login" replace />}>
<Route path="/" element={<Dashboard />} />
<Route path="/plans" element={<Plans />} />
<Route path="/plans" element={<PlansHub />} />
<Route path="/plans/current" element={<PlansActive />} />
<Route path="/plans/archive" element={<PlansArchive />} />
<Route path="/plans/shared" element={<PlansShared />} />
<Route path="/plans/templates" element={<PlanTemplates />} />
<Route path="/plans/templates/new" element={<PlanEditor templateMode />} />
<Route path="/plans/templates/:id/edit" element={<PlanEditor templateMode />} />
<Route path="/plans/templates/:id" element={<PlanDetail templateMode />} />
<Route path="/plans/new" element={<PlanEditor />} />
<Route path="/plans/:id/edit" element={<PlanEditor />} />
<Route path="/plans/:id" element={<PlanDetail />} />

View File

@@ -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<PlanTemplateDetailResponse>(`/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<PlanVolume>(`/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',

View File

@@ -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;

View File

@@ -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 (
<Link
to={`/plans/${plan.id}`}
className="group relative mb-5 flex flex-col gap-4 overflow-hidden rounded-2xl border border-line bg-(image:--card-grad) p-5 pl-6 shadow-card transition-all duration-150 hover:border-accent/55 md:flex-row md:items-center md:gap-6"
>
<span
aria-hidden="true"
className="absolute inset-y-0 left-0 w-[3px] bg-(image:--nav-bar-grad)"
/>
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2.5 gap-y-1">
<span className="min-w-0 truncate font-display text-xl font-bold transition-colors group-hover:text-accent-text">
{plan.title}
</span>
<Badge color={st.color}>{t(`common:${st.labelKey}`)}</Badge>
{plan.currentWeek != null && (
<span className="text-dim text-[0.875rem]">
{t('hero.weekOf', { current: plan.currentWeek, total: plan.weeksCount })}
</span>
)}
</div>
{progress && progress.total > 0 && (
<div className="mt-3 flex items-center gap-2.5">
<div className="h-2 flex-1 overflow-hidden rounded-full bg-input">
<div
className="h-full rounded-full bg-(image:--progress-grad) transition-[width] duration-300"
style={{ width: `${percent}%` }}
/>
</div>
<span className="font-display text-[0.9rem] font-bold tabular-nums text-dim">
{t('hero.daysProgress', { done: progress.completed, total: progress.total })}
</span>
</div>
)}
<div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-dim text-[0.875rem]">
{next && (
<span className="inline-flex flex-wrap items-center gap-x-1.5">
<CalendarDays className="w-4 h-4" aria-hidden="true" />
<span>{t('hero.nextPrefix')}</span>
<strong className="font-semibold text-ink">
{dayName(next.dayOfWeek)}
{nextIsToday ? ` · ${t('hero.today')}` : ` · ${fmtDate(next.date)}`}
</strong>
<span>{t('hero.exercisesCount', { count: next.exerciseCount })}</span>
</span>
)}
{plan.gym && (
<span className="inline-flex items-center gap-1.5">
<MapPin className="w-4 h-4" aria-hidden="true" />
{plan.gym.name}
</span>
)}
{creatorLabel && (
<span className="inline-flex items-center gap-1.5">
<Layers className="w-4 h-4" aria-hidden="true" />
{t('card.createdPrefix')}: {creatorLabel}
</span>
)}
</div>
</div>
<div className="flex shrink-0 items-center gap-1 text-[0.875rem] font-semibold text-dim transition-all group-hover:gap-2 group-hover:text-accent-text">
{t('card.open')}
<ChevronRight className="w-4 h-4" />
</div>
</Link>
);
}

View File

@@ -0,0 +1,77 @@
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { FileStack, Layers } from 'lucide-react';
import { Modal, Skeleton } from '../ui';
import type { PlanTemplateListItem } from '../../api/types';
/**
* Menu „Nowy plan”: od zera albo z szablonu (wybór szablonu → kopia DRAFT
* z atrybucją). Akcja wywoływana z Topbaru zakładki „Aktualne”.
*/
export function NewPlanMenu({
open,
onClose,
onFromScratch,
onUseTemplate,
cloning,
templates,
templatesLoading,
}: {
open: boolean;
onClose: () => void;
onFromScratch: () => void;
onUseTemplate: (templateId: string) => void;
cloning: boolean;
templates: PlanTemplateListItem[];
templatesLoading: boolean;
}) {
const { t } = useTranslation('plans');
return (
<Modal open={open} onClose={onClose} title={t('newMenu.title')} handle>
<p className="mb-3 text-dim text-[0.875rem]">{t('newMenu.intro')}</p>
<button
type="button"
onClick={onFromScratch}
className="flex w-full cursor-pointer items-center gap-2.5 rounded-[10px] border border-line px-3 py-3 text-left font-semibold transition-colors hover:border-accent/55 hover:bg-line/30"
>
<Layers className="h-4 w-4 shrink-0 text-dim" aria-hidden="true" />
{t('newMenu.fromScratch')}
</button>
<h4 className="mt-4 mb-1.5 text-[0.75rem] font-semibold text-dim">
{t('newMenu.fromTemplate')}
</h4>
{templatesLoading && <Skeleton className="h-10" />}
{!templatesLoading && templates.length === 0 && (
<p className="text-dim text-[0.875rem]">
{t('newMenu.noTemplates')}{' '}
<Link to="/plans/templates" className="text-accent-text underline">
{t('newMenu.templatesLink')}
</Link>
</p>
)}
{!templatesLoading && templates.length > 0 && (
<div className="flex flex-col gap-1">
{templates.map((tm) => (
<button
key={tm.id}
type="button"
disabled={cloning}
aria-label={t('newMenu.useTemplateAria', { title: tm.title })}
onClick={() => onUseTemplate(tm.id)}
className="flex cursor-pointer items-center justify-between gap-3 rounded-[10px] px-3 py-2.5 text-left text-[0.95rem] font-semibold transition-colors hover:bg-line/30 disabled:opacity-50"
>
<span className="inline-flex min-w-0 items-center gap-2">
<FileStack className="h-4 w-4 shrink-0 text-dim" aria-hidden="true" />
<span className="min-w-0 truncate">{tm.title}</span>
</span>
<span className="shrink-0 text-dim text-[0.8rem]">
{t('templates.weeksShort', { count: tm.weeksCount })} ·{' '}
{t('templates.daysShort', { count: tm.daysCount })}
</span>
</button>
))}
</div>
)}
</Modal>
);
}

View File

@@ -2,7 +2,7 @@ import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { CalendarDays, ChevronRight } from 'lucide-react';
import { fmtDate } from '../../lib/format';
import { MetaItem } from '../ui';
import { Badge, MetaItem } from '../ui';
import type { Plan } from '../../api/types';
/* Kolor krawędzi statusu na karcie planu. */
@@ -58,6 +58,7 @@ export function PlanCard({
<span className="min-w-0 truncate font-semibold transition-colors group-hover:text-accent-text">
{plan.title}
</span>
{plan.sourceTemplateId && <Badge color="gray">{t('card.fromTemplate')}</Badge>}
{creatorLabel && (
<span className="text-dim text-[0.8125rem]">
{createdPrefix}: {creatorLabel}

View File

@@ -0,0 +1,201 @@
import { useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { ArrowUpDown, Dumbbell, Filter, type LucideIcon } from 'lucide-react';
import { PLAN_STATUS } from '../../lib/labels';
import { FilterDropdown } from '../FilterDropdown';
import { PlanCard } from './PlanCard';
import { Badge, Card, EmptyState, H3 } from '../ui';
import type { Plan } from '../../api/types';
export type PlanSortKey = 'default' | 'name' | 'start' | 'progress';
/** Opcje sortowania w menu kontekstowym. */
const SORT_OPTIONS: { id: PlanSortKey; labelKey: string }[] = [
{ id: 'default', labelKey: 'sorts.default' },
{ id: 'name', labelKey: 'sorts.name' },
{ id: 'start', labelKey: 'sorts.start' },
{ id: 'progress', labelKey: 'sorts.progress' },
];
/** Sortowanie listy planów wg klucza („default” = kolejność z API). */
export function sortPlans(list: Plan[], sortKey: PlanSortKey): Plan[] {
if (sortKey === 'default') return list;
const sorted = [...list];
if (sortKey === 'name') sorted.sort((a, b) => a.title.localeCompare(b.title, 'pl'));
else if (sortKey === 'start')
sorted.sort((a, b) => {
// bez startu na końcu
if (a.startDate === b.startDate) return a.title.localeCompare(b.title, 'pl');
if (!a.startDate) return 1;
if (!b.startDate) return -1;
return b.startDate.localeCompare(a.startDate);
});
else
sorted.sort(
(a, b) =>
(b.progress?.percent ?? 0) - (a.progress?.percent ?? 0) ||
a.title.localeCompare(b.title, 'pl'),
);
return sorted;
}
/** Zasięg filtra statusu: zakładka aktualna (bez archiwum) albo archiwum. */
export type PlanFilterScope = 'current' | 'archive';
const SCOPE_FILTERS: Record<PlanFilterScope, { id: 'ALL' | Plan['status']; labelKey: string }[]> = {
current: [
{ id: 'ALL', labelKey: 'filters.ALL' },
{ id: 'ACTIVE', labelKey: 'filters.ACTIVE' },
{ id: 'SUSPENDED', labelKey: 'filters.SUSPENDED' },
{ id: 'DRAFT', labelKey: 'filters.DRAFT' },
],
archive: [
{ id: 'ALL', labelKey: 'filters.ALL' },
{ id: 'COMPLETED', labelKey: 'filters.COMPLETED' },
{ id: 'ABANDONED', labelKey: 'filters.ABANDONED' },
],
};
/** Stan + kontrolki filtrów listy planów (status per zakres zakładki, sortowanie). */
export function usePlanListFilters(scope: PlanFilterScope) {
const { t } = useTranslation('plans');
const [statusFilter, setStatusFilter] = useState<'ALL' | Plan['status']>('ALL');
const [sortKey, setSortKey] = useState<PlanSortKey>('default');
const options = SCOPE_FILTERS[scope];
/* przyciski filtrów pokazują tylko bieżący stan (oszczędność miejsca);
kategoria zostaje wyłącznie w aria-label (czytnik + stabilne selektory testów) */
const statusValue = t(options.find((s) => s.id === statusFilter)?.labelKey ?? 'filters.ALL');
const sortValue = t(SORT_OPTIONS.find((s) => s.id === sortKey)?.labelKey ?? 'sorts.default');
const filters = [
<FilterDropdown
key="status"
icon={<Filter className="w-4 h-4" />}
label={statusValue}
srLabel={t('list.statusLabel', { label: statusValue })}
active={statusFilter !== 'ALL'}
options={options.map((s) => ({ id: s.id, label: t(s.labelKey) }))}
selected={statusFilter}
onSelect={(id) => setStatusFilter(id as 'ALL' | Plan['status'])}
/>,
<FilterDropdown
key="sort"
icon={<ArrowUpDown className="w-4 h-4" />}
label={sortValue}
srLabel={t('list.sortLabel', { label: sortValue })}
active={sortKey !== 'default'}
options={SORT_OPTIONS.map((s) => ({ id: s.id, label: t(s.labelKey) }))}
selected={sortKey}
onSelect={(id) => setSortKey(id as PlanSortKey)}
/>,
];
return {
filters,
filterActive: statusFilter !== 'ALL' || sortKey !== 'default',
statusFilter,
sortKey,
};
}
/**
* Widok listy planów (karty + grupy statusów lub lista płaska przy filtrze/sorcie).
* Współdzielony przez zakładki Aktualne i Archiwum.
*/
export function PlanListView({
plans,
q,
statusFilter,
sortKey,
groupOrder,
emptyTitle,
emptyDesc,
emptyAction,
emptyIcon,
creatorLabel,
}: {
plans: Plan[];
q: string;
statusFilter: 'ALL' | Plan['status'];
sortKey: PlanSortKey;
groupOrder: Plan['status'][];
emptyTitle: string;
emptyDesc?: string;
emptyAction?: ReactNode;
emptyIcon?: LucideIcon;
creatorLabel?: (p: Plan) => string | null;
}) {
const { t } = useTranslation('plans');
const filtered = sortPlans(
(q ? plans.filter((p) => p.title.toLowerCase().includes(q)) : plans).filter(
(p) => statusFilter === 'ALL' || p.status === statusFilter,
),
sortKey,
);
if (plans.length === 0) {
return (
<Card>
<EmptyState
icon={emptyIcon ?? Dumbbell}
title={emptyTitle}
description={emptyDesc}
action={emptyAction}
/>
</Card>
);
}
if (filtered.length === 0) {
return (
<Card>
<p className="text-dim">{t('list.noResults')}</p>
</Card>
);
}
// pogrupowane według statusu (kategorie); wybrany status lub sortowanie → lista płaska
const groups =
statusFilter === 'ALL' && sortKey === 'default'
? groupOrder
.map((status) => ({ status, plans: filtered.filter((p) => p.status === status) }))
.filter((g) => g.plans.length > 0)
: null;
if (groups !== null) {
return (
<>
{groups.map((g) => {
const st = PLAN_STATUS[g.status];
return (
<section key={g.status} className="mb-5">
<div className="mb-2.5 flex items-center gap-2.5">
<H3 className="mb-0">{t(`common:${st.labelKey}`)}</H3>
<Badge color={st.color}>{g.plans.length}</Badge>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{g.plans.map((p) => (
<PlanCard key={p.id} plan={p} creatorLabel={creatorLabel?.(p) ?? null} />
))}
</div>
</section>
);
})}
</>
);
}
return (
<section className="mb-5">
<div className="mb-2.5 flex items-center gap-2.5">
<H3 className="mb-0">{t('list.allPlans')}</H3>
<Badge color="gray">{filtered.length}</Badge>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{filtered.map((p) => (
<PlanCard key={p.id} plan={p} creatorLabel={creatorLabel?.(p) ?? null} />
))}
</div>
</section>
);
}

View File

@@ -0,0 +1,38 @@
import { useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Tabs } from '../ui';
const TAB_PATHS: Record<string, string> = {
active: '/plans/current',
archive: '/plans/archive',
templates: '/plans/templates',
shared: '/plans/shared',
};
/** Segment zakładek sekcji planów (Aktualne / Archiwum / Szablony / Udostępnione). */
export function PlansTabs() {
const { t } = useTranslation('plans');
const { pathname } = useLocation();
const navigate = useNavigate();
const active = pathname.startsWith('/plans/templates')
? 'templates'
: pathname.startsWith('/plans/shared')
? 'shared'
: pathname.startsWith('/plans/archive')
? 'archive'
: 'active';
return (
<div className="mb-4">
<Tabs
tabs={[
{ id: 'active', label: t('tabs.active') },
{ id: 'archive', label: t('tabs.archive') },
{ id: 'templates', label: t('tabs.templates') },
{ id: 'shared', label: t('tabs.shared') },
]}
active={active}
onChange={(id) => navigate(TAB_PATHS[id] ?? '/plans')}
/>
</div>
);
}

View File

@@ -0,0 +1,87 @@
import { useTranslation } from 'react-i18next';
import { muscleName } from '../../lib/labels';
import { Badge } from '../ui';
import type { MuscleReport } from '../../api/types';
/**
* Paski objętości per partia: plan vs. realizacja w seriach + zalecany zakres
* (priorytety FocusArea). Współdzielone: raport trenera (ProgressTab) i kokpit
* Objętość w detalu planu. Progi: poniżej setsMin = niedobór, powyżej
* setsMax * 1.1 = nadmiar.
*/
export function VolumeRanges({ muscles }: { muscles: MuscleReport[] }) {
const { t } = useTranslation('plans');
return (
<div className="flex flex-col gap-3">
{muscles.map((m) => {
const scaleMax = Math.max(
m.planned.sets,
m.actual.sets,
m.recommendedRange?.setsMax ?? 0,
1,
);
const pct = Math.min(100, Math.round((m.actual.sets / scaleMax) * 100));
const tone = !m.recommendedRange
? 'bg-info'
: m.actual.sets < m.recommendedRange.setsMin
? 'bg-danger'
: m.actual.sets > m.recommendedRange.setsMax * 1.1
? 'bg-warn'
: 'bg-(image:--progress-grad)';
return (
<div key={m.muscle}>
<div className="grid grid-cols-[92px_1fr_auto] items-center gap-3 text-[0.8125rem]">
<span className="min-w-0 truncate font-semibold">{muscleName(m.muscle)}</span>
<div
className="relative h-2 overflow-hidden rounded-full bg-input"
title={`${t('volume.planWord')} ${m.planned.sets} · ${t('volume.doneWord')} ${
m.actual.sets
}${
m.recommendedRange
? ` · ${t('volume.rangeWord')} ${m.recommendedRange.setsMin}–${
m.recommendedRange.setsMax
}`
: ''
}`}
>
{m.recommendedRange && (
<div
className="absolute inset-y-0 bg-line"
style={{
left: `${(m.recommendedRange.setsMin / scaleMax) * 100}%`,
width: `${
((m.recommendedRange.setsMax - m.recommendedRange.setsMin) / scaleMax) * 100
}%`,
}}
/>
)}
<div className={`h-full rounded-full ${tone}`} style={{ width: `${pct}%` }} />
</div>
<span className="shrink-0 text-dim tabular-nums">
{m.actual.sets}/{m.planned.sets}
{m.recommendedRange
? ` · ${m.recommendedRange.setsMin}–${m.recommendedRange.setsMax}`
: ''}
</span>
</div>
{(m.extra.sets > 0 || m.missing.sets > 0 || m.outOfRange) && (
<div className="mt-1 flex flex-wrap items-center gap-1.5 sm:pl-[104px]">
{m.extra.sets > 0 && (
<Badge color="green">
+{m.extra.sets} {t('volume.excessWord')}
</Badge>
)}
{m.missing.sets > 0 && (
<Badge color="red">
-{m.missing.sets} {t('volume.deficitWord')}
</Badge>
)}
{m.outOfRange && <Badge color="yellow">{t('volume.outOfRange')}</Badge>}
</div>
)}
</div>
);
})}
</div>
);
}

View File

@@ -5,6 +5,7 @@
"NOT_FOUND": "Resource not found.",
"CONFLICT": "The change conflicts with existing data.",
"PLAN_DAY_TAKEN": "Another workout is already planned on that date.",
"TEMPLATE_NOT_PLAN": "A template is not a plan — clone it to create one.",
"VALIDATION_ERROR": "Please correct the form data.",
"INTERNAL_ERROR": "A server error occurred. Try again.",
"RATE_LIMITED": "Too many attempts. Try again later.",

View File

@@ -1,4 +1,95 @@
{
"tabs": {
"active": "Current",
"archive": "Archive",
"templates": "Templates",
"shared": "Shared"
},
"hub": {
"intro": "Your plans in one place — pick a category.",
"countActive_one": "{{count}} active",
"countActive_other": "{{count}} active",
"countSuspended_one": "{{count}} suspended",
"countSuspended_other": "{{count}} suspended",
"countDraft_one": "{{count}} draft",
"countDraft_other": "{{count}} drafts",
"countCompleted_one": "{{count}} completed",
"countCompleted_other": "{{count}} completed",
"countAbandoned_one": "{{count}} abandoned",
"countAbandoned_other": "{{count}} abandoned",
"countTemplates_one": "{{count}} template",
"countTemplates_other": "{{count}} templates",
"sharedWithMe_one": "{{count}} for me",
"sharedWithMe_other": "{{count}} for me",
"sharedByMe_one": "{{count}} by me",
"sharedByMe_other": "{{count}} by me",
"emptyCurrent": "No current plans",
"emptyArchive": "Archive is empty",
"emptyTemplates": "No templates",
"emptyShared": "Nothing shared",
"traineesCard": "Trainee planning",
"traineesCardDesc": "Coach panels with plans, progress and calendar"
},
"hero": {
"weekOf": "Week {{current}} of {{total}}",
"daysProgress": "{{done}}/{{total}} days",
"nextPrefix": "Next workout:",
"today": "today",
"exercisesCount_one": "{{count}} exercise",
"exercisesCount_other": "{{count}} exercises"
},
"archive": {
"emptyTitle": "The archive is empty",
"emptyDesc": "Completed and abandoned plans will end up here."
},
"newMenu": {
"title": "New plan",
"intro": "Start from scratch or clone a ready template.",
"fromScratch": "From scratch",
"fromTemplate": "From template",
"noTemplates": "You don't have any templates yet.",
"templatesLink": "Create a template",
"useTemplateAria": "Use template {{title}}"
},
"templates": {
"newTemplate": "New template",
"emptyTitle": "No templates",
"emptyDesc": "A template is a reusable training structure — clone it when creating another plan.",
"usedCount_one": "{{count}} use",
"usedCount_other": "{{count}} uses",
"weeksShort": "{{count}} wk",
"daysShort": "{{count}} days",
"exercisesShort": "{{count}} exercises",
"updatedPrefix": "updated:",
"assignTitle": "Assign to trainee",
"assignDesc": "We will create a draft plan for the trainee — a copy of this template. Activation stays a separate action.",
"assignNoTrainees": "You have no active trainees.",
"assignAria": "Assign: {{name}}",
"assignHasActivePlan": "has an active plan",
"assignedToast": "Plan created from template for: {{name}}"
},
"shared": {
"emptyTitle": "Nothing shared",
"emptyDesc": "Share plans with trainers and trainees — you will see both sides here.",
"sectionWithMe": "Shared with me",
"sectionByMe": "Shared by me",
"withPrefix": "shared with:"
},
"volume": {
"title": "Volume",
"desc": "Planned vs. performed sets in muscle groups covered by your priorities.",
"noData": "No volume data for this plan.",
"planWord": "plan",
"doneWord": "performed",
"rangeWord": "range",
"excessWord": "excess",
"deficitWord": "deficit",
"outOfRange": "out of range"
},
"meter": {
"title": "Weekly volume",
"weekly": "sets this week"
},
"set": {
"fillTitle": "Complete set {{n}}",
"editTitle": "Edit set {{n}}",
@@ -122,6 +213,8 @@
"titleNewTrainee": "Plan for trainee",
"titleEdit": "Editing plan",
"titleNew": "New plan",
"titleEditTemplate": "Editing template",
"titleNewTemplate": "New template",
"next": "Next",
"save": "Save",
"saveChanges": "Save changes",
@@ -204,7 +297,10 @@
"abandon": "Abandon",
"reopen": "Resume",
"completeLabel": "Complete",
"share": "Share"
"share": "Share",
"saveAsTemplate": "Save as template",
"useTemplate": "Use",
"assignTrainee": "Assign to trainee"
},
"dialog": {
"title": "Share plan",
@@ -219,7 +315,8 @@
},
"card": {
"open": "Open",
"createdPrefix": "created by"
"createdPrefix": "created by",
"fromTemplate": "from template"
},
"toasts": {
"activated": "Plan activated",
@@ -228,7 +325,8 @@
"suspended": "Plan suspended",
"abandoned": "Plan abandoned",
"resumed": "Plan resumed",
"reopened": "Plan resumed"
"reopened": "Plan resumed",
"savedAsTemplate": "Saved as template"
},
"genericError": "Error",
"detail": {
@@ -257,7 +355,13 @@
"confirmActivateDesc": "The plan will be activated from Monday of the selected week.",
"confirmCompleteTitle": "Mark as completed?",
"confirmCompleteDesc": "The plan will be marked as completed.",
"traineeConflictActivate": "The trainee already has an active plan — only one plan can be active. To activate this plan, complete, abandon or suspend the active one first."
"traineeConflictActivate": "The trainee already has an active plan — only one plan can be active. To activate this plan, complete, abandon or suspend the active one first.",
"fromTemplate": "created from a template",
"savedAsTemplateLink": "Open saved template",
"usesTitle": "Uses",
"usesCount_one": "{{count}} plan created from this template",
"usesCount_other": "{{count}} plans created from this template",
"usesEmpty": "This template has not been used yet."
},
"edits": {
"title": "Plan change history",

View File

@@ -5,6 +5,7 @@
"NOT_FOUND": "Nie znaleziono zasobu.",
"CONFLICT": "Zmiana koliduje z istniejącymi danymi.",
"PLAN_DAY_TAKEN": "W tym terminie jest już zaplanowany inny trening.",
"TEMPLATE_NOT_PLAN": "Szablon nie jest planem do realizacji — sklonuj go, aby utworzyć plan.",
"VALIDATION_ERROR": "Popraw dane w formularzu.",
"INTERNAL_ERROR": "Wystąpił błąd serwera. Spróbuj ponownie.",
"RATE_LIMITED": "Zbyt wiele prób. Spróbuj później.",

View File

@@ -1,4 +1,111 @@
{
"tabs": {
"active": "Aktualne",
"archive": "Archiwum",
"templates": "Szablony",
"shared": "Udostępnione"
},
"hub": {
"intro": "Twoje plany w jednym miejscu — wybierz kategorię.",
"countActive_one": "{{count}} aktywny",
"countActive_few": "{{count}} aktywne",
"countActive_many": "{{count}} aktywnych",
"countActive_other": "{{count}} aktywnych",
"countSuspended_one": "{{count}} wstrzymany",
"countSuspended_few": "{{count}} wstrzymane",
"countSuspended_many": "{{count}} wstrzymanych",
"countSuspended_other": "{{count}} wstrzymanych",
"countDraft_one": "{{count}} szkic",
"countDraft_few": "{{count}} szkice",
"countDraft_many": "{{count}} szkiców",
"countDraft_other": "{{count}} szkiców",
"countCompleted_one": "{{count}} ukończony",
"countCompleted_few": "{{count}} ukończone",
"countCompleted_many": "{{count}} ukończonych",
"countCompleted_other": "{{count}} ukończonych",
"countAbandoned_one": "{{count}} porzucony",
"countAbandoned_few": "{{count}} porzucone",
"countAbandoned_many": "{{count}} porzuconych",
"countAbandoned_other": "{{count}} porzuconych",
"countTemplates_one": "{{count}} szablon",
"countTemplates_few": "{{count}} szablony",
"countTemplates_many": "{{count}} szablonów",
"countTemplates_other": "{{count}} szablonów",
"sharedWithMe_one": "{{count}} dla mnie",
"sharedWithMe_other": "{{count}} dla mnie",
"sharedByMe_one": "{{count}} przeze mnie",
"sharedByMe_other": "{{count}} przeze mnie",
"emptyCurrent": "Brak bieżących planów",
"emptyArchive": "Archiwum jest puste",
"emptyTemplates": "Brak szablonów",
"emptyShared": "Brak udostępnień",
"traineesCard": "Planowanie podopiecznych",
"traineesCardDesc": "Panele trenera z planami, postępem i kalendarzem"
},
"hero": {
"weekOf": "Tydzień {{current}} z {{total}}",
"daysProgress": "{{done}}/{{total}} dni",
"nextPrefix": "Następny trening:",
"today": "dziś",
"exercisesCount_one": "{{count}} ćwiczenie",
"exercisesCount_few": "{{count}} ćwiczenia",
"exercisesCount_many": "{{count}} ćwiczeń",
"exercisesCount_other": "{{count}} ćwiczeń"
},
"archive": {
"emptyTitle": "Archiwum jest puste",
"emptyDesc": "Tu trafią plany ukończone i porzucone."
},
"newMenu": {
"title": "Nowy plan",
"intro": "Zacznij od zera albo skopiuj gotowy szablon.",
"fromScratch": "Od zera",
"fromTemplate": "Z szablonu",
"noTemplates": "Nie masz jeszcze żadnych szablonów.",
"templatesLink": "Utwórz szablon",
"useTemplateAria": "Użyj szablonu {{title}}"
},
"templates": {
"newTemplate": "Nowy szablon",
"emptyTitle": "Brak szablonów",
"emptyDesc": "Szablon to gotowa struktura treningowa — klonuj ją, tworząc kolejny plan.",
"usedCount_one": "{{count}} użycie",
"usedCount_few": "{{count}} użycia",
"usedCount_many": "{{count}} użyć",
"usedCount_other": "{{count}} użyć",
"weeksShort": "{{count}} tyg.",
"daysShort": "{{count}} dni",
"exercisesShort": "{{count}} ćwiczeń",
"updatedPrefix": "zmieniono:",
"assignTitle": "Przypisz podopiecznemu",
"assignDesc": "Utworzymy szkic planu dla podopiecznego — kopię tego szablonu. Aktywacja pozostaje osobną akcją.",
"assignNoTrainees": "Nie masz aktywnych podopiecznych.",
"assignAria": "Przypisz: {{name}}",
"assignHasActivePlan": "ma aktywny plan",
"assignedToast": "Utworzono plan z szablonu dla: {{name}}"
},
"shared": {
"emptyTitle": "Brak udostępnień",
"emptyDesc": "Udostępniaj plany trenerom i podopiecznym — tutaj zobaczysz obie strony.",
"sectionWithMe": "Udostępnione mi",
"sectionByMe": "Udostępnione przeze mnie",
"withPrefix": "udostępniono:"
},
"volume": {
"title": "Objętość",
"desc": "Serie zaplanowane vs. zrealizowane w partiach objętych priorytetami.",
"noData": "Brak danych o objętości tego planu.",
"planWord": "plan",
"doneWord": "wykonane",
"rangeWord": "zakres",
"excessWord": "nadmiar",
"deficitWord": "deficyt",
"outOfRange": "poza zakresem"
},
"meter": {
"title": "Objętość tygodnia",
"weekly": "serie w tygodniu"
},
"set": {
"fillTitle": "Uzupełnij serię {{n}}",
"editTitle": "Edytuj serię {{n}}",
@@ -122,6 +229,8 @@
"titleNewTrainee": "Plan dla podopiecznego",
"titleEdit": "Edycja planu",
"titleNew": "Nowy plan",
"titleEditTemplate": "Edycja szablonu",
"titleNewTemplate": "Nowy szablon",
"next": "Dalej",
"save": "Zapisz",
"saveChanges": "Zapisz zmiany",
@@ -205,7 +314,10 @@
"abandon": "Porzuć",
"reopen": "Wznów",
"completeLabel": "Ukończ",
"share": "Udostępnij"
"share": "Udostępnij",
"saveAsTemplate": "Zapisz jako szablon",
"useTemplate": "Użyj",
"assignTrainee": "Przypisz podopiecznemu"
},
"dialog": {
"title": "Udostępnij plan",
@@ -220,7 +332,8 @@
},
"card": {
"open": "Otwórz",
"createdPrefix": "utworzył"
"createdPrefix": "utworzył",
"fromTemplate": "z szablonu"
},
"toasts": {
"activated": "Plan aktywowany",
@@ -229,7 +342,8 @@
"suspended": "Plan zawieszony",
"abandoned": "Plan porzucony",
"resumed": "Plan wznowiony",
"reopened": "Plan wznowiony"
"reopened": "Plan wznowiony",
"savedAsTemplate": "Zapisano jako szablon"
},
"genericError": "Błąd",
"detail": {
@@ -258,7 +372,15 @@
"confirmActivateDesc": "Plan zostanie aktywowany od poniedziałku zaznaczonego tygodnia.",
"confirmCompleteTitle": "Oznaaczyć jako ukończony?",
"confirmCompleteDesc": "Plan zostanie oznaczony jako ukończony.",
"traineeConflictActivate": "Podopieczny ma już aktywny plan — tylko jeden plan może być aktywny. Aby aktywować ten plan, najpierw ukończ, porzuć lub zawieś aktywny."
"traineeConflictActivate": "Podopieczny ma już aktywny plan — tylko jeden plan może być aktywny. Aby aktywować ten plan, najpierw ukończ, porzuć lub zawieś aktywny.",
"fromTemplate": "utworzony z szablonu",
"savedAsTemplateLink": "Otwórz zapisany szablon",
"usesTitle": "Użycia",
"usesCount_one": "Utworzono {{count}} plan z tego szablonu",
"usesCount_few": "Utworzono {{count}} plany z tego szablonu",
"usesCount_many": "Utworzono {{count}} planów z tego szablonu",
"usesCount_other": "Utworzono {{count}} planów z tego szablonu",
"usesEmpty": "Ten szablon nie został jeszcze użyty."
},
"edits": {
"title": "Historia zmian w planie",

View File

@@ -1,24 +1,44 @@
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQueryClient } from '@tanstack/react-query';
import { CalendarDays, MapPin, Pause, Pencil, Play, RotateCcw, Share2, Trash2 } from 'lucide-react';
import {
CalendarDays,
Copy,
FileStack,
MapPin,
Pause,
Pencil,
Play,
RotateCcw,
Share2,
Trash2,
UserPlus,
} from 'lucide-react';
import {
abandonPlan,
activatePlan,
clonePlan,
completePlan,
createTraineePlanFromTemplate,
deletePlan,
reopenPlan,
resumePlan,
savePlanAsTemplate,
suspendPlan,
useMe,
usePlan,
usePlanTemplate,
usePlanVolume,
usePlans,
useTrainees,
} from '../../api/queries';
import { apiErrorMessage } from '../../lib/errors';
import { fmtDate, fmtDateTime } from '../../lib/format';
import { PLAN_STATUS } from '../../lib/labels';
import { PlanWeeks } from '../../components/plans/PlanWeeks';
import { SharePlanDialog } from '../../components/plans/SharePlanDialog';
import { VolumeRanges } from '../../components/plans/VolumeRanges';
import { useToast } from '../../components/toast';
import { useTopbar } from '../../topbar';
import {
@@ -28,18 +48,24 @@ import {
ConfirmDialog,
ErrorText,
H3,
Loading,
MetaItem,
Modal,
Muted,
PageHeader,
SectionHeader,
Skeleton,
WeekPicker,
} from '../../components/ui';
export default function PlanDetail() {
export default function PlanDetail({ templateMode = false }: { templateMode?: boolean }) {
const { id } = useParams();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { data, isLoading, error } = usePlan(id ?? '');
const tplQuery = usePlanTemplate(templateMode ? (id ?? '') : '');
const ownerQuery = usePlan(templateMode ? '' : (id ?? ''));
const isLoading = templateMode ? tplQuery.isLoading : ownerQuery.isLoading;
const error = templateMode ? tplQuery.error : ownerQuery.error;
const { data: plansData } = usePlans();
const { data: meData } = useMe();
const { push } = useToast();
@@ -47,11 +73,13 @@ export default function PlanDetail() {
const [startDate, setStartDate] = useState('');
const [actionError, setActionError] = useState('');
const [busy, setBusy] = useState(false);
const [savedTplId, setSavedTplId] = useState<string | null>(null);
const [assignOpen, setAssignOpen] = useState(false);
const [confirm, setConfirm] = useState<
null | 'delete' | 'abandon' | 'reopen' | 'suspend' | 'resume'
>(null);
const planData = data?.plan;
const planData = templateMode ? tplQuery.data?.plan : ownerQuery.data?.plan;
const [shareOpen, setShareOpen] = useState(false);
// Szkic zapisany z zaznaczonym tygodniem startu — picker preuzupełnia planowany
// start (jednorazowo, żeby nie nadpisywać ręcznej zmiany użytkownika).
@@ -68,6 +96,24 @@ export default function PlanDetail() {
// odbiorca share'a = read-only (canManage z detalu; fallback: właściciel).
const isOwner = !!planData && !!meData && planData.userId === meData.user.id;
const canManage = planData ? (planData.canManage ?? isOwner) : false;
// „Zapisz jako szablon": właściciel planu albo jego autor (trener, który sam
// zrobił plan dla podopiecznego). Szablonów nie zapisujemy ponownie.
const canSaveTemplate =
!!planData &&
planData.kind !== 'TEMPLATE' &&
(isOwner || (!!meData && planData.creator?.id === meData.user.id));
// Przypisanie szablonu podopiecznemu = tylko trener z aktywnymi podopiecznymi.
const isTrainer = (meData?.memberships ?? []).some((m) => m.roles.includes('TRAINER'));
const { data: traineesData } = useTrainees(undefined, isTrainer);
// Kokpit objętości: właściciel, plan zwykły w trakcie realizacji lub domknięty.
const volumeEnabled =
!templateMode &&
isOwner &&
planData?.kind !== 'TEMPLATE' &&
(planData?.status === 'ACTIVE' ||
planData?.status === 'COMPLETED' ||
planData?.status === 'ABANDONED');
const volumeQuery = usePlanVolume(id ?? '', volumeEnabled);
// Blokada aktywacji: tylko jeden plan może być aktywny w danej chwili.
const hasOtherActivePlan = (plansData?.plans ?? []).some(
(p) => p.status === 'ACTIVE' && p.id !== planData?.id,
@@ -92,14 +138,109 @@ export default function PlanDetail() {
}
};
// „Zapisz jako szablon": kopia struktury należąca do sprawcy; źródło nietknięte.
const asTemplate = async () => {
if (!planData) return;
setActionError('');
setBusy(true);
try {
const res = await savePlanAsTemplate(planData.id);
setSavedTplId(res.plan.id);
await queryClient.invalidateQueries({ queryKey: ['plans', 'templates'] });
push(t('toasts.savedAsTemplate'), 'success');
} catch (e) {
setActionError(apiErrorMessage(e, t, t('genericError')));
} finally {
setBusy(false);
}
};
// „Użyj” (detail szablonu): klon do własnego szkicu — redirect do kopii.
const useForMe = async () => {
if (!planData) return;
setActionError('');
setBusy(true);
try {
const res = await clonePlan(planData.id);
await queryClient.invalidateQueries({ queryKey: ['plans'] });
navigate(`/plans/${res.plan.id}`);
} catch (e) {
setActionError(apiErrorMessage(e, t, t('genericError')));
} finally {
setBusy(false);
}
};
// „Przypisz podopiecznemu” (trener): klon szablonu do szkicu podopiecznego.
const assignToTrainee = async (userId: string, name: string) => {
if (!planData) return;
setActionError('');
setBusy(true);
try {
const res = await createTraineePlanFromTemplate(userId, planData.id);
await queryClient.invalidateQueries({ queryKey: ['trainees', userId, 'plans'] });
setAssignOpen(false);
push(t('templates.assignedToast', { name }), 'success');
navigate(`/plans/${res.plan.id}`);
} catch (e) {
setActionError(apiErrorMessage(e, t, t('genericError')));
setBusy(false);
}
};
// operacje stronicowe w menu kontekstowym (standard topmenu); WeekPicker + hint zostają w karcie
// read-only (odbiorca share'a): bez akcji statusowych i bez „Udostępnij”
useTopbar({
title: t('nav:plans'),
back: '/plans',
actions:
planData && canManage
back: templateMode ? '/plans/templates' : '/plans',
actions: templateMode
? planData
? [
{
label: t('actions.edit'),
to: `/plans/templates/${planData.id}/edit`,
variant: 'secondary' as const,
icon: Pencil,
},
{
label: t('actions.useTemplate'),
icon: Copy,
disabled: busy,
onClick: () => void useForMe(),
},
...(isTrainer
? [
{
label: t('actions.assignTrainee'),
icon: UserPlus,
variant: 'secondary' as const,
disabled: busy,
onClick: () => setAssignOpen(true),
},
]
: []),
{
label: t('actions.delete'),
icon: Trash2,
variant: 'danger' as const,
disabled: busy,
onClick: () => setConfirm('delete'),
},
]
: undefined
: planData && canManage
? [
...(canSaveTemplate
? [
{
label: t('actions.saveAsTemplate'),
icon: FileStack,
variant: 'secondary' as const,
disabled: busy,
onClick: () => void asTemplate(),
},
]
: []),
...(planData.status === 'DRAFT'
? [
{
@@ -221,7 +362,17 @@ export default function PlanDetail() {
]
: []),
]
: undefined,
: planData && canSaveTemplate
? [
{
label: t('actions.saveAsTemplate'),
icon: FileStack,
variant: 'secondary' as const,
disabled: busy,
onClick: () => void asTemplate(),
},
]
: undefined,
defaultOpenGroup: 'actions',
});
@@ -240,9 +391,9 @@ export default function PlanDetail() {
{t('detail.errorPrefix')} {(error as Error).message}
</ErrorText>
);
if (!data) return null;
if (!planData) return null;
const plan = data.plan;
const plan = planData;
const st = PLAN_STATUS[plan.status];
const allDays = plan.weeks.flatMap((w) => w.days);
const doneDays = allDays.filter((d) => d.status === 'COMPLETED').length;
@@ -264,7 +415,9 @@ export default function PlanDetail() {
<PageHeader
title={plan.title}
badge={<Badge color={st.color}>{t(`common:${st.labelKey}`)}</Badge>}
actions={<BackButton onClick={() => navigate('/plans')} />}
actions={
<BackButton onClick={() => navigate(templateMode ? '/plans/templates' : '/plans')} />
}
/>
<Card>
@@ -293,6 +446,19 @@ export default function PlanDetail() {
</Muted>
)}
</div>
{(plan.sourceTemplateId || savedTplId) && (
<div className="mt-2 flex flex-wrap items-center gap-2.5">
{plan.sourceTemplateId && <Badge color="gray">{t('detail.fromTemplate')}</Badge>}
{savedTplId && (
<Link
to={`/plans/templates/${savedTplId}`}
className="text-accent-text text-[0.875rem] underline"
>
{t('detail.savedAsTemplateLink')}
</Link>
)}
</div>
)}
{allDays.length > 0 && (
<div className="mt-3 flex items-center gap-2.5">
<div className="h-[5px] flex-1 overflow-hidden rounded-full bg-input">
@@ -306,7 +472,7 @@ export default function PlanDetail() {
</span>
</div>
)}
{plan.status === 'DRAFT' && canManage && (
{plan.status === 'DRAFT' && canManage && !templateMode && (
<div className="mt-4">
<p className="mb-2 text-[0.875rem] text-dim">{t('detail.startWeekLabel')}</p>
<WeekPicker value={startDate} onChange={setStartDate} />
@@ -326,7 +492,79 @@ export default function PlanDetail() {
)}
</Card>
<PlanWeeks weeks={plan.weeks} showDate canExecute={plan.status === 'ACTIVE'} />
<PlanWeeks
weeks={plan.weeks}
showDate={!templateMode}
canExecute={!templateMode && plan.status === 'ACTIVE'}
/>
{volumeEnabled && (
<Card className="mt-4">
<SectionHeader title={t('volume.title')} description={t('volume.desc')} />
{volumeQuery.isLoading && <Loading />}
{volumeQuery.error && (
<ErrorText>
{t('detail.errorPrefix')} {(volumeQuery.error as Error).message}
</ErrorText>
)}
{!volumeQuery.isLoading &&
!volumeQuery.error &&
(volumeQuery.data?.muscles ?? []).length === 0 && (
<p className="text-dim">{t('volume.noData')}</p>
)}
{!volumeQuery.isLoading &&
!volumeQuery.error &&
(volumeQuery.data?.muscles ?? []).length > 0 && (
<VolumeRanges muscles={volumeQuery.data?.muscles ?? []} />
)}
</Card>
)}
{templateMode && tplQuery.data && (
<Card className="mt-4">
<SectionHeader
title={t('detail.usesTitle')}
description={t('detail.usesCount', { count: tplQuery.data.usedCount })}
/>
{tplQuery.data.derived.length === 0 ? (
<p className="text-dim">{t('detail.usesEmpty')}</p>
) : (
<ul className="space-y-2.5">
{tplQuery.data.derived.map((d) => {
const dst = PLAN_STATUS[d.status];
return (
<li key={d.id}>
<Link
to={`/plans/${d.id}`}
className="flex flex-col gap-1.5 rounded-[10px] border border-line bg-card/40 p-3 transition-colors hover:border-accent/55"
>
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className="min-w-0 truncate font-semibold">{d.title}</span>
<Badge color={dst.color}>{t(`common:${dst.labelKey}`)}</Badge>
<span className="text-dim text-[0.8125rem] sm:ml-auto">{d.ownerName}</span>
</div>
<div className="flex items-center gap-2.5">
<div className="h-[5px] flex-1 overflow-hidden rounded-full bg-input">
<div
className="h-full rounded-full bg-(image:--progress-grad)"
style={{ width: `${d.progress.percent}%` }}
/>
</div>
<span className="text-dim text-[0.8125rem] tabular-nums">
{t('detail.daysDone', {
done: d.progress.completed,
total: d.progress.total,
})}
</span>
</div>
</Link>
</li>
);
})}
</ul>
)}
</Card>
)}
{(plan.edits?.length ?? 0) > 0 && (
<Card className="mt-4">
@@ -370,6 +608,43 @@ export default function PlanDetail() {
)}
<SharePlanDialog open={shareOpen} onClose={() => setShareOpen(false)} plan={plan} />
{/* Przypisanie szablonu podopiecznemu (trener): kopia DRAFT dla wybranej osoby. */}
<Modal
open={assignOpen}
onClose={() => setAssignOpen(false)}
title={t('templates.assignTitle')}
handle
>
<p className="mb-3 text-dim text-[0.875rem]">{t('templates.assignDesc')}</p>
{(traineesData?.trainees ?? []).length === 0 && (
<p className="text-dim text-[0.875rem]">{t('templates.assignNoTrainees')}</p>
)}
<div className="flex flex-col gap-1">
{(traineesData?.trainees ?? []).map((tr) => {
const name =
[tr.user.firstName, tr.user.lastName].filter(Boolean).join(' ') ||
tr.user.nickname ||
t('dialog.userFallback');
return (
<button
key={tr.user.id}
type="button"
disabled={busy}
aria-label={t('templates.assignAria', { name })}
onClick={() => void assignToTrainee(tr.user.id, name)}
className="flex cursor-pointer items-center justify-between gap-3 rounded-[10px] px-3 py-2.5 text-left text-[0.95rem] font-semibold transition-colors hover:bg-line/30 disabled:opacity-50"
>
<span className="min-w-0 truncate">{name}</span>
{tr.activePlan && (
<span className="shrink-0 text-dim text-[0.8rem]">
{t('templates.assignHasActivePlan')}
</span>
)}
</button>
);
})}
</div>
</Modal>
<ConfirmDialog
open={confirm === 'delete'}
onClose={() => setConfirm(null)}
@@ -377,7 +652,7 @@ export default function PlanDetail() {
setConfirm(null);
await act(async () => {
await deletePlan(plan.id);
navigate('/plans');
navigate(templateMode ? '/plans/templates' : '/plans');
}, t('toasts.deleted'));
}}
title={t('detail.confirmDeleteTitle')}

View File

@@ -13,6 +13,7 @@ import {
useTraineeExerciseProgress,
useTraineeLatestResults,
useExercises,
useFocusAreas,
type PlanBody,
} from '../../api/queries';
import { CalendarX, Check, ChevronRight, Copy, History, Trash2, Unlink } from 'lucide-react';
@@ -44,6 +45,7 @@ import { PlanSummary } from './plan-editor/PlanSummary';
import { WeekPanel } from './plan-editor/WeekPanel';
import { DayPicker } from './plan-editor/DayPicker';
import { DayEditor } from './plan-editor/DayEditor';
import { WeekVolumeMeter, type VolumeRange } from './plan-editor/WeekVolumeMeter';
/** Stan ładowania trybu edycji: skeleton w miejscu formularza i tygodni. */
function EditorSkeleton() {
@@ -127,7 +129,12 @@ function WizardStepper({ step, onGo }: { step: number; onGo: (n: number) => void
);
}
export default function PlanEditor() {
/**
* Kreator planu — trzy tryby: właściciela (/plans/...), podopiecznego
* (/trainees/:userId/plans/...) i szablonu (templateMode — /plans/templates/...:
* bez startu i siłowni, zapis jako kind=TEMPLATE).
*/
export default function PlanEditor({ templateMode = false }: { templateMode?: boolean }) {
const { id, userId, planId } = useParams();
const { t, i18n } = useTranslation('plans');
const traineeUserId = userId ?? '';
@@ -148,12 +155,18 @@ export default function PlanEditor() {
// Siłownie do wyboru: tryb własny = członkostwa zalogowanego, tryb trenera = członkostwa podopiecznego.
const { data: gymsData } = useGyms();
const { data: traineeData } = useTrainee(isTraineeMode ? traineeUserId : '');
// Zakresy tygodniowe priorytetów — miernik objętości w edytorze (frontend-only).
const { data: focusAreasData } = useFocusAreas();
const backPath = isTraineeMode
? `/trainees/${traineeUserId}?tab=plans`
: isEdit
? `/plans/${planIdParam}`
: '/plans';
: templateMode
? isEdit
? `/plans/templates/${planIdParam}`
: '/plans/templates'
: isEdit
? `/plans/${planIdParam}`
: '/plans';
const [saving, setSaving] = useState(false);
const [step, setStep] = useState(1);
@@ -190,13 +203,17 @@ export default function PlanEditor() {
};
useTopbar({
title: isTraineeMode
title: templateMode
? isEdit
? t('wizard.titleEditTrainee')
: t('wizard.titleNewTrainee')
: isEdit
? t('wizard.titleEdit')
: t('wizard.titleNew'),
? t('wizard.titleEditTemplate')
: t('wizard.titleNewTemplate')
: isTraineeMode
? isEdit
? t('wizard.titleEditTrainee')
: t('wizard.titleNewTrainee')
: isEdit
? t('wizard.titleEdit')
: t('wizard.titleNew'),
// „Wstecz”: telefon = ikona „<” (smartBack: krok > 1 → poprzedni etap, krok 1 → wyjście
// z guardem), tablet/PC = BackButton w treści — jedno sterowanie na viewport
back: backPath,
@@ -271,6 +288,29 @@ export default function PlanEditor() {
const [changeNote, setChangeNoteState] = useState('');
const exercises = exData?.exercises ?? [];
// Zakresy tygodniowe priorytetów (FocusArea.setsMin/setsMax) i partia ćwiczenia —
// miernik objętości w edytorze (frontend-only; te same progi co w raporcie trenera).
const volumeRanges = useMemo(() => {
const m = new Map<string, VolumeRange>();
for (const f of focusAreasData?.focusAreas ?? [])
if (f.setsMin != null && f.setsMax != null)
m.set(f.muscle, { min: f.setsMin, max: f.setsMax });
return m;
}, [focusAreasData]);
const muscleById = useMemo(
() => new Map(exercises.map((e) => [e.id, e.primaryMuscle])),
[exercises],
);
const weeklyCounts = (wi: number) => {
const counts = new Map<string, number>();
for (const d of displayedDaysOf(editor.weeks, wi))
for (const e of d.exercises) {
const m = muscleById.get(e.exerciseId);
if (!m) continue;
counts.set(m, (counts.get(m) ?? 0) + e.sets.length);
}
return counts;
};
// Wybrana siłownia (z wyposażeniem) — limituje picker ćwiczeń do dostępnego sprzętu.
// (przed wczesnym returnem — hooki muszą być bezwarunkowe)
const selectedGym =
@@ -377,7 +417,7 @@ export default function PlanEditor() {
const body: PlanBody = {
title: editor.title.trim(),
weeksCount: editor.weeksCount,
gymId: editor.gymId,
...(templateMode ? { kind: 'TEMPLATE' as const } : { gymId: editor.gymId }),
weeks: editor.weeks.map((w, i) => {
const keepIds = i === 0 || w.detached;
return {
@@ -410,8 +450,8 @@ export default function PlanEditor() {
// Data startu w obu trybach — plan ZAWSZE pozostaje szkicem; zaznaczony tydzień
// to planowany start (daty dni wyliczane przy aktywacji „Aktywuj”).
// Tydzień startu: bieżący lub przyszły (WeekPicker blokuje minione; guard zapasowy).
// Plan ACTIVE ma start niezmienny — nie wysyłamy go wcale.
if (!isPlanActive && editor.startDate) {
// Plan ACTIVE ma start niezmienny — nie wysyłamy go wcale. Szablon startu nie ma.
if (!templateMode && !isPlanActive && editor.startDate) {
if (isPastWeek(editor.startDate)) {
push(t('wizard.startWeekError'), 'error');
return;
@@ -420,11 +460,17 @@ export default function PlanEditor() {
}
setSaving(true);
try {
let targetPath = `/plans/${planIdParam}`;
let targetPath = templateMode ? `/plans/templates/${planIdParam}` : `/plans/${planIdParam}`;
if (isTraineeMode) {
if (!isEdit) await createTraineePlan(traineeUserId, body);
else await updateTraineePlan(traineeUserId, planIdParam, body);
targetPath = backPath;
} else if (templateMode) {
if (isEdit) await updatePlan(planIdParam, body);
else {
const res = await createPlan(body);
targetPath = `/plans/templates/${res.plan.id}`;
}
} else if (isEdit) {
await updatePlan(planIdParam, body);
} else {
@@ -657,6 +703,7 @@ export default function PlanEditor() {
startDateLocked={isPlanActive}
changeNote={isPlanActive ? changeNote : undefined}
onSetChangeNote={isPlanActive ? (v) => setChangeNoteState(v) : undefined}
templateMode={templateMode}
/>
)}
@@ -716,6 +763,11 @@ export default function PlanEditor() {
canClear={weekDays.length > 0 || !week.detached}
onClear={() => setClearWeekIdx(activeWi)}
>
<WeekVolumeMeter
counts={weeklyCounts(activeWi)}
ranges={volumeRanges}
className="mt-0 mb-3"
/>
{mirrored ? (
/* Lustrzany tydzień: zamiast edytora — jawny podgląd tygodnia 1 + odłączenie.
Zmiana dnia w takim tygodniu i tak by go odłączała (editWeek), więc
@@ -922,6 +974,9 @@ export default function PlanEditor() {
gymName={gymName}
startDate={editor.startDate}
weeks={editor.weeks}
ranges={volumeRanges}
muscleOf={(eid) => muscleById.get(eid)}
templateMode={templateMode}
/>
)}

View File

@@ -0,0 +1,115 @@
import { useEffect } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { FileStack, Layers } from 'lucide-react';
import { usePlanTemplates } from '../../api/queries';
import { fmtDate } from '../../lib/format';
import { PlansTabs } from '../../components/plans/PlansTabs';
import { Badge, Button, Card, EmptyState, ErrorText, Skeleton } from '../../components/ui';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
import type { PlanTemplateListItem } from '../../api/types';
/** Karta szablonu: tytuł + liczniki (tygodnie/dni/ćwiczenia/użycia). */
function TemplateCard({ tpl }: { tpl: PlanTemplateListItem }) {
const { t } = useTranslation('plans');
return (
<Link
to={`/plans/templates/${tpl.id}`}
className="group relative flex flex-col gap-3 overflow-hidden rounded-xl border border-line bg-(image:--card-grad) p-4 pl-5 shadow-card transition-all duration-150 hover:border-accent/55 sm:flex-row sm:items-center sm:gap-4"
>
<span aria-hidden="true" className="absolute inset-y-0 left-0 w-[3px] bg-line" />
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5">
<span className="min-w-0 truncate font-semibold transition-colors group-hover:text-accent-text">
{tpl.title}
</span>
{tpl.usedCount > 0 && (
<Badge color="blue">{t('templates.usedCount', { count: tpl.usedCount })}</Badge>
)}
</div>
<div className="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-dim text-[0.8125rem]">
<span className="inline-flex items-center gap-1.5">
<Layers className="w-4 h-4" aria-hidden="true" />
{t('templates.weeksShort', { count: tpl.weeksCount })}
</span>
<span>{t('templates.daysShort', { count: tpl.daysCount })}</span>
<span>{t('templates.exercisesShort', { count: tpl.exercisesCount })}</span>
<span>
{t('templates.updatedPrefix')} {fmtDate(tpl.updatedAt)}
</span>
</div>
</div>
</Link>
);
}
export default function PlanTemplates() {
const { t } = useTranslation('plans');
useTopbar({
title: t('nav:plans'),
search: 'plans',
actions: [{ label: t('templates.newTemplate'), to: '/plans/templates/new', icon: FileStack }],
});
const { data, isLoading, error } = usePlanTemplates();
const query = useListSearch((s) => s.queries.plans);
const setQuery = useListSearch((s) => s.setQuery);
useEffect(() => () => setQuery('plans', ''), [setQuery]);
const templates = data?.templates ?? [];
const q = query.toLowerCase();
const filtered = q ? templates.filter((tm) => tm.title.toLowerCase().includes(q)) : templates;
return (
<>
<PlansTabs />
{isLoading && (
<div className="flex flex-col gap-4">
<Skeleton className="h-20" />
<Skeleton className="h-20" />
</div>
)}
{error && (
<ErrorText>
{t('list.errorPrefix')} {(error as Error).message}
</ErrorText>
)}
{data && templates.length === 0 && (
<Card>
<EmptyState
icon={FileStack}
title={t('templates.emptyTitle')}
description={t('templates.emptyDesc')}
action={
<Link to="/plans/templates/new">
<Button>
<FileStack className="w-4 h-4" />
{t('templates.newTemplate')}
</Button>
</Link>
}
/>
</Card>
)}
{data && templates.length > 0 && filtered.length === 0 && (
<Card>
<p className="text-dim">{t('list.noResults')}</p>
</Card>
)}
{filtered.length > 0 && (
<section className="mb-5">
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{filtered.map((tm) => (
<TemplateCard key={tm.id} tpl={tm} />
))}
</div>
</section>
)}
</>
);
}

View File

@@ -1,247 +0,0 @@
import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ArrowUpDown, CalendarPlus, Dumbbell, Filter, Plus } from 'lucide-react';
import { useMe, usePlans, useSharedWithMe } from '../../api/queries';
import { PLAN_STATUS } from '../../lib/labels';
import { FilterDropdown } from '../../components/FilterDropdown';
import { PlanCard } from '../../components/plans/PlanCard';
import { Badge, Button, Card, EmptyState, ErrorText, H3, Skeleton } from '../../components/ui';
import type { Plan } from '../../api/types';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
/** Kolejność kategorii (statusów) na liście planów. */
const STATUS_ORDER: Plan['status'][] = ['ACTIVE', 'SUSPENDED', 'DRAFT', 'COMPLETED', 'ABANDONED'];
/** Filtry statusu w menu kontekstowym (domyślnie: wszystkie kategorie naraz). */
const STATUS_FILTERS: { id: 'ALL' | Plan['status']; labelKey: string }[] = [
{ id: 'ALL', labelKey: 'filters.ALL' },
{ id: 'ACTIVE', labelKey: 'filters.ACTIVE' },
{ id: 'SUSPENDED', labelKey: 'filters.SUSPENDED' },
{ id: 'DRAFT', labelKey: 'filters.DRAFT' },
{ id: 'COMPLETED', labelKey: 'filters.COMPLETED' },
{ id: 'ABANDONED', labelKey: 'filters.ABANDONED' },
];
type SortKey = 'default' | 'name' | 'start' | 'progress';
/** Opcje sortowania w menu kontekstowym. */
const SORT_OPTIONS: { id: SortKey; labelKey: string }[] = [
{ id: 'default', labelKey: 'sorts.default' },
{ id: 'name', labelKey: 'sorts.name' },
{ id: 'start', labelKey: 'sorts.start' },
{ id: 'progress', labelKey: 'sorts.progress' },
];
/** Sortowanie listy planów wg klucza („default” = kolejność z API). */
function sortPlans(list: Plan[], sortKey: SortKey): Plan[] {
if (sortKey === 'default') return list;
const sorted = [...list];
if (sortKey === 'name') sorted.sort((a, b) => a.title.localeCompare(b.title, 'pl'));
else if (sortKey === 'start')
sorted.sort((a, b) => {
// bez startu na końcu
if (a.startDate === b.startDate) return a.title.localeCompare(b.title, 'pl');
if (!a.startDate) return 1;
if (!b.startDate) return -1;
return b.startDate.localeCompare(a.startDate);
});
else
sorted.sort(
(a, b) =>
(b.progress?.percent ?? 0) - (a.progress?.percent ?? 0) ||
a.title.localeCompare(b.title, 'pl'),
);
return sorted;
}
export default function Plans() {
const { t } = useTranslation('plans');
const [statusFilter, setStatusFilter] = useState<'ALL' | Plan['status']>('ALL');
const [sortKey, setSortKey] = useState<SortKey>('default');
/* przyciski filtrów pokazują tylko bieżący stan (oszczędność miejsca);
kategoria zostaje wyłącznie w aria-label (czytnik + stabilne selektory testów) */
const statusValue = t(
STATUS_FILTERS.find((s) => s.id === statusFilter)?.labelKey ?? 'filters.ALL',
);
const sortValue = t(SORT_OPTIONS.find((s) => s.id === sortKey)?.labelKey ?? 'sorts.default');
useTopbar({
title: t('nav:plans'),
search: 'plans',
filters: [
<FilterDropdown
key="status"
icon={<Filter className="w-4 h-4" />}
label={statusValue}
srLabel={t('list.statusLabel', { label: statusValue })}
active={statusFilter !== 'ALL'}
options={STATUS_FILTERS.map((s) => ({ id: s.id, label: t(s.labelKey) }))}
selected={statusFilter}
onSelect={(id) => setStatusFilter(id as 'ALL' | Plan['status'])}
/>,
<FilterDropdown
key="sort"
icon={<ArrowUpDown className="w-4 h-4" />}
label={sortValue}
srLabel={t('list.sortLabel', { label: sortValue })}
active={sortKey !== 'default'}
options={SORT_OPTIONS.map((s) => ({ id: s.id, label: t(s.labelKey) }))}
selected={sortKey}
onSelect={(id) => setSortKey(id as SortKey)}
/>,
],
filterActive: statusFilter !== 'ALL' || sortKey !== 'default',
actions: [{ label: t('list.newPlan'), to: '/plans/new', icon: Plus }],
});
const { data, isLoading, error } = usePlans();
const { data: sharedData } = useSharedWithMe();
const { data: meData } = useMe();
const query = useListSearch((s) => s.queries.plans);
const setQuery = useListSearch((s) => s.setQuery);
/** Imię i nazwisko twórcy, gdy plan nie został utworzony przez zalogowanego. */
const creatorLabel = (p: Plan): string | null => {
if (!p.creator) return null;
if (meData?.user.id && p.creator.id === meData.user.id) return null;
return (
[p.creator.firstName, p.creator.lastName].filter(Boolean).join(' ') ||
t('list.trainerFallback')
);
};
/** Imię i nazwisko osoby, która udostępniła plan (sekcja „Udostępnione mi”). */
const sharedByLabel = (p: Plan): string =>
[p.sharedBy?.firstName, p.sharedBy?.lastName].filter(Boolean).join(' ') ||
t('list.trainerFallback');
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
useEffect(() => () => setQuery('plans', ''), [setQuery]);
const plans = data?.plans ?? [];
const q = query.toLowerCase();
const filtered = useMemo(() => {
const list = q ? plans.filter((p) => p.title.toLowerCase().includes(q)) : plans;
const byStatus = statusFilter === 'ALL' ? list : list.filter((p) => p.status === statusFilter);
return sortPlans(byStatus, sortKey);
}, [plans, q, statusFilter, sortKey]);
// plany pogrupowane według statusu (kategorie); puste kategorie są pomijane.
// wybrany konkretny status lub sortowanie → lista płaska (grupy/nagłówki
// ignorowałyby globalne sortowanie i dublowały filtr)
const groups =
statusFilter === 'ALL' && sortKey === 'default'
? STATUS_ORDER.map((status) => ({
status,
plans: filtered.filter((p) => p.status === status),
})).filter((g) => g.plans.length > 0)
: null;
// plany jawnie udostępnione (read-only) — osobna sekcja pod kategoriami statusu
const sharedPlans = sharedData?.plans ?? [];
const filteredShared = useMemo(() => {
const list = q ? sharedPlans.filter((p) => p.title.toLowerCase().includes(q)) : sharedPlans;
return sortPlans(list, sortKey);
}, [sharedPlans, q, sortKey]);
const anyOwnedResults = filtered.length > 0 || filteredShared.length > 0;
return (
<>
{isLoading && (
<div className="flex flex-col gap-4">
<Skeleton className="h-20" />
<Skeleton className="h-20" />
<Skeleton className="h-20" />
</div>
)}
{error && (
<ErrorText>
{t('list.errorPrefix')} {(error as Error).message}
</ErrorText>
)}
{data && plans.length === 0 && sharedPlans.length === 0 && (
<Card>
<EmptyState
icon={Dumbbell}
title={t('list.emptyTitle')}
description={t('list.emptyDesc')}
action={
<Link to="/plans/new">
<Button>
<CalendarPlus className="w-4 h-4" />
{t('list.newPlan')}
</Button>
</Link>
}
/>
</Card>
)}
{data && plans.length > 0 && !anyOwnedResults && (
<Card>
<p className="text-dim">{t('list.noResults')}</p>
</Card>
)}
{groups !== null &&
groups.map((g) => {
const st = PLAN_STATUS[g.status];
return (
<section key={g.status} className="mb-5">
<div className="mb-2.5 flex items-center gap-2.5">
<H3 className="mb-0">{t(`common:${st.labelKey}`)}</H3>
<Badge color={st.color}>{g.plans.length}</Badge>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{g.plans.map((p) => (
<PlanCard key={p.id} plan={p} creatorLabel={creatorLabel(p)} />
))}
</div>
</section>
);
})}
{groups === null && filtered.length > 0 && (
<section className="mb-5">
<div className="mb-2.5 flex items-center gap-2.5">
<H3 className="mb-0">
{statusFilter === 'ALL'
? t('list.allPlans')
: t(STATUS_FILTERS.find((s) => s.id === statusFilter)?.labelKey ?? 'filters.ALL')}
</H3>
<Badge color="gray">{filtered.length}</Badge>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{filtered.map((p) => (
<PlanCard key={p.id} plan={p} creatorLabel={creatorLabel(p)} />
))}
</div>
</section>
)}
{filteredShared.length > 0 && (
<section className="mb-5">
<div className="mb-2.5 flex items-center gap-2.5">
<H3 className="mb-0">{t('list.sharedSection')}</H3>
<Badge color="blue">{filteredShared.length}</Badge>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
{filteredShared.map((p) => (
<PlanCard
key={p.id}
plan={p}
creatorLabel={sharedByLabel(p)}
creatorPrefix={t('list.sharedPrefix')}
/>
))}
</div>
</section>
)}
</>
);
}

View File

@@ -0,0 +1,143 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQueryClient } from '@tanstack/react-query';
import { CalendarPlus, Plus } from 'lucide-react';
import { clonePlan, useMe, usePlanTemplates, usePlans } from '../../api/queries';
import { apiErrorMessage } from '../../lib/errors';
import { useToast } from '../../components/toast';
import { ActivePlanHero } from '../../components/plans/ActivePlanHero';
import { PlanListView, usePlanListFilters } from '../../components/plans/PlanList';
import { PlansTabs } from '../../components/plans/PlansTabs';
import { NewPlanMenu } from '../../components/plans/NewPlanMenu';
import { Button, Card, EmptyState, ErrorText, Skeleton } from '../../components/ui';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
import type { Plan } from '../../api/types';
/** Statusy pokazywane na zakładce „Aktualne” (archiwalne → osobna podstrona). */
const CURRENT_STATUSES: Plan['status'][] = ['ACTIVE', 'SUSPENDED', 'DRAFT'];
const CURRENT_GROUP_ORDER: Plan['status'][] = ['ACTIVE', 'SUSPENDED', 'DRAFT'];
export default function PlansActive() {
const { t } = useTranslation('plans');
const navigate = useNavigate();
const queryClient = useQueryClient();
const { push } = useToast();
const { filters, filterActive, statusFilter, sortKey } = usePlanListFilters('current');
const [newOpen, setNewOpen] = useState(false);
const [cloning, setCloning] = useState(false);
useTopbar({
title: t('nav:plans'),
search: 'plans',
filters,
filterActive,
actions: [{ label: t('list.newPlan'), icon: Plus, onClick: () => setNewOpen(true) }],
});
const { data, isLoading, error } = usePlans();
const { data: meData } = useMe();
const { data: templateData, isLoading: templatesLoading } = usePlanTemplates();
const query = useListSearch((s) => s.queries.plans);
const setQuery = useListSearch((s) => s.setQuery);
// wyszukiwarka jest w menu kontekstowym (Layout) — czyścimy ją przy opuszczeniu strony
useEffect(() => () => setQuery('plans', ''), [setQuery]);
/** Imię i nazwisko twórcy, gdy plan nie został utworzony przez zalogowanego. */
const creatorLabel = (p: Plan): string | null => {
if (!p.creator) return null;
if (meData?.user.id && p.creator.id === meData.user.id) return null;
return (
[p.creator.firstName, p.creator.lastName].filter(Boolean).join(' ') ||
t('list.trainerFallback')
);
};
const plans = (data?.plans ?? []).filter(
(p) => p.kind !== 'TEMPLATE' && CURRENT_STATUSES.includes(p.status),
);
// Hero = jedyny aktywny plan (inwariant DB); ukryty, gdy filtr wskazuje inną
// kategorię niż Aktywne/Wszystkie. Pozostałe (SUSPENDED/DRAFT) jako karty.
const hero =
statusFilter === 'ALL' || statusFilter === 'ACTIVE'
? (plans.find((p) => p.status === 'ACTIVE') ?? null)
: null;
const rest = hero ? plans.filter((p) => p.id !== hero.id) : plans;
const useTemplate = async (templateId: string) => {
if (cloning) return;
setCloning(true);
try {
const res = await clonePlan(templateId);
await queryClient.invalidateQueries({ queryKey: ['plans'] });
setNewOpen(false);
navigate(`/plans/${res.plan.id}/edit`);
} catch (e) {
push(apiErrorMessage(e, t, t('genericError')), 'error');
setCloning(false);
}
};
const q = query.toLowerCase();
const emptyState = (
<Card>
<EmptyState
icon={CalendarPlus}
title={t('list.emptyTitle')}
description={t('list.emptyDesc')}
action={
<Button onClick={() => setNewOpen(true)}>
<Plus className="w-4 h-4" />
{t('list.newPlan')}
</Button>
}
/>
</Card>
);
return (
<>
<PlansTabs />
{isLoading && (
<div className="flex flex-col gap-4">
<Skeleton className="h-20" />
<Skeleton className="h-20" />
<Skeleton className="h-20" />
</div>
)}
{error && (
<ErrorText>
{t('list.errorPrefix')} {(error as Error).message}
</ErrorText>
)}
{data && hero && <ActivePlanHero plan={hero} creatorLabel={creatorLabel(hero)} />}
{data && plans.length === 0 && emptyState}
{data && plans.length > 0 && (
<PlanListView
plans={rest}
q={q}
statusFilter={statusFilter}
sortKey={sortKey}
groupOrder={CURRENT_GROUP_ORDER}
emptyTitle={t('list.noResults')}
creatorLabel={creatorLabel}
/>
)}
<NewPlanMenu
open={newOpen}
onClose={() => setNewOpen(false)}
onFromScratch={() => {
setNewOpen(false);
navigate('/plans/new');
}}
onUseTemplate={(id) => void useTemplate(id)}
cloning={cloning}
templates={templateData?.templates ?? []}
templatesLoading={templatesLoading}
/>
</>
);
}

View File

@@ -0,0 +1,75 @@
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Archive } from 'lucide-react';
import { useMe, usePlans } from '../../api/queries';
import { PlanListView, usePlanListFilters } from '../../components/plans/PlanList';
import { PlansTabs } from '../../components/plans/PlansTabs';
import { ErrorText, Skeleton } from '../../components/ui';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
import type { Plan } from '../../api/types';
/** Statusy archiwum: domknięte plany (ukończone + porzucone). */
const ARCHIVE_STATUSES: Plan['status'][] = ['COMPLETED', 'ABANDONED'];
export default function PlansArchive() {
const { t } = useTranslation('plans');
const { filters, filterActive, statusFilter, sortKey } = usePlanListFilters('archive');
useTopbar({
title: t('nav:plans'),
search: 'plans',
filters,
filterActive,
});
const { data, isLoading, error } = usePlans();
const { data: meData } = useMe();
const query = useListSearch((s) => s.queries.plans);
const setQuery = useListSearch((s) => s.setQuery);
useEffect(() => () => setQuery('plans', ''), [setQuery]);
const creatorLabel = (p: Plan): string | null => {
if (!p.creator) return null;
if (meData?.user.id && p.creator.id === meData.user.id) return null;
return (
[p.creator.firstName, p.creator.lastName].filter(Boolean).join(' ') ||
t('list.trainerFallback')
);
};
const plans = (data?.plans ?? []).filter(
(p) => p.kind !== 'TEMPLATE' && ARCHIVE_STATUSES.includes(p.status),
);
const q = query.toLowerCase();
return (
<>
<PlansTabs />
{isLoading && (
<div className="flex flex-col gap-4">
<Skeleton className="h-20" />
<Skeleton className="h-20" />
</div>
)}
{error && (
<ErrorText>
{t('list.errorPrefix')} {(error as Error).message}
</ErrorText>
)}
{data && (
<PlanListView
plans={plans}
q={q}
statusFilter={statusFilter}
sortKey={sortKey}
groupOrder={ARCHIVE_STATUSES}
emptyTitle={t('archive.emptyTitle')}
emptyDesc={t('archive.emptyDesc')}
emptyIcon={Archive}
creatorLabel={creatorLabel}
/>
)}
</>
);
}

View File

@@ -0,0 +1,220 @@
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQueryClient } from '@tanstack/react-query';
import {
Archive,
CalendarClock,
ChevronRight,
FileStack,
Plus,
Share2,
Users,
type LucideIcon,
} from 'lucide-react';
import {
clonePlan,
useIsTrainer,
useMe,
usePlanTemplates,
usePlans,
useSharedByMe,
useSharedWithMe,
} from '../../api/queries';
import { apiErrorMessage } from '../../lib/errors';
import { useToast } from '../../components/toast';
import { ActivePlanHero } from '../../components/plans/ActivePlanHero';
import { NewPlanMenu } from '../../components/plans/NewPlanMenu';
import { ErrorText, Skeleton } from '../../components/ui';
import { useTopbar } from '../../topbar';
import type { Plan } from '../../api/types';
/** Kafelek kategorii: ikona, nazwa i licznik treści w środku — cały prowadzi do podstrony. */
function HubCard({
to,
icon: Icon,
title,
detail,
}: {
to: string;
icon: LucideIcon;
title: string;
detail: string;
}) {
return (
<Link
to={to}
className="group relative flex items-center gap-3.5 overflow-hidden rounded-xl border border-line bg-(image:--card-grad) p-4 pl-5 shadow-card transition-all duration-150 hover:border-accent/55"
>
<span
aria-hidden="true"
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-line bg-input text-accent-text"
>
<Icon className="h-5 w-5" />
</span>
<span className="min-w-0 flex-1">
<span className="block font-semibold transition-colors group-hover:text-accent-text">
{title}
</span>
<span className="mt-0.5 block text-dim text-[0.8125rem]">{detail}</span>
</span>
<ChevronRight
aria-hidden="true"
className="w-4 h-4 shrink-0 text-dim transition-all group-hover:translate-x-0.5 group-hover:text-accent-text"
/>
</Link>
);
}
/**
* Strona główna sekcji planów: hero aktywnego planu + kafelki kategorii
* (Aktualne / Archiwum / Szablony / Udostępnione [+ Podopieczni dla trenera]).
* Prowadzą do podstron z listami; sama strona nie wyświetla płaskiej listy planów.
*/
export default function PlansHub() {
const { t } = useTranslation('plans');
const navigate = useNavigate();
const queryClient = useQueryClient();
const { push } = useToast();
const [newOpen, setNewOpen] = useState(false);
const [cloning, setCloning] = useState(false);
useTopbar({
title: t('nav:plans'),
actions: [{ label: t('list.newPlan'), icon: Plus, onClick: () => setNewOpen(true) }],
});
const { data, isLoading, error } = usePlans();
const { data: meData } = useMe();
const isTrainer = useIsTrainer();
const { data: templateData, isLoading: templatesLoading } = usePlanTemplates();
const { data: withMeData } = useSharedWithMe();
const { data: byMeData } = useSharedByMe();
const own = (data?.plans ?? []).filter((p) => p.kind !== 'TEMPLATE');
const countBy = (...statuses: Plan['status'][]) =>
own.filter((p) => statuses.includes(p.status)).length;
const hero = own.find((p) => p.status === 'ACTIVE') ?? null;
/** Imię i nazwisko twórcy, gdy plan nie został utworzony przez zalogowanego. */
const creatorLabel = (p: Plan): string | null => {
if (!p.creator) return null;
if (meData?.user.id && p.creator.id === meData.user.id) return null;
return (
[p.creator.firstName, p.creator.lastName].filter(Boolean).join(' ') ||
t('list.trainerFallback')
);
};
const nActive = countBy('ACTIVE');
const nSuspended = countBy('SUSPENDED');
const nDraft = countBy('DRAFT');
const currentDetail =
[
nActive > 0 && t('hub.countActive', { count: nActive }),
nSuspended > 0 && t('hub.countSuspended', { count: nSuspended }),
nDraft > 0 && t('hub.countDraft', { count: nDraft }),
]
.filter(Boolean)
.join(' · ') || t('hub.emptyCurrent');
const nCompleted = countBy('COMPLETED');
const nAbandoned = countBy('ABANDONED');
const archiveDetail =
[
nCompleted > 0 && t('hub.countCompleted', { count: nCompleted }),
nAbandoned > 0 && t('hub.countAbandoned', { count: nAbandoned }),
]
.filter(Boolean)
.join(' · ') || t('hub.emptyArchive');
const nTemplates = templateData?.templates?.length ?? 0;
const templatesDetail =
nTemplates > 0 ? t('hub.countTemplates', { count: nTemplates }) : t('hub.emptyTemplates');
const nWithMe = withMeData?.plans?.length ?? 0;
const nByMe = byMeData?.plans?.length ?? 0;
const sharedDetail =
[
nWithMe > 0 && t('hub.sharedWithMe', { count: nWithMe }),
nByMe > 0 && t('hub.sharedByMe', { count: nByMe }),
]
.filter(Boolean)
.join(' · ') || t('hub.emptyShared');
const useTemplate = async (templateId: string) => {
if (cloning) return;
setCloning(true);
try {
const res = await clonePlan(templateId);
await queryClient.invalidateQueries({ queryKey: ['plans'] });
setNewOpen(false);
navigate(`/plans/${res.plan.id}/edit`);
} catch (e) {
push(apiErrorMessage(e, t, t('genericError')), 'error');
setCloning(false);
}
};
return (
<>
{isLoading && (
<div className="flex flex-col gap-4">
<Skeleton className="h-20" />
<Skeleton className="h-24" />
</div>
)}
{error && (
<ErrorText>
{t('list.errorPrefix')} {(error as Error).message}
</ErrorText>
)}
{data && hero && <ActivePlanHero plan={hero} creatorLabel={creatorLabel(hero)} />}
{data && !hero && <p className="mb-5 text-dim">{t('hub.intro')}</p>}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<HubCard
to="/plans/current"
icon={CalendarClock}
title={t('tabs.active')}
detail={currentDetail}
/>
<HubCard
to="/plans/archive"
icon={Archive}
title={t('tabs.archive')}
detail={archiveDetail}
/>
<HubCard
to="/plans/templates"
icon={FileStack}
title={t('tabs.templates')}
detail={templatesDetail}
/>
<HubCard to="/plans/shared" icon={Share2} title={t('tabs.shared')} detail={sharedDetail} />
{isTrainer && (
<HubCard
to="/trainees"
icon={Users}
title={t('hub.traineesCard')}
detail={t('hub.traineesCardDesc')}
/>
)}
</div>
<NewPlanMenu
open={newOpen}
onClose={() => setNewOpen(false)}
onFromScratch={() => {
setNewOpen(false);
navigate('/plans/new');
}}
onUseTemplate={(id) => void useTemplate(id)}
cloning={cloning}
templates={templateData?.templates ?? []}
templatesLoading={templatesLoading}
/>
</>
);
}

View File

@@ -0,0 +1,126 @@
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Share2 } from 'lucide-react';
import { useSharedByMe, useSharedWithMe } from '../../api/queries';
import { H3, Badge, Card, EmptyState, ErrorText, Skeleton } from '../../components/ui';
import { PlansTabs } from '../../components/plans/PlansTabs';
import { PlanCard } from '../../components/plans/PlanCard';
import { useListSearch } from '../../store/list-search';
import { useTopbar } from '../../topbar';
import type { Plan, SharedByMePlan } from '../../api/types';
/** Sekcja kart: nagłówek z licznikiem + siatka kart planów. */
function Section({
title,
count,
children,
}: {
title: string;
count: number;
children: React.ReactNode;
}) {
return (
<section className="mb-5">
<div className="mb-2.5 flex items-center gap-2.5">
<H3 className="mb-0">{title}</H3>
<Badge color="blue">{count}</Badge>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">{children}</div>
</section>
);
}
export default function PlansShared() {
const { t } = useTranslation('plans');
useTopbar({
title: t('nav:plans'),
search: 'plans',
});
const { data: withMeData, isLoading: withMeLoading, error: withMeError } = useSharedWithMe();
const { data: byMeData, isLoading: byMeLoading, error: byMeError } = useSharedByMe();
const query = useListSearch((s) => s.queries.plans);
const setQuery = useListSearch((s) => s.setQuery);
useEffect(() => () => setQuery('plans', ''), [setQuery]);
const sharedWithMe: Plan[] = withMeData?.plans ?? [];
const sharedByMe: SharedByMePlan[] = byMeData?.plans ?? [];
const q = query.toLowerCase();
const filteredWithMe = q
? sharedWithMe.filter((p) => p.title.toLowerCase().includes(q))
: sharedWithMe;
const filteredByMe = q ? sharedByMe.filter((p) => p.title.toLowerCase().includes(q)) : sharedByMe;
const sharedByLabel = (p: Plan): string =>
[p.sharedBy?.firstName, p.sharedBy?.lastName].filter(Boolean).join(' ') ||
t('list.trainerFallback');
const loading = withMeLoading || byMeLoading;
return (
<>
<PlansTabs />
{loading && (
<div className="flex flex-col gap-4">
<Skeleton className="h-20" />
<Skeleton className="h-20" />
</div>
)}
{(withMeError || byMeError) && (
<ErrorText>
{t('list.errorPrefix')} {((withMeError ?? byMeError) as Error).message}
</ErrorText>
)}
{!loading && sharedWithMe.length === 0 && sharedByMe.length === 0 && (
<Card>
<EmptyState
icon={Share2}
title={t('shared.emptyTitle')}
description={t('shared.emptyDesc')}
/>
</Card>
)}
{filteredWithMe.length > 0 && (
<Section title={t('shared.sectionWithMe')} count={filteredWithMe.length}>
{filteredWithMe.map((p) => (
<PlanCard
key={p.id}
plan={p}
creatorLabel={sharedByLabel(p)}
creatorPrefix={t('list.sharedPrefix')}
/>
))}
</Section>
)}
{filteredByMe.length > 0 && (
<Section title={t('shared.sectionByMe')} count={filteredByMe.length}>
{filteredByMe.map((p) => (
<PlanCard
key={p.id}
plan={p}
creatorLabel={
[p.sharedWith.firstName, p.sharedWith.lastName].filter(Boolean).join(' ') ||
t('dialog.userFallback')
}
creatorPrefix={t('shared.withPrefix')}
/>
))}
</Section>
)}
{!loading &&
(sharedWithMe.length > 0 || sharedByMe.length > 0) &&
filteredWithMe.length === 0 &&
filteredByMe.length === 0 && (
<Card>
<p className="text-dim">{t('list.noResults')}</p>
</Card>
)}
</>
);
}

View File

@@ -27,6 +27,7 @@ export function PlanMetaForm({
startDateLocked = false,
changeNote,
onSetChangeNote,
templateMode = false,
}: {
title: string;
onTitleChange: (v: string) => void;
@@ -50,12 +51,16 @@ export function PlanMetaForm({
/** Notatka audytowa (tylko plan ACTIVE); opcjonalna — brak = historia bez „dlaczego”. */
changeNote?: string;
onSetChangeNote?: (v: string) => void;
/** Tryb szablonu: meta bez siłowni i bez tygodnia startu (szablon nie ma startu). */
templateMode?: boolean;
}) {
const { t } = useTranslation('plans');
return (
<>
<Card>
<div className="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-3">
<div
className={`grid grid-cols-1 gap-x-4 gap-y-3 ${templateMode ? 'sm:grid-cols-2' : 'sm:grid-cols-3'}`}
>
<Field
label={t('meta.title')}
labelIcon={<Tag className="h-3.5 w-3.5" />}
@@ -96,26 +101,28 @@ export function PlanMetaForm({
))}
</Select>
</Field>
<Field
label={t('meta.gym')}
labelIcon={<CircleSlash className="h-3.5 w-3.5" />}
className="mb-0"
>
{gymOptions.length > 0 ? (
<Select value={gymId ?? ''} onChange={(e) => onGymIdChange(e.target.value || null)}>
<option value="">{t('meta.noGym')}</option>
{gymOptions.map((g) => (
<option key={g.id} value={g.id}>
{g.name}
</option>
))}
</Select>
) : (
<p className="py-1 text-dim text-[0.875rem]">{noGymNotice}</p>
)}
</Field>
{!templateMode && (
<Field
label={t('meta.gym')}
labelIcon={<CircleSlash className="h-3.5 w-3.5" />}
className="mb-0"
>
{gymOptions.length > 0 ? (
<Select value={gymId ?? ''} onChange={(e) => onGymIdChange(e.target.value || null)}>
<option value="">{t('meta.noGym')}</option>
{gymOptions.map((g) => (
<option key={g.id} value={g.id}>
{g.name}
</option>
))}
</Select>
) : (
<p className="py-1 text-dim text-[0.875rem]">{noGymNotice}</p>
)}
</Field>
)}
</div>
{onSetChangeNote && (
{!templateMode && onSetChangeNote && (
<div className="mt-4">
<Field label={t('meta.changeNoteLabel')}>
<textarea
@@ -132,31 +139,33 @@ export function PlanMetaForm({
)}
</Card>
<Card>
{startDateLocked ? (
<>
<Field label={t('detail.startWeekLabel')}>
<p className="rounded-[10px] border border-line bg-input px-3 py-2 text-[0.9rem]">
{startDate ? fmtDate(startDate) : '—'}
{!templateMode && (
<Card>
{startDateLocked ? (
<>
<Field label={t('detail.startWeekLabel')}>
<p className="rounded-[10px] border border-line bg-input px-3 py-2 text-[0.9rem]">
{startDate ? fmtDate(startDate) : '—'}
</p>
<p className="mt-1.5 text-dim text-[0.8125rem]">{t('meta.startDateLockedHint')}</p>
</Field>
<p className="mt-1 flex items-start gap-2 text-dim text-[0.875rem]">
<Info className="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
{t('meta.editActiveHint')}
</p>
<p className="mt-1.5 text-dim text-[0.8125rem]">{t('meta.startDateLockedHint')}</p>
</Field>
<p className="mt-1 flex items-start gap-2 text-dim text-[0.875rem]">
<Info className="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
{t('meta.editActiveHint')}
</p>
</>
) : (
<>
<WeekPicker value={startDate} onChange={onStartDateChange} />
{startWeekError && (
<div className="mt-3">
<ErrorText>{startWeekError}</ErrorText>
</div>
)}
</>
)}
</Card>
</>
) : (
<>
<WeekPicker value={startDate} onChange={onStartDateChange} />
{startWeekError && (
<div className="mt-3">
<ErrorText>{startWeekError}</ErrorText>
</div>
)}
</>
)}
</Card>
)}
</>
);
}

View File

@@ -9,35 +9,49 @@ import {
} from '../../../lib/labels';
import { dayName, fmtDate } from '../../../lib/format';
import { displayedDaysOf, type EditorWeek } from './types';
import { WeekVolumeMeter, type VolumeRange } from './WeekVolumeMeter';
/**
* Krok 3 wizarda: przejrzysty przegląd całego planu przed zapisem.
* Puste tygodnie nie blokują zapisu — są oznaczone ostrzeżeniem.
* `ranges` + `muscleOf` włączają miernik objętości per tydzień (frontend-only).
*/
export function PlanSummary({
title,
gymName,
startDate,
weeks,
ranges,
muscleOf,
templateMode = false,
}: {
title: string;
gymName: string | null;
/** '' = szkic bez tygodnia startu. */
startDate: string;
weeks: EditorWeek[];
/** Zakresy tygodniowe partii (FocusArea) — miernik objętości. */
ranges?: Map<string, VolumeRange>;
/** Partia mięśniowa ćwiczenia po id z katalogu. */
muscleOf?: (exerciseId: string) => string | undefined;
/** Tryb szablonu: bez siłowni i startu (szablon ich nie ma). */
templateMode?: boolean;
}) {
const { t } = useTranslation('plans');
const rows = weeks.map((w, i) => {
const days = displayedDaysOf(weeks, i);
let exercises = 0;
let sets = 0;
const counts = new Map<string, number>();
days.forEach((d) => {
exercises += d.exercises.length;
d.exercises.forEach((e) => {
sets += e.sets.length;
const m = muscleOf?.(e.exerciseId);
if (m) counts.set(m, (counts.get(m) ?? 0) + e.sets.length);
});
});
return { i, alias: w.customName.trim(), days, exercises, sets };
return { i, alias: w.customName.trim(), days, exercises, sets, counts };
});
const totals = rows.reduce(
(acc, r) => ({
@@ -52,17 +66,19 @@ export function PlanSummary({
return (
<Card>
<H2>{title || t('summary.noTitle')}</H2>
<div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-dim text-[0.875rem]">
<span className="inline-flex items-center gap-1.5">
<MapPin className="w-4 h-4" />
{gymName ?? t('summary.noGymLower')}
</span>
<span>
{startDate
? `${t('detail.startPrefix')} ${fmtDate(startDate)}`
: t('summary.draftNoStart')}
</span>
</div>
{!templateMode && (
<div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-dim text-[0.875rem]">
<span className="inline-flex items-center gap-1.5">
<MapPin className="w-4 h-4" />
{gymName ?? t('summary.noGymLower')}
</span>
<span>
{startDate
? `${t('detail.startPrefix')} ${fmtDate(startDate)}`
: t('summary.draftNoStart')}
</span>
</div>
)}
<div className="mt-4 divide-y divide-line">
{rows.map((r) => (
@@ -78,6 +94,7 @@ export function PlanSummary({
{setCountLabel(r.sets)}
</span>
</div>
{ranges && <WeekVolumeMeter counts={r.counts} ranges={ranges} className="mt-1.5" />}
</div>
))}
</div>

View File

@@ -0,0 +1,61 @@
import { useTranslation } from 'react-i18next';
import { cn } from '../../../lib/utils';
import { muscleName } from '../../../lib/labels';
export interface VolumeRange {
min: number;
max: number;
}
/**
* Miernik objętości w edytorze (frontend-only): serie per mięsień w tygodniu
* ze stanu edytora vs. zalecane zakresy tygodniowe priorytetów (FocusArea).
* Progi identyczne jak w raporcie trenera: poniżej min = niedobór,
* powyżej max * 1.1 = nadmiar.
*/
export function WeekVolumeMeter({
counts,
ranges,
className,
}: {
counts: Map<string, number>;
ranges: Map<string, VolumeRange>;
className?: string;
}) {
const { t } = useTranslation('plans');
const muscles = [...counts.entries()].filter(([, sets]) => sets > 0);
if (muscles.length === 0) return null;
return (
<div className={cn('mt-3 flex flex-wrap items-center gap-1.5', className)}>
<span className="text-[0.75rem] font-semibold text-dim">{t('meter.title')}:</span>
{muscles.map(([muscle, sets]) => {
const range = ranges.get(muscle);
const below = range != null && sets < range.min;
const over = range != null && sets > range.max * 1.1;
return (
<span
key={muscle}
title={
range
? `${muscleName(muscle)}: ${t('meter.weekly')} ${sets} · ${range.min}–${range.max}`
: `${muscleName(muscle)}: ${t('meter.weekly')} ${sets}`
}
className={cn(
'rounded-full border px-2 py-0.5 text-[0.75rem] font-medium tabular-nums',
below
? 'border-danger/40 bg-danger/10 text-danger'
: over
? 'border-warn/40 bg-warn/10 text-warn'
: range
? 'border-accent/40 bg-accent/10 text-accent-text'
: 'border-line text-dim',
)}
>
{muscleName(muscle)} {sets}
{range ? ` · ${range.min}–${range.max}` : ''}
</span>
);
})}
</div>
);
}

View File

@@ -4,6 +4,7 @@ import { muscleName } from '../../../lib/labels';
import { localizedName } from '../../../lib/localizedName';
import ExerciseProgressCards from '../../../components/ExerciseProgressCards';
import ExerciseReportTable from '../../../components/ExerciseReportTable';
import { VolumeRanges } from '../../../components/plans/VolumeRanges';
import { Badge, Card, ErrorText, Loading, SectionHeader } from '../../../components/ui';
import type { ExerciseReport, TraineeReport } from '../../../api/types';
@@ -51,75 +52,7 @@ export function ProgressTab({ userId, report, reportLoading, reportError }: Prog
<p className="text-dim">{t('noPlanReport')}</p>
)}
{!reportLoading && !reportError && (report?.muscles ?? []).length > 0 && (
<div className="flex flex-col gap-3">
{(report?.muscles ?? []).map((m) => {
const scaleMax = Math.max(
m.planned.sets,
m.actual.sets,
m.recommendedRange?.setsMax ?? 0,
1,
);
const pct = Math.min(100, Math.round((m.actual.sets / scaleMax) * 100));
const tone = !m.recommendedRange
? 'bg-info'
: m.actual.sets < m.recommendedRange.setsMin
? 'bg-danger'
: m.actual.sets > m.recommendedRange.setsMax * 1.1
? 'bg-warn'
: 'bg-(image:--progress-grad)';
return (
<div key={m.muscle}>
<div className="grid grid-cols-[92px_1fr_auto] items-center gap-3 text-[0.8125rem]">
<span className="min-w-0 truncate font-semibold">{muscleName(m.muscle)}</span>
<div
className="relative h-2 overflow-hidden rounded-full bg-input"
title={`${t('planWord')} ${m.planned.sets} · ${t('doneWord')} ${m.actual.sets}${
m.recommendedRange
? ` · ${t('rangeWord')} ${m.recommendedRange.setsMin}–${m.recommendedRange.setsMax}`
: ''
}`}
>
{m.recommendedRange && (
<div
className="absolute inset-y-0 bg-line"
style={{
left: `${(m.recommendedRange.setsMin / scaleMax) * 100}%`,
width: `${
((m.recommendedRange.setsMax - m.recommendedRange.setsMin) /
scaleMax) *
100
}%`,
}}
/>
)}
<div className={`h-full rounded-full ${tone}`} style={{ width: `${pct}%` }} />
</div>
<span className="shrink-0 text-dim tabular-nums">
{m.actual.sets}/{m.planned.sets}
{m.recommendedRange
? ` · ${m.recommendedRange.setsMin}–${m.recommendedRange.setsMax}`
: ''}
</span>
</div>
{(m.extra.sets > 0 || m.missing.sets > 0 || m.outOfRange) && (
<div className="mt-1 flex flex-wrap items-center gap-1.5 sm:pl-[104px]">
{m.extra.sets > 0 && (
<Badge color="green">
+{m.extra.sets} {t('excessWord')}
</Badge>
)}
{m.missing.sets > 0 && (
<Badge color="red">
-{m.missing.sets} {t('deficitWord')}
</Badge>
)}
{m.outOfRange && <Badge color="yellow">{t('outOfRange')}</Badge>}
</div>
)}
</div>
);
})}
</div>
<VolumeRanges muscles={report?.muscles ?? []} />
)}
</Card>

View File

@@ -208,6 +208,9 @@ async function loginAndOpenPlans(user: userEvent.User, email: string) {
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: 'Plany treningowe' }));
expect(await screen.findByRole('heading', { name: 'Plany treningowe' })).toBeInTheDocument();
// hub sekcji → kategoria „Aktualne” (lista z zakładkami)
await user.click(await screen.findByRole('link', { name: /^Aktualne/ }));
expect(await screen.findByRole('button', { name: 'Archiwum' })).toBeInTheDocument();
}
beforeEach(async () => {
@@ -292,9 +295,10 @@ describe('PlanDetail — udostępnianie planów (WP4)', () => {
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, RECIPIENT.email);
await user.click(screen.getByRole('button', { name: 'Udostępnione' }));
// sekcja „Udostępnione mi” z etykietą twórcy
expect(screen.getByRole('heading', { name: 'Udostępnione mi' })).toBeInTheDocument();
expect(await screen.findByRole('heading', { name: 'Udostępnione mi' })).toBeInTheDocument();
expect(screen.getByText('udostępnił: Jan Kowalski')).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
@@ -403,8 +407,9 @@ describe('PlanDetail — statusy i klikalność dni', () => {
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('button', { name: 'Archiwum' }));
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
await user.click(await screen.findByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
const header = document.querySelector('header')!;
@@ -427,8 +432,9 @@ describe('PlanDetail — statusy i klikalność dni', () => {
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('button', { name: 'Archiwum' }));
await user.click(screen.getByRole('link', { name: /Plan masowy/ }));
await user.click(await screen.findByRole('link', { name: /Plan masowy/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
const header = document.querySelector('header')!;
@@ -504,8 +510,9 @@ describe('PlanDetail — statusy i klikalność dni', () => {
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('button', { name: 'Archiwum' }));
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
await user.click(await screen.findByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
const header = document.querySelector('header')!;

View File

@@ -148,6 +148,9 @@ async function loginAndOpenNewPlan(user: userEvent.User) {
// „Nowy plan” pojawia się w menu kontekstowym i w pustym stanie listy — klikamy pierwsze (menu)
await user.click(screen.getAllByRole('button', { name: 'Nowy plan' })[0]);
expect(await screen.findByRole('heading', { name: 'Nowy plan' })).toBeInTheDocument();
// picker ofert: właściwy kreator otwiera się dopiero po „Od zera”
await user.click(screen.getByRole('button', { name: 'Od zera' }));
expect(await screen.findByPlaceholderText('np. Plan masowy 8-tygodniowy')).toBeInTheDocument();
}
/* Komórka serii to picker kółkowy — testy wpisują wartość deterministycznie
@@ -775,7 +778,9 @@ async function loginAndOpenEditor(user: userEvent.User, planTitle = 'Plan w trak
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: 'Plany treningowe' }));
expect(await screen.findByRole('heading', { name: 'Plany treningowe' })).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
// hub sekcji → kategoria „Aktualne” (lista/hero planów)
await user.click(await screen.findByRole('link', { name: /^Aktualne/ }));
await user.click(await screen.findByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: planTitle })).toBeInTheDocument();
// akcja „Edytuj” w topmenu (PlanDetail) prowadzi do edytora
await user.click(

View File

@@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react';
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
@@ -27,6 +27,13 @@ const USER: User = {
createdAt: '2026-08-22T10:00:00.000Z',
};
const todayIso = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
d.getDate(),
).padStart(2, '0')}`;
};
const PLANS: Plan[] = [
{
id: 'plan-1',
@@ -35,6 +42,9 @@ const PLANS: Plan[] = [
status: 'ACTIVE',
weeksCount: 8,
startDate: '2026-08-24',
progress: { completed: 5, total: 10, percent: 50 },
currentWeek: 2,
nextDay: { date: '2026-11-20', dayOfWeek: 5, exerciseCount: 4 },
weeks: [],
},
{
@@ -81,6 +91,8 @@ function mockApi(plans: Plan[] = PLANS) {
});
if (url.includes('/exercises')) return jsonResponse(200, { exercises: [] });
if (url.includes('/plans/shared-with-me')) return jsonResponse(200, { plans: [] });
if (url.includes('/plans/shared-by-me')) return jsonResponse(200, { plans: [] });
if (url.includes('/plans/templates')) return jsonResponse(200, { templates: [] });
if (url.includes('/plans')) return jsonResponse(200, { plans });
if (url.includes('/calendar')) return jsonResponse(200, { month: '2026-08', days: [] });
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
@@ -113,6 +125,13 @@ async function openPlans(user: userEvent.User) {
expect(await screen.findByRole('heading', { name: 'Plany treningowe' })).toBeInTheDocument();
}
/** Hub → kategoria „Aktualne” (podstrona z listą i zakładkami). */
async function openCurrentPlans(user: userEvent.User) {
await openPlans(user);
await user.click(await screen.findByRole('link', { name: /^Aktualne/ }));
expect(await screen.findByRole('button', { name: 'Archiwum' })).toBeInTheDocument();
}
beforeEach(() => {
setAccessToken(null);
useAuth.setState({ user: null, ready: false });
@@ -123,80 +142,190 @@ afterEach(() => {
useAuth.setState({ user: null, ready: false });
});
describe('Lista planów', () => {
it('grupuje plany według statusu w sekcje z licznikiem', async () => {
describe('Strona główna sekcji planów (/plans)', () => {
it('kafelki kategorii z licznikami prowadzą do podstron', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
// sekcje kategorii (statusów) z licznikami
expect(screen.getByRole('heading', { name: 'Aktywny' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Szkic' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Ukończony' })).toBeInTheDocument();
// kategoria bez planów nie jest renderowana
expect(screen.queryByRole('heading', { name: 'Porzucony' })).not.toBeInTheDocument();
const current = await screen.findByRole('link', { name: /^Aktualne/ });
expect(current).toHaveAttribute('href', '/plans/current');
expect(within(current).getByText(/1 aktywny · 1 szkic/)).toBeInTheDocument();
const archive = screen.getByRole('link', { name: /^Archiwum/ });
expect(within(archive).getByText('1 ukończony')).toBeInTheDocument();
const templates = screen.getByRole('link', { name: /^Szablony/ });
expect(within(templates).getByText('Brak szablonów')).toBeInTheDocument();
const shared = screen.getByRole('link', { name: /^Udostępnione/ });
expect(within(shared).getByText('Brak udostępnień')).toBeInTheDocument();
// płaska lista stanów zniknęła z indeksu — są tylko kafelki
expect(screen.queryByRole('link', { name: /Szkic siłowy/ })).not.toBeInTheDocument();
await user.click(archive);
expect(await screen.findByRole('heading', { name: 'Ukończony' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Aktualne' })).toBeInTheDocument();
});
it('aktywny plan eksponowany jako hero także na stronie głównej', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
const hero = await screen.findByRole('link', { name: /Plan masowy/ });
expect(hero).toHaveAttribute('href', '/plans/plan-1');
expect(within(hero).getByText('Następny trening:')).toBeInTheDocument();
});
it('akcja „Nowy plan” dostępna też na stronie głównej', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
await user.click(await screen.findByRole('button', { name: 'Nowy plan' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('Zacznij od zera albo skopiuj gotowy szablon.')).toBeInTheDocument();
});
});
describe('Podstrona „Aktualne” (/plans/current)', () => {
it('renderuje zakładki sekcji planów', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
expect(screen.getByRole('button', { name: 'Aktualne' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Archiwum' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Szablony' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Udostępnione' })).toBeInTheDocument();
});
it('aktywny plan jest hero: postęp dni, „Tydzień X z Y”, następny trening', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
const hero = await screen.findByRole('link', { name: /Plan masowy/ });
expect(hero).toHaveAttribute('href', '/plans/plan-1');
expect(within(hero).getByText('Tydzień 2 z 8')).toBeInTheDocument();
expect(within(hero).getByText('5/10 dni')).toBeInTheDocument();
expect(within(hero).getByText('Następny trening:')).toBeInTheDocument();
// piątek, przyszła data + liczba ćwiczeń
expect(within(hero).getByText('Piątek · 20.11.2026')).toBeInTheDocument();
expect(within(hero).getByText('4 ćwiczenia')).toBeInTheDocument();
});
it('gdy następny trening wypada dziś — hero pokazuje etykietę „dziś”', async () => {
const withToday: Plan[] = [
{
...PLANS[0],
nextDay: { date: todayIso(), dayOfWeek: ((new Date().getDay() + 6) % 7) + 1, exerciseCount: 2 },
},
PLANS[1],
];
mockApi(withToday);
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
const hero = await screen.findByRole('link', { name: /Plan masowy/ });
expect(within(hero).getByText(/dziś/)).toBeInTheDocument();
});
it('bez planu ACTIVE — brak hero; archiwalne plany znikają z listy', async () => {
mockApi([PLANS[1], PLANS[2]]);
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
expect(screen.getByRole('link', { name: /Szkic siłowy/ })).toBeInTheDocument();
expect(screen.queryByText('Następny trening:')).not.toBeInTheDocument();
expect(screen.queryByText('Tydzień 2 z 8')).not.toBeInTheDocument();
// ukończony plan należy do archiwum, nie do „Aktualnych”
expect(screen.queryByRole('link', { name: /Plan definicyjny/ })).not.toBeInTheDocument();
});
it('archiwum: zakładka pokazuje COMPLETED i ABANDONED', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
await user.click(screen.getByRole('button', { name: 'Archiwum' }));
expect(await screen.findByRole('heading', { name: 'Ukończony' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Plan definicyjny/ })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: /Plan masowy/ })).not.toBeInTheDocument();
});
it('każdy kafelek jest linkiem otwierającym szczegóły planu', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
await openCurrentPlans(user);
// kafelek = link o href /plans/{id} (pełni funkcję przycisku „otwórz”)
const tile = screen.getByRole('link', { name: /Plan masowy/ });
expect(tile).toHaveAttribute('href', '/plans/plan-1');
const tile = await screen.findByRole('link', { name: /Szkic siłowy/ });
expect(tile).toHaveAttribute('href', '/plans/plan-2');
expect(tile).toHaveTextContent('Otwórz');
expect(tile).toHaveTextContent('8 tyg.');
expect(tile).toHaveTextContent('4 tyg.');
});
it('pusty stan pokazuje komunikat i akcję „Nowy plan”', async () => {
mockApi([]);
const user = userEvent.setup();
renderApp();
await openPlans(user);
await openCurrentPlans(user);
expect(screen.getByRole('heading', { name: 'Brak planów' })).toBeInTheDocument();
// akcja „Nowy plan” w topbarze i w pustym stanie
expect(await screen.findByRole('heading', { name: 'Brak planów' })).toBeInTheDocument();
// akcja „Nowy plan”: topbar + pusty stan
expect(screen.getAllByRole('button', { name: 'Nowy plan' }).length).toBeGreaterThan(0);
});
it('„Nowy plan” otwiera wybór: od zera albo z szablonu', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
await user.click(await screen.findByRole('button', { name: 'Nowy plan' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('Zacznij od zera albo skopiuj gotowy szablon.')).toBeInTheDocument();
await user.click(within(dialog).getByRole('button', { name: 'Od zera' }));
expect(await screen.findByRole('heading', { name: 'Nowy plan' })).toBeInTheDocument();
});
it('filtr statusu z menu kontekstowego pokazuje tylko daną kategorię', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
await openCurrentPlans(user);
await user.click(screen.getByRole('button', { name: /Status:/ }));
await user.click(await screen.findByRole('button', { name: /Status:/ }));
await user.click(await screen.findByRole('button', { name: 'Szkice' }));
// lista płaska wybranej kategorii: tylko szkic, bez nagłówków pozostałych kategorii
// lista płaska wybranej kategorii: tylko szkic, hero aktywnego znika
expect(screen.getByRole('link', { name: /Szkic siłowy/ })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: /Plan masowy/ })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Aktywny' })).not.toBeInTheDocument();
expect(screen.queryByRole('heading', { name: 'Ukończony' })).not.toBeInTheDocument();
expect(screen.queryByText('Następny trening:')).not.toBeInTheDocument();
});
it('sortowanie nazwą A→Z (menu kontekstowe) porządkuje listę i przechodzi na płaską', async () => {
it('sortowanie nazwą A→Z porządkuje listę płaską (bez hero)', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
await openCurrentPlans(user);
const tileOrder = () =>
Array.from(document.querySelectorAll('a[href^="/plans/plan-"]')).map((a) =>
a.getAttribute('href'),
);
// domyślnie: grupowanie po statusie (Aktywny → Szkic → Ukończony)
expect(tileOrder()).toEqual(['/plans/plan-1', '/plans/plan-2', '/plans/plan-3']);
await user.click(screen.getByRole('button', { name: /Sortuj:/ }));
await user.click(await screen.findByRole('button', { name: /Sortuj:/ }));
await user.click(await screen.findByRole('button', { name: 'Nazwa A→Z' }));
// sortowanie globalne wymaga listy płaskiej: Plan definicyjny, Plan masowy, Szkic siłowy
expect(tileOrder()).toEqual(['/plans/plan-3', '/plans/plan-1', '/plans/plan-2']);
expect(screen.queryByRole('heading', { name: 'Aktywny' })).not.toBeInTheDocument();
// sortowanie globalne = lista płaska: Plan masowy, Szkic siłowy (aktywny traci hero)
const tiles = Array.from(document.querySelectorAll('a[href^="/plans/plan-"]')).map((a) =>
a.getAttribute('href'),
);
expect(tiles).toEqual(['/plans/plan-1', '/plans/plan-2']);
expect(screen.getByRole('heading', { name: 'Wszystkie plany' })).toBeInTheDocument();
});
});

View File

@@ -54,6 +54,8 @@ export const TEST_FOCUS_AREAS = [
name: 'Klatka piersiowa',
muscle: 'chest',
description: 'Wyciskanie, rozpiętki, pompki.',
setsMin: 12,
setsMax: 20,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
@@ -62,11 +64,46 @@ export const TEST_FOCUS_AREAS = [
name: 'Nogi',
muscle: 'legs',
description: 'Przysiady, wykroki.',
setsMin: 10,
setsMax: 18,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
];
/** Domyślna objętość planu (GET /plans/:id/volume) — partie z priorytetów. */
export const TEST_PLAN_VOLUME = {
plan: {
id: 'plan-v',
title: 'Plan objętości',
weeksCount: 4,
startDate: '2026-10-05',
status: 'ACTIVE',
},
muscles: [
{
muscle: 'chest',
planned: { sets: 48, reps: 480 },
actual: { sets: 40, reps: 400 },
extra: { sets: 4 },
missing: { sets: 8 },
completionPct: 83,
recommendedRange: { setsMin: 48, setsMax: 80 },
outOfRange: true,
},
{
muscle: 'legs',
planned: { sets: 32, reps: 320 },
actual: { sets: 34, reps: 340 },
extra: { sets: 2 },
missing: { sets: 0 },
completionPct: 100,
recommendedRange: { setsMin: 40, setsMax: 72 },
outOfRange: false,
},
],
};
export const TEST_FOCUS_CHAIN = {
develop: [
{ muscle: 'chest', name: 'Klatka piersiowa', exercises: [{ id: 'pz-2', name: 'Wyciskanie' }] },
@@ -1299,6 +1336,14 @@ export interface MockApiOptions {
myGyms?: unknown;
/** Ciało odpowiedzi GET /plans/shared-with-me (domyślnie: brak udostępnionych planów). */
sharedWithMe?: unknown;
/** Ciało odpowiedzi GET /plans/shared-by-me (domyślnie: brak planów udostępnionych przeze mnie). */
sharedByMe?: unknown;
/** Ciało odpowiedzi GET /plans/templates (domyślnie: brak szablonów). */
planTemplates?: unknown;
/** Ciało odpowiedzi GET /plans/templates/:id (domyślnie: 404). */
planTemplateDetail?: unknown;
/** Ciało odpowiedzi GET /plans/:id/volume (domyślnie: TEST_PLAN_VOLUME). */
planVolume?: unknown;
/** Ciało odpowiedzi GET /me/trainers (domyślnie: brak trenerów). */
myTrainers?: unknown;
/** Ciało odpowiedzi GET /me/history (domyślnie: myHistoryBody; honoruje ?month=). */
@@ -1359,6 +1404,10 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
gymInvitations = { invitations: [] },
myGyms,
sharedWithMe,
sharedByMe,
planTemplates,
planTemplateDetail,
planVolume,
myTrainers,
history,
myStats,
@@ -1635,6 +1684,55 @@ export function mockApi(page: Page, opts: MockApiOptions = {}) {
body: JSON.stringify(sharedWithMe ?? { plans: [] }),
}),
);
page.route('**/api/v1/plans/shared-by-me', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(sharedByMe ?? { plans: [] }),
}),
);
// ---------- szablony planów (kind=TEMPLATE) ----------
page.route('**/api/v1/plans/templates/*', (route) =>
planTemplateDetail
? route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(planTemplateDetail),
})
: route.fulfill({
status: 404,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'NOT_FOUND', message: 'Plan template not found' } }),
}),
);
page.route('**/api/v1/plans/templates', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(planTemplates ?? { templates: [] }),
}),
);
page.route('**/api/v1/plans/*/clone', (route) =>
route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ plan: { id: 'plan-cloned', title: 'Plan e2e', status: 'DRAFT' } }),
}),
);
page.route('**/api/v1/plans/*/as-template', (route) =>
route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ plan: { id: 'tpl-new', title: 'Plan e2e', status: 'DRAFT' } }),
}),
);
page.route('**/api/v1/plans/*/volume', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(planVolume ?? TEST_PLAN_VOLUME),
}),
);
page.route('**/api/v1/me/trainers', (route) =>
route.fulfill({
status: 200,
@@ -2983,6 +3081,15 @@ export function mockTraineePlans(page: Page, opts: MockApiOptions = {}) {
body: JSON.stringify({ plans: TEST_TRAINEE_PLANS }),
});
});
// POST /trainer/trainees/:id/plans/from-template/:templateId — klon szablonu trenera.
// Rejestrowany po wildcardzie plans/* — ma pierwszeństwo (odwrotna kolejność rejestracji).
page.route('**/api/v1/trainer/trainees/*/plans/from-template/*', (route) =>
route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ plan: { id: 'tp-from-tpl', title: 'Plan e2e', status: 'DRAFT' } }),
}),
);
}
/**

View File

@@ -12,6 +12,7 @@ async function login(page: Page) {
async function openNewPlan(page: Page) {
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Od zera' }).click();
await expect(page.getByRole('heading', { name: 'Nowy plan' })).toBeVisible();
}

View File

@@ -18,8 +18,10 @@ async function openNewPlan(page: Page) {
await page.getByRole('button', { name: 'Otwórz menu' }).click();
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await expect(page.getByRole('heading', { name: 'Plany treningowe' })).toBeVisible();
// akcja „Nowy plan” (Link w grupie „Dodawanie”, nie CTA z topbara)
await page.getByRole('link', { name: 'Nowy plan' }).click();
// akcja „Nowy plan” (modal: od zera albo z szablonu) — na telefonie z grupy „Dodawanie”
await page.getByRole('button', { name: 'Dodawanie' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).click();
await page.getByRole('button', { name: 'Od zera' }).click();
await expect(page.getByRole('heading', { name: 'Nowy plan' })).toBeVisible();
}

View File

@@ -104,6 +104,8 @@ test('„Udostępnione mi”: plan read-only — bez akcji statusowych, „Udost
await login(page);
await page.getByRole('link', { name: 'Plany treningowe' }).click();
// sekcja udostępnień mieszka na osobnej podstronie — kafelek „Udostępnione” w hubie
await page.getByRole('link', { name: /^Udostępnione/ }).click();
await expect(page.getByRole('heading', { name: 'Udostępnione mi' })).toBeVisible();
await expect(page.getByText('udostępnił: Jan Kowalski')).toBeVisible();
@@ -115,6 +117,7 @@ test('„Udostępnione mi”: plan read-only — bez akcji statusowych, „Udost
await expect(page.getByRole('button', { name: 'Edytuj' })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Usuń' })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Udostępnij' })).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Zapisz jako szablon' })).toHaveCount(0);
await expect(page.getByText('Tydzień startu')).toHaveCount(0);
});
@@ -125,6 +128,7 @@ test('właściciel: „Udostępnij” — dialog z podopiecznymi, share = POST /
await login(page);
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('link', { name: /^Aktualne/ }).click();
await page.getByRole('link', { name: /Plan masowy/ }).click();
await expect(page.getByRole('heading', { name: 'Plan masowy' })).toBeVisible();

View File

@@ -0,0 +1,353 @@
import { test, expect, type Page } from './fixtures';
import { mockApi } from './mock-api';
const TEMPLATE_ID = 'tpl-1';
const CLONED_ID = 'plan-cloned';
async function login(page: Page) {
await page.goto('/login');
await page.locator('input[type="email"]').fill('test@fitos.pl');
await page.locator('input[type="password"]').fill('haslo123');
await page.getByRole('button', { name: 'Zaloguj' }).click();
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
}
function exerciseRows(exId: string, name: string, muscle: string, setsCount: number) {
return [
{
id: `pex-${exId}`,
exerciseId: exId,
order: 0,
exercise: { id: exId, name, primaryMuscle: muscle },
sets: Array.from({ length: setsCount }, (_, i) => ({
id: `ps-${exId}-${i}`,
index: i,
reps: 10,
loadKg: 40,
restSec: 90,
rir: 2,
cardioBpm: null,
timeSec: null,
speed: null,
})),
},
];
}
/** Struktura szablonu: 2 tygodnie, Pon + Śr; w klonie/planie dni z datami. */
function templateWeeks(dated: boolean) {
const nextWeek = new Date();
nextWeek.setDate(nextWeek.getDate() + 7);
const iso = nextWeek.toISOString().slice(0, 10);
return [0, 1].map((w) => ({
id: `tw-${w}`,
index: w,
customName: null,
days: [
{
id: `td-${w}-1`,
dayOfWeek: 1,
date: dated ? iso : null,
status: 'PLANNED',
moveLog: [],
sessions: [],
exercises: exerciseRows('ex-1', 'Przysiady', 'legs', 3),
},
{
id: `td-${w}-2`,
dayOfWeek: 3,
date: null,
status: 'PLANNED',
moveLog: [],
sessions: [],
exercises: exerciseRows('ex-2', 'Wyciskanie', 'chest', 2),
},
],
}));
}
function templatePlan() {
return {
id: TEMPLATE_ID,
userId: 'user-test',
kind: 'TEMPLATE',
canManage: true,
title: 'Szablon e2e',
status: 'DRAFT',
weeksCount: 2,
startDate: null,
gym: null,
creator: null,
weeks: templateWeeks(false),
};
}
function templateListItem() {
return {
id: TEMPLATE_ID,
title: 'Szablon e2e',
weeksCount: 2,
daysCount: 4,
exercisesCount: 2,
usedCount: 0,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
};
}
function draftPlan() {
return {
id: 'plan-d',
userId: 'user-test',
kind: 'PLAN',
canManage: true,
title: 'Plan szkic e2e',
status: 'DRAFT',
weeksCount: 2,
startDate: null,
gym: null,
creator: null,
weeks: templateWeeks(false),
};
}
function activePlan() {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
return {
id: 'plan-a',
userId: 'user-test',
kind: 'PLAN',
canManage: true,
title: 'Plan aktywny e2e',
status: 'ACTIVE',
weeksCount: 4,
startDate: '2026-10-05',
gym: { id: 'gym-1', name: 'Żelazna Świątynia' },
creator: null,
progress: { completed: 3, total: 8, percent: 38 },
currentWeek: 2,
nextDay: { date: tomorrow.toISOString().slice(0, 10), dayOfWeek: 3, exerciseCount: 4 },
weeks: templateWeeks(true),
};
}
function clonedPlan() {
return {
...templatePlan(),
id: CLONED_ID,
kind: 'PLAN',
title: 'Plan z szablonu e2e',
sourceTemplateId: TEMPLATE_ID,
weeks: templateWeeks(false),
};
}
/**
* Rejestrowane po mockApi — mają pierwszeństwo nad wildcardami plans/*
* (Playwright: odwrotna kolejność rejestracji route'ów).
*/
function mockPlansArea(
page: Page,
plans: Record<string, unknown>[],
detailOf?: (id: string) => Record<string, unknown> | null,
) {
page.route('**/api/v1/exercises', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
exercises: [
{ id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
{ id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' },
],
}),
}),
);
page.route('**/api/v1/plans', (route) => {
if (route.request().method() !== 'GET') return route.fallback();
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ plans }),
});
});
for (const p of plans) {
const id = String(p.id);
page.route(`**/api/v1/plans/${id}`, (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ plan: (detailOf?.(id) ?? null) ?? p }),
}),
);
}
}
test('„Zapisz jako szablon”: toast, link do zapisanego szablonu i sekcja Użycia', async ({
page,
}) => {
mockApi(page, {
planTemplates: { templates: [templateListItem()] },
planTemplateDetail: { plan: templatePlan(), usedCount: 0, derived: [] },
});
mockPlansArea(page, [draftPlan()]);
// cel „Otwórz zapisany szablon” (POST /as-template zwraca id tpl-new)
page.route('**/api/v1/plans/tpl-new', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ plan: templatePlan() }),
}),
);
await login(page);
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('link', { name: /^Aktualne/ }).click();
await page.getByRole('link', { name: /Plan szkic e2e/ }).click();
await expect(page.getByRole('heading', { name: 'Plan szkic e2e' })).toBeVisible();
// akcja w topbarze (w treści nie ma przycisku „Zapisz”)
await expect(page.getByRole('button', { name: 'Zapisz', exact: true })).toHaveCount(0);
await page.getByRole('button', { name: 'Zapisz jako szablon' }).click();
await expect(page.getByText('Zapisano jako szablon')).toBeVisible();
await page.getByRole('link', { name: 'Otwórz zapisany szablon' }).click();
await expect(page.getByRole('heading', { name: 'Szablon e2e' })).toBeVisible();
await expect(page.getByText('Użycia')).toBeVisible();
await expect(page.getByText('Ten szablon nie został jeszcze użyty.')).toBeVisible();
});
test('Szablony: karta otwiera detal z sekcją Użycia; „Użyj” klonuje ze atrybucją', async ({
page,
}) => {
mockApi(page, {
planTemplates: { templates: [{ ...templateListItem(), usedCount: 1 }] },
planTemplateDetail: {
plan: templatePlan(),
usedCount: 1,
derived: [
{
id: 'plan-old',
title: 'Plan po szablonie',
status: 'COMPLETED',
ownerId: 'user-test',
ownerName: 'Test User',
progress: { completed: 2, total: 4, percent: 50 },
},
],
},
});
mockPlansArea(page, []);
page.route(`**/api/v1/plans/${TEMPLATE_ID}/clone`, (route) =>
route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ plan: { id: CLONED_ID } }),
}),
);
page.route(`**/api/v1/plans/${CLONED_ID}`, (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ plan: clonedPlan() }),
}),
);
await login(page);
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('link', { name: /^Szablony/ }).click();
await expect(page.getByText('2 tyg.')).toBeVisible();
await page.getByRole('link', { name: /Szablon e2e/ }).click();
await expect(page.getByRole('heading', { name: 'Szablon e2e' })).toBeVisible();
// sekcja Użycia: wiersz sklonowanego planu
await expect(page.getByText('Utworzono 1 plan z tego szablonu')).toBeVisible();
await expect(page.getByRole('link', { name: /Plan po szablonie/ })).toBeVisible();
// „Użyj” w topbarze -> klon DRAFT ze atrybucją szablonu
await page.getByRole('button', { name: 'Użyj' }).click();
await expect(page.getByRole('heading', { name: 'Plan z szablonu e2e' })).toBeVisible();
await expect(page.getByText('utworzony z szablonu')).toBeVisible();
});
test('menu „Nowy plan”: „Z szablonu” klonuje wybrany szablon prosto do edytora', async ({
page,
}) => {
mockApi(page, {
planTemplates: { templates: [templateListItem()] },
planTemplateDetail: { plan: templatePlan(), usedCount: 0, derived: [] },
});
mockPlansArea(page, [draftPlan()], (id) => (id === CLONED_ID ? clonedPlan() : null));
page.route(`**/api/v1/plans/${CLONED_ID}`, (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ plan: clonedPlan() }),
}),
);
page.route(`**/api/v1/plans/${TEMPLATE_ID}/clone`, (route) =>
route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ plan: { id: CLONED_ID } }),
}),
);
await login(page);
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Użyj szablonu Szablon e2e' }).click();
// edytor otwiera się na kopii — tytuł pochodzi ze szablonu
await expect(page.getByPlaceholder('np. Plan masowy 8-tygodniowy')).toHaveValue(
'Plan z szablonu e2e',
);
});
test('detal aktywnego planu: kokpit Objętość z partiami i progami', async ({ page }) => {
mockApi(page);
mockPlansArea(page, [activePlan()]);
await login(page);
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('link', { name: /Plan aktywny e2e/ }).click();
await expect(page.getByRole('heading', { name: 'Plan aktywny e2e' })).toBeVisible();
// TEST_PLAN_VOLUME: klatka poza zakresem (deficyt), nogi w zakresie
await expect(page.getByRole('heading', { name: 'Objętość' })).toBeVisible();
await expect(page.getByText('Klatka', { exact: true })).toBeVisible();
await expect(page.getByText('-8 deficyt')).toBeVisible();
await expect(page.getByText('poza zakresem')).toBeVisible();
await expect(page.getByText('Nogi', { exact: true })).toBeVisible();
});
test('hero aktywnego planu na „Aktualnych”: klik otwiera detal; bez ACTIVE — brak hero', async ({
page,
}) => {
mockApi(page);
mockPlansArea(page, [activePlan(), draftPlan()]);
await login(page);
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await expect(page.getByText('Tydzień 2 z 4')).toBeVisible();
await expect(page.getByText('Następny trening:')).toBeVisible();
await expect(page.getByText('3/8 dni')).toBeVisible();
await page.getByRole('link', { name: /Plan aktywny e2e/ }).click();
await expect(page.getByRole('heading', { name: 'Plan aktywny e2e' })).toBeVisible();
});
test('bez planu ACTIVE — brak hero; kategoria „Aktualne” prowadzi do listy ze szkicem', async ({
page,
}) => {
mockApi(page);
mockPlansArea(page, [draftPlan()]);
await login(page);
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await expect(page.getByText('Następny trening:')).toHaveCount(0);
await page.getByRole('link', { name: /^Aktualne/ }).click();
await expect(page.getByRole('link', { name: /Plan szkic e2e/ })).toBeVisible();
});

View File

@@ -32,6 +32,7 @@ test('formularz nowego planu ma wybór tygodnia startu i przycisk „Wstecz” w
// otwórz formularz nowego planu (akcja „Nowy plan” w menu kontekstowym — na PC inline)
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Od zera' }).click();
await expect(page.getByRole('heading', { name: 'Nowy plan' })).toBeVisible();
// przycisk „Wstecz” jest też w treści podstrony (topbar ma własny, inteligentny)
@@ -116,6 +117,7 @@ test('cofniecie tygodnia startu pyta o usunięcie dni, które wpadną w przeszł
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Od zera' }).click();
await expect(page.getByRole('heading', { name: 'Nowy plan' })).toBeVisible();
// start w przyszłym tygodniu → zaznaczamy dzień, który przy bieżącym starcie minął
@@ -152,6 +154,7 @@ test('walidacja tytułu i podsumowanie w kroku 3', async ({ page }) => {
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Od zera' }).click();
await expect(page.getByRole('heading', { name: 'Nowy plan' })).toBeVisible();
// pusty tytuł → „Dalej” i „Zapisz” zablokowane (zapis szkicu bez nazwy niemożliwy)
@@ -180,6 +183,7 @@ test('zakładki tygodni: klik taba przełącza tydzień; lustrzany — podgląd
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Od zera' }).click();
await expect(page.getByRole('heading', { name: 'Nowy plan' })).toBeVisible();
// zakładki tygodni są na kroku 2 (4 tygodnie domyślnie) — kotwiczone regexy, bo
@@ -207,6 +211,7 @@ test('kopiowanie dni z dowolnego tygodnia („Kopiuj z…”)', async ({ page })
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Od zera' }).click();
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
@@ -246,6 +251,7 @@ test('kopiowanie zawartości dnia („Kopiuj dzień z…")', async ({ page }) =>
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Od zera' }).click();
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
@@ -278,6 +284,7 @@ test('zmiana kolejności ćwiczeń i stepper serii', async ({ page }) => {
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await expect(page.getByRole('heading', { name: 'Plany treningowe' })).toBeVisible();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Od zera' }).click();
await expect(page.getByRole('heading', { name: 'Nowy plan' })).toBeVisible();
// dodaj dzień i dwa ćwiczenia (krok 2)
@@ -317,6 +324,7 @@ test('obciążenie po przecinku: kropka normalizowana, znaki obce odrzucane, zap
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Od zera' }).click();
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
await page.getByRole('button', { name: 'Pon' }).click();
@@ -355,6 +363,7 @@ test('picker kółkowy serii: kółko minut/sekund dla przerwy, zatwierdzanie wa
await page.getByRole('link', { name: 'Plany treningowe' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await page.getByRole('button', { name: 'Od zera' }).click();
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
await page.getByRole('button', { name: 'Pon' }).click();