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

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

View File

@@ -0,0 +1,11 @@
-- AlterTable
ALTER TABLE "PlanWeek" ADD COLUMN "customName" TEXT;
-- AlterTable
ALTER TABLE "TrainingPlan" ADD COLUMN "gymId" TEXT;
-- CreateIndex
CREATE INDEX "TrainingPlan_gymId_idx" ON "TrainingPlan"("gymId");
-- AddForeignKey
ALTER TABLE "TrainingPlan" ADD CONSTRAINT "TrainingPlan_gymId_fkey" FOREIGN KEY ("gymId") REFERENCES "Gym"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View File

@@ -85,45 +85,45 @@ enum EquipmentKind {
}
model User {
id String @id @default(cuid())
email String @unique
passwordHash String
firstName String?
lastName String?
nickname String?
socialMedia Json?
age Int?
heightCm Float?
phone String? @unique
isAdmin Boolean @default(false)
tokenVersion Int @default(0)
availability Json?
priorities String?
exclusions String?
id String @id @default(cuid())
email String @unique
passwordHash String
firstName String?
lastName String?
nickname String?
socialMedia Json?
age Int?
heightCm Float?
phone String? @unique
isAdmin Boolean @default(false)
tokenVersion Int @default(0)
availability Json?
priorities String?
exclusions String?
developMuscles String[] @default([])
canDoMuscles String[] @default([])
difficultMuscles String[] @default([])
avoidMuscles String[] @default([])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
memberships GymMembership[]
plans TrainingPlan[]
createdPlans TrainingPlan[] @relation("PlanCreator")
weightEntries BodyMeasurement[]
memberships GymMembership[]
plans TrainingPlan[]
createdPlans TrainingPlan[] @relation("PlanCreator")
weightEntries BodyMeasurement[]
circumferenceEntries CircumferenceMeasurement[]
coachingsAsTrainer Coaching[] @relation("CoachingTrainer")
coachingsAsUser Coaching[] @relation("CoachingUser")
commentsAsAuthor Comment[] @relation("CommentAuthor")
commentsAsTarget Comment[] @relation("CommentTarget")
messagesAsSender Message[] @relation("MessageSender")
conversationReads ConversationRead[]
activityLogs ActivityLog[] @relation("ActivityLogActor")
gymRatings GymRating[]
gymClaims GymClaim[]
claimsDecided GymClaim[] @relation("ClaimDecider")
gymInvitations GymInvitation[]
gymInvitationsSent GymInvitation[] @relation("GymInviteSender")
coachingsAsTrainer Coaching[] @relation("CoachingTrainer")
coachingsAsUser Coaching[] @relation("CoachingUser")
commentsAsAuthor Comment[] @relation("CommentAuthor")
commentsAsTarget Comment[] @relation("CommentTarget")
messagesAsSender Message[] @relation("MessageSender")
conversationReads ConversationRead[]
activityLogs ActivityLog[] @relation("ActivityLogActor")
gymRatings GymRating[]
gymClaims GymClaim[]
claimsDecided GymClaim[] @relation("ClaimDecider")
gymInvitations GymInvitation[]
gymInvitationsSent GymInvitation[] @relation("GymInviteSender")
}
/// Audit trail of user actions (app + trainer level). Best-effort writes,
@@ -147,16 +147,16 @@ model ActivityLog {
/// Trainer ↔ trainee relation. Created as PENDING (invitation), becomes ACTIVE
/// after the invited party accepts. Invitations expire after 7 days.
model Coaching {
id String @id @default(cuid())
trainerId String
userId String
gymId String?
status CoachingStatus @default(PENDING)
note String?
invitedBy String
invitedAt DateTime @default(now())
expiresAt DateTime
createdAt DateTime @default(now())
id String @id @default(cuid())
trainerId String
userId String
gymId String?
status CoachingStatus @default(PENDING)
note String?
invitedBy String
invitedAt DateTime @default(now())
expiresAt DateTime
createdAt DateTime @default(now())
trainer User @relation("CoachingTrainer", fields: [trainerId], references: [id], onDelete: Cascade)
user User @relation("CoachingUser", fields: [userId], references: [id], onDelete: Cascade)
@@ -216,26 +216,27 @@ model ConversationRead {
}
model Gym {
id String @id @default(cuid())
name String
location String?
id String @id @default(cuid())
name String
location String?
availability Json?
capacity Int?
capacity Int?
/// Existing rows default to REAL; VIRTUAL gyms are created by users.
kind GymKind @default(REAL)
kind GymKind @default(REAL)
/// Only meaningful for VIRTUAL gyms (hidden from the public list).
isPrivate Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
isPrivate Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
memberships GymMembership[]
memberships GymMembership[]
customExercises Exercise[]
equipment GymEquipment[]
exceptions GymException[]
ratings GymRating[]
claims GymClaim[]
invitations GymInvitation[]
photos GymPhoto[]
equipment GymEquipment[]
exceptions GymException[]
ratings GymRating[]
claims GymClaim[]
invitations GymInvitation[]
photos GymPhoto[]
plans TrainingPlan[]
}
/// Zdjęcie w galerii siłowni REAL. `order` = kolejność; okładka = najmniejsze `order` (tie → najstarsze `createdAt`).
@@ -262,7 +263,7 @@ model GymRating {
createdAt DateTime @default(now())
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([gymId, userId])
@@index([gymId])
@@ -271,33 +272,33 @@ model GymRating {
/// A claim: verification of an existing virtual gym (gymId set) or a request for a
/// new real gym (gymId null, gym data carried in the claim).
model GymClaim {
id String @id @default(cuid())
id String @id @default(cuid())
/// null = claim for a NEW real gym (data below); set = verification of that virtual gym.
gymId String?
userId String
gymId String?
userId String
/// Gym data — only for claims with gymId = null:
gymName String?
gymLocation String?
gymName String?
gymLocation String?
gymAvailability Json?
gymCapacity Int?
gymCapacity Int?
/// Applicant data / proof:
description String
companyName String?
nip String?
phone String?
email String?
description String
companyName String?
nip String?
phone String?
email String?
/// Verification claims only: overrides gym.location on approval.
address String?
status ClaimStatus @default(PENDING)
rejectReason String?
decidedById String?
decidedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
address String?
status ClaimStatus @default(PENDING)
rejectReason String?
decidedById String?
decidedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
gym Gym? @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
decidedBy User? @relation("ClaimDecider", fields: [decidedById], references: [id], onDelete: SetNull)
gym Gym? @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
decidedBy User? @relation("ClaimDecider", fields: [decidedById], references: [id], onDelete: SetNull)
documents GymClaimDocument[]
@@index([gymId, status])
@@ -320,14 +321,14 @@ model GymClaimDocument {
/// Invitation to a PRIVATE virtual gym (owner invites a specific user, 7-day TTL).
model GymInvitation {
id String @id @default(cuid())
id String @id @default(cuid())
gymId String
userId String
invitedById String
status GymInvitationStatus @default(PENDING)
invitedAt DateTime @default(now())
invitedAt DateTime @default(now())
expiresAt DateTime
createdAt DateTime @default(now())
createdAt DateTime @default(now())
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -342,10 +343,10 @@ model GymInvitation {
/// Gym ↔ equipment instance: how many units of a catalog item a gym has
/// (e.g. two pairs of dumbbells).
model GymEquipment {
id String @id @default(cuid())
id String @id @default(cuid())
gymId String
equipmentId String
quantity Int @default(1)
quantity Int @default(1)
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
equipment Equipment @relation(fields: [equipmentId], references: [id], onDelete: Cascade)
@@ -381,7 +382,7 @@ model FocusArea {
}
model GymMembership {
id String @id @default(cuid())
id String @id @default(cuid())
userId String
gymId String
roles GymRole[] @default([MEMBER])
@@ -431,8 +432,8 @@ model Equipment {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
exercises Exercise[]
gyms GymEquipment[]
exercises Exercise[]
gyms GymEquipment[]
}
model Exercise {
@@ -464,7 +465,7 @@ model Exercise {
gym Gym? @relation(fields: [gymId], references: [id], onDelete: SetNull)
equipment Equipment[]
planExercises PlanExercise[]
planExercises PlanExercise[]
sessionExercises SessionExercise[]
@@index([source])
@@ -478,20 +479,26 @@ model TrainingPlan {
status PlanStatus @default(DRAFT)
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
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[]
@@index([userId, status])
@@index([gymId])
}
model PlanWeek {
id String @id @default(cuid())
planId String
index Int
id String @id @default(cuid())
planId String
index Int
/// Opcjonalny alias tygodnia (np. „Deload").
customName String?
plan TrainingPlan @relation(fields: [planId], references: [id], onDelete: Cascade)
days PlanDay[]
@@ -500,15 +507,15 @@ model PlanWeek {
}
model PlanDay {
id String @id @default(cuid())
id String @id @default(cuid())
weekId String
dayOfWeek Int
date DateTime?
status DayStatus @default(PLANNED)
status DayStatus @default(PLANNED)
completedAt DateTime?
skippedAt DateTime?
week PlanWeek @relation(fields: [weekId], references: [id], onDelete: Cascade)
week PlanWeek @relation(fields: [weekId], references: [id], onDelete: Cascade)
moveLog DayMove[]
exercises PlanExercise[]
sessions TrainingSession[]
@@ -542,19 +549,19 @@ model PlanExercise {
}
model PlanSet {
id String @id @default(cuid())
exerciseId String
index Int
reps Int?
loadKg Float?
restSec Int?
rir Int?
difficulty Int?
cardioBpm Int?
timeSec Int?
speed Float?
id String @id @default(cuid())
exerciseId String
index Int
reps Int?
loadKg Float?
restSec Int?
rir Int?
difficulty Int?
cardioBpm Int?
timeSec Int?
speed Float?
exercise PlanExercise @relation(fields: [exerciseId], references: [id], onDelete: Cascade)
exercise PlanExercise @relation(fields: [exerciseId], references: [id], onDelete: Cascade)
sessionSets SessionSet[]
@@unique([exerciseId, index])
@@ -567,9 +574,9 @@ model TrainingSession {
startedAt DateTime @default(now())
endedAt DateTime?
day PlanDay @relation(fields: [dayId], references: [id], onDelete: Cascade)
exercises SessionExercise[]
messagesAsSession Message[] @relation("MessageSession")
day PlanDay @relation(fields: [dayId], references: [id], onDelete: Cascade)
exercises SessionExercise[]
messagesAsSession Message[] @relation("MessageSession")
@@index([dayId, status])
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -390,6 +390,114 @@ describe('plans routes', () => {
});
});
describe('plans: gym and week alias', () => {
let token: string;
let exerciseId: string;
let gymId: string;
let otherGymId: string;
const body = (title: string) => ({
title,
weeksCount: 1,
weeks: [
{
index: 0,
customName: 'Deload',
days: [{ dayOfWeek: 1, exercises: [{ exerciseId, order: 0, sets: [{ index: 0, reps: 10 }] }] }],
},
],
});
beforeAll(async () => {
const reg = await registerViaApi();
token = reg.token;
exerciseId = (await createExercise()).id;
const gym = await prisma.gym.create({ data: { name: `Plan Gym ${rand()}` } });
gymId = gym.id;
const other = await prisma.gym.create({ data: { name: `Other Gym ${rand()}` } });
otherGymId = other.id;
await prisma.gymMembership.create({ data: { userId: reg.user.id, gymId, roles: ['MEMBER'] as never } });
});
it('creates a plan with gymId and per-week customName', async () => {
const app = buildApp();
const res = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send({ ...body('Z siłownią'), gymId });
expect(res.status).toBe(201);
expect(res.body.plan.gym).toMatchObject({ id: gymId });
expect(res.body.plan.gym.name).toBeTruthy();
const detail = await app.get(`/api/v1/plans/${res.body.plan.id}`).set('Authorization', `Bearer ${token}`);
expect(detail.body.plan.gym).toMatchObject({ id: gymId });
expect(detail.body.plan.weeks[0].customName).toBe('Deload');
});
it('lists plans with the gym attached', async () => {
const app = buildApp();
const res = await app.get('/api/v1/plans').set('Authorization', `Bearer ${token}`);
const found = res.body.plans.find((p: { title: string }) => p.title === 'Z siłownią');
expect(found.gym).toMatchObject({ id: gymId });
});
it('rejects creation with a gym the user is not a member of with 400', async () => {
const app = buildApp();
const res = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send({ ...body('Bez członkostwa'), gymId: otherGymId });
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Plan owner is not a member of the gym');
});
it('rejects creation with an unknown gymId with 400', async () => {
const app = buildApp();
const res = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send({ ...body('Nieznana siłownia'), gymId: 'nonexistent-gym' });
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Unknown gymId in plan');
});
it('rejects a week alias longer than 40 chars with 400', async () => {
const app = buildApp();
const b = body('Długi alias');
b.weeks[0].customName = 'a'.repeat(41);
const res = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(b);
expect(res.status).toBe(400);
});
it('updates gymId and customName via PATCH', async () => {
const app = buildApp();
const created = await app.post('/api/v1/plans').set('Authorization', `Bearer ${token}`).send(body('Do zmiany'));
const id = created.body.plan.id;
const res = await app
.patch(`/api/v1/plans/${id}`)
.set('Authorization', `Bearer ${token}`)
.send({ ...body('Do zmiany v2'), gymId, weeks: [{ index: 0, customName: null, days: [] }] });
expect(res.status).toBe(200);
const detail = await app.get(`/api/v1/plans/${id}`).set('Authorization', `Bearer ${token}`);
expect(detail.body.plan.gym).toMatchObject({ id: gymId });
expect(detail.body.plan.weeks[0].customName).toBeNull();
});
it('clears gymId to null when the gym is deleted', async () => {
const app = buildApp();
const created = await app
.post('/api/v1/plans')
.set('Authorization', `Bearer ${token}`)
.send({ ...body('Plan z siłownią do usunięcia'), gymId });
const id = created.body.plan.id;
await prisma.gym.delete({ where: { id: gymId } });
const detail = await app.get(`/api/v1/plans/${id}`).set('Authorization', `Bearer ${token}`);
expect(detail.body.plan.gym).toBeNull();
});
});
describe('plans: direct seeding sanity', () => {
it('seedPlan creates a consistent structure in the database', async () => {
const { user } = await createUser();
@@ -498,4 +606,26 @@ describe('plans: trainer-created plan (creator + owner access)', () => {
const res = await app.get(`/api/v1/plans/${planId}`).set('Authorization', `Bearer ${plainToken}`);
expect(res.status).toBe(404);
});
it('trainer can attach a gym the trainee is a member of', async () => {
const gym = await prisma.gym.create({ data: { name: `Trainee Gym ${rand()}` } });
await prisma.gymMembership.create({ data: { userId: traineeId, gymId: gym.id, roles: ['MEMBER'] as never } });
const res = await app
.post(`/api/v1/trainer/trainees/${traineeId}/plans`)
.set('Authorization', `Bearer ${trainerToken}`)
.send({ ...body('Plan z siłownią'), gymId: gym.id });
expect(res.status).toBe(201);
expect(res.body.plan.gym).toMatchObject({ id: gym.id });
});
it('trainer cannot attach a gym the trainee is NOT a member of (400)', async () => {
const gym = await prisma.gym.create({ data: { name: `Trainer-only Gym ${rand()}` } });
await prisma.gymMembership.create({ data: { userId: trainerId, gymId: gym.id, roles: ['TRAINER'] as never } });
const res = await app
.post(`/api/v1/trainer/trainees/${traineeId}/plans`)
.set('Authorization', `Bearer ${trainerToken}`)
.send({ ...body('Plan bez członkostwa'), gymId: gym.id });
expect(res.status).toBe(400);
expect(res.body.error.message).toBe('Plan owner is not a member of the gym');
});
});

View File

@@ -231,6 +231,7 @@ describe('listPlans', () => {
orderBy: { createdAt: 'desc' },
include: {
creator: { select: { id: true, firstName: true, lastName: true } },
gym: { select: { id: true, name: true } },
weeks: { select: { days: { select: { status: true } } } },
},
});

View File

@@ -54,9 +54,7 @@ export function useBodyParameters() {
return useQuery({
queryKey: ['me', 'body-parameters'],
queryFn: () =>
api<{ weight: WeightPoint[]; circumferences: CircumferenceSeries[] }>(
'/me/body-parameters',
),
api<{ weight: WeightPoint[]; circumferences: CircumferenceSeries[] }>('/me/body-parameters'),
});
}
@@ -71,12 +69,18 @@ function toIsoDate(date: string | undefined): string | undefined {
export function addWeight(value: number, date?: string) {
const iso = toIsoDate(date);
return api('/me/body-parameters/weight', { method: 'POST', body: { value, ...(iso ? { date: iso } : {}) } });
return api('/me/body-parameters/weight', {
method: 'POST',
body: { value, ...(iso ? { date: iso } : {}) },
});
}
export function addCircumference(name: string, value: number, date?: string) {
const iso = toIsoDate(date);
return api('/me/body-parameters/circumference', { method: 'POST', body: { name, value, ...(iso ? { date: iso } : {}) } });
return api('/me/body-parameters/circumference', {
method: 'POST',
body: { name, value, ...(iso ? { date: iso } : {}) },
});
}
export function removeWeightPoint(id: string) {
@@ -126,10 +130,9 @@ export function useGymDetail(id: string | undefined) {
export function addGymPhotos(gymId: string, files: File[]) {
const form = new FormData();
for (const f of files) form.append('photos', f);
return api<{ gym: Gym & { photos: { id: string; url: string; order: number; createdAt: string }[] } }>(
`/gyms/${gymId}/photos`,
{ method: 'POST', body: form },
);
return api<{
gym: Gym & { photos: { id: string; url: string; order: number; createdAt: string }[] };
}>(`/gyms/${gymId}/photos`, { method: 'POST', body: form });
}
export function deleteGymPhoto(gymId: string, photoId: string) {
@@ -224,7 +227,10 @@ export function useGymExceptions(gymId: string) {
});
}
export function createGymException(gymId: string, body: { date: string; availability: { start: string; end: string } | null }) {
export function createGymException(
gymId: string,
body: { date: string; availability: { start: string; end: string } | null },
) {
return api<{ exception: GymException }>(`/gyms/${gymId}/exceptions`, {
method: 'POST',
body,
@@ -323,17 +329,26 @@ export function useGymInviteeSearch(gymId: string, firstName: string, lastName:
/** List the equipment (machine/device) catalog. */
export function useEquipment() {
return useQuery({ queryKey: ['equipment'], queryFn: () => api<{ equipment: Equipment[] }>('/equipment') });
return useQuery({
queryKey: ['equipment'],
queryFn: () => api<{ equipment: Equipment[] }>('/equipment'),
});
}
// ---------- exercises ----------
export function useExercises() {
return useQuery({ queryKey: ['exercises'], queryFn: () => api<{ exercises: Exercise[] }>('/exercises') });
return useQuery({
queryKey: ['exercises'],
queryFn: () => api<{ exercises: Exercise[] }>('/exercises'),
});
}
// ---------- focus areas (priorities/exclusions) ----------
export function useFocusAreas() {
return useQuery({ queryKey: ['focus-areas'], queryFn: () => api<{ focusAreas: FocusArea[] }>('/focus-areas') });
return useQuery({
queryKey: ['focus-areas'],
queryFn: () => api<{ focusAreas: FocusArea[] }>('/focus-areas'),
});
}
export function useFocusChain() {
@@ -378,20 +393,26 @@ export interface PlanDayInput {
export interface PlanWeekInput {
index: number;
/** Opcjonalny alias tygodnia (np. „Deload"); null = bez aliasu. */
customName?: string | null;
days: PlanDayInput[];
}
export function createPlan(body: {
export interface PlanBody {
title: string;
weeksCount: number;
/** Informacyjna — siłownia planu; null/brak = bez siłowni. */
gymId?: string | null;
weeks: PlanWeekInput[];
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
startDate?: string;
}) {
}
export function createPlan(body: PlanBody) {
return api<{ plan: { id: string } }>('/plans', { method: 'POST', body });
}
export function updatePlan(id: string, body: { title: string; weeksCount: number; weeks: PlanWeekInput[] }) {
export function updatePlan(id: string, body: Omit<PlanBody, 'startDate'>) {
return api(`/plans/${id}`, { method: 'PATCH', body });
}
@@ -439,7 +460,10 @@ export function addSessionExercise(sessionId: string, exerciseId: string) {
});
}
export function setSessionExerciseState(exerciseId: string, data: { hidden?: boolean; removed?: boolean }) {
export function setSessionExerciseState(
exerciseId: string,
data: { hidden?: boolean; removed?: boolean },
) {
return api(`/sessions/exercises/${exerciseId}`, { method: 'PATCH', body: data });
}
@@ -447,7 +471,15 @@ export function addSessionSet(exerciseId: string) {
return api<{ setId: string }>(`/sessions/exercises/${exerciseId}/sets`, { method: 'POST' });
}
export function updateSessionSet(setId: string, data: { reps?: number | null; rir?: number | null; difficulty?: number | null; note?: string | null }) {
export function updateSessionSet(
setId: string,
data: {
reps?: number | null;
rir?: number | null;
difficulty?: number | null;
note?: string | null;
},
) {
return api(`/sessions/sets/${setId}`, { method: 'PATCH', body: data });
}
@@ -539,7 +571,10 @@ export function useTraineeSearch(firstName: string, lastName: string) {
}
export function sendInvitation(userId: string) {
return api<{ coaching: { id: string } }>('/trainer/invitations', { method: 'POST', body: { userId } });
return api<{ coaching: { id: string } }>('/trainer/invitations', {
method: 'POST',
body: { userId },
});
}
export function archiveTrainee(userId: string) {
@@ -569,9 +604,7 @@ export function useCalendar(month?: string) {
return useQuery({
queryKey: ['calendar', month],
queryFn: () =>
api<{ month: string; days: CalendarDay[] }>(
`/calendar${month ? `?month=${month}` : ''}`,
),
api<{ month: string; days: CalendarDay[] }>(`/calendar${month ? `?month=${month}` : ''}`),
});
}
@@ -617,13 +650,20 @@ export function addTraineeComment(
userId: string,
data: { body: string; sessionId?: string; sessionExerciseId?: string },
) {
return api<{ comment: ExerciseComment }>(`/trainer/trainees/${encodeURIComponent(userId)}/comments`, {
method: 'POST',
body: data,
});
return api<{ comment: ExerciseComment }>(
`/trainer/trainees/${encodeURIComponent(userId)}/comments`,
{
method: 'POST',
body: data,
},
);
}
export function addMyComment(data: { body: string; sessionId: string; sessionExerciseId?: string }) {
export function addMyComment(data: {
body: string;
sessionId: string;
sessionExerciseId?: string;
}) {
return api<{ comment: ExerciseComment }>('/me/comments', { method: 'POST', body: data });
}
@@ -647,7 +687,8 @@ export function useExerciseProgress() {
export function useTraineeExerciseProgress(userId: string) {
return useQuery({
queryKey: ['trainees', userId, 'exercise-progress'],
queryFn: () => api<{ exercises: ExerciseProgress[] }>(`/trainer/trainees/${userId}/exercise-progress`),
queryFn: () =>
api<{ exercises: ExerciseProgress[] }>(`/trainer/trainees/${userId}/exercise-progress`),
enabled: !!userId,
});
}
@@ -655,7 +696,8 @@ export function useTraineeExerciseProgress(userId: string) {
export function useTraineeLatestResults(userId: string) {
return useQuery({
queryKey: ['trainees', userId, 'exercise-latest'],
queryFn: () => api<{ results: LatestExerciseResult[] }>(`/trainer/trainees/${userId}/exercise-latest`),
queryFn: () =>
api<{ results: LatestExerciseResult[] }>(`/trainer/trainees/${userId}/exercise-latest`),
enabled: !!userId,
});
}
@@ -677,20 +719,18 @@ export function useTraineePlan(userId: string, planId: string) {
});
}
export function createTraineePlan(
userId: string,
body: {
title: string;
weeksCount: number;
weeks: PlanWeekInput[];
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
startDate?: string;
},
) {
return api<{ plan: { id: string } }>(`/trainer/trainees/${userId}/plans`, { method: 'POST', body });
export function createTraineePlan(userId: string, body: PlanBody) {
return api<{ plan: { id: string } }>(`/trainer/trainees/${userId}/plans`, {
method: 'POST',
body,
});
}
export function updateTraineePlan(userId: string, planId: string, body: { title: string; weeksCount: number; weeks: PlanWeekInput[] }) {
export function updateTraineePlan(
userId: string,
planId: string,
body: Omit<PlanBody, 'startDate'>,
) {
return api(`/trainer/trainees/${userId}/plans/${planId}`, { method: 'PATCH', body });
}
@@ -699,7 +739,10 @@ export function deleteTraineePlan(userId: string, planId: string) {
}
export function activateTraineePlan(userId: string, planId: string, startDate: string) {
return api(`/trainer/trainees/${userId}/plans/${planId}/activate`, { method: 'POST', body: { startDate } });
return api(`/trainer/trainees/${userId}/plans/${planId}/activate`, {
method: 'POST',
body: { startDate },
});
}
export function abandonTraineePlan(userId: string, planId: string) {

View File

@@ -184,7 +184,12 @@ export interface GymInvitation {
/** Kto został zaproszony (tylko direction = 'sent'). */
user: { id: string; firstName: string | null; lastName: string | null; email: string } | null;
/** Kto zaprosił (tylko direction = 'received'). */
invitedBy: { id: string; firstName: string | null; lastName: string | null; email: string } | null;
invitedBy: {
id: string;
firstName: string | null;
lastName: string | null;
email: string;
} | null;
invitedAt: string;
expiresAt: string;
}
@@ -262,6 +267,8 @@ export interface PlanDay {
export interface PlanWeek {
id: string;
index: number;
/** Opcjonalny alias tygodnia (np. „Deload"). */
customName: string | null;
days: PlanDay[];
}
@@ -271,6 +278,8 @@ export interface Plan {
status: 'DRAFT' | 'ACTIVE' | 'COMPLETED' | 'ABANDONED';
weeksCount: number;
startDate: string | null;
/** Informacyjna — siłownia, w której realizowany jest plan; null = bez siłowni. */
gym: { id: string; name: string } | null;
/** Kto utworzył plan (trener, gdy plan należy do podopiecznego); null = podopieczny sam. */
creator: { id: string; firstName: string | null; lastName: string | null } | null;
/** Podsumowanie postępu (lista planów); brak = dane niedostępne. */
@@ -325,7 +334,11 @@ export interface ActiveSession {
export interface Dashboard {
killstreak: number;
nextTraining: { dayId: string; date: string; exercises: { name: string; muscle: string }[] } | null;
nextTraining: {
dayId: string;
date: string;
exercises: { name: string; muscle: string }[];
} | null;
progress: { completed: number; total: number; percent: number } | null;
/** Serie wykonane ponad plan (planSetId = null) w ukończonych sesjach aktywnego planu. */
extra: { sets: number } | null;
@@ -353,7 +366,12 @@ export interface HistorySet {
reps: number | null;
rir: number | null;
difficulty: number | null;
planned: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null } | null;
planned: {
reps: number | null;
loadKg: number | null;
restSec: number | null;
rir: number | null;
} | null;
}
export interface ExerciseComment {
@@ -418,7 +436,12 @@ export interface MessageAttachment {
index: number;
reps: number | null;
rir: number | null;
planned: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null } | null;
planned: {
reps: number | null;
loadKg: number | null;
restSec: number | null;
rir: number | null;
} | null;
}[];
} | null;
/** Tylko gdy exercise == null. */
@@ -483,7 +506,11 @@ export interface UserSearchResult {
export interface Trainee {
user: { id: string; firstName: string | null; lastName: string | null; nickname: string | null };
gyms: { id: string; name: string }[];
activePlan: { id: string; title: string; progress: { completed: number; total: number; percent: number } } | null;
activePlan: {
id: string;
title: string;
progress: { completed: number; total: number; percent: number };
} | null;
killstreak: number;
lastSessionAt: string | null;
flags: TraineeFlag[];
@@ -498,7 +525,11 @@ export interface TraineeDetail {
activePlan: { id: string; title: string; startDate: string } | null;
progress: { completed: number; total: number; percent: number } | null;
killstreak: number;
nextTraining: { dayId: string; date: string; exercises: { name: string; muscle: string }[] } | null;
nextTraining: {
dayId: string;
date: string;
exercises: { name: string; muscle: string }[];
} | null;
extra: { sets: number } | null;
missing: { sets: number } | null;
lastSessionAt: string | null;
@@ -535,7 +566,14 @@ export interface DayMoveEntry {
export interface Invitation {
id: string;
direction: 'sent' | 'received';
other: { id: string; firstName: string | null; lastName: string | null; nickname: string | null; email: string; phone: string | null } | null;
other: {
id: string;
firstName: string | null;
lastName: string | null;
nickname: string | null;
email: string;
phone: string | null;
} | null;
invitedAt: string;
expiresAt: string;
}

View File

@@ -31,10 +31,15 @@ export function PlanDayRow({
actions?: ReactNode;
}) {
return (
<div className={`rounded-[10px] px-3 py-3 transition-colors hover:bg-line/20 ${DAY_TINT[day.status]}`.trim()}>
<div
className={`rounded-[10px] px-3 py-3 transition-colors hover:bg-line/20 ${DAY_TINT[day.status]}`.trim()}
>
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<span aria-hidden="true" className={`h-2 w-2 flex-none rounded-full ${DAY_DOT[day.status]}`} />
<span
aria-hidden="true"
className={`h-2 w-2 flex-none rounded-full ${DAY_DOT[day.status]}`}
/>
<strong className="text-[0.95rem]">{DAY_NAMES[day.dayOfWeek]}</strong>
{showDate && day.date && (
<span className="text-dim text-[0.8125rem] tabular-nums">{fmtDate(day.date)}</span>
@@ -51,7 +56,9 @@ export function PlanDayRow({
<span className="min-w-0 truncate text-[0.875rem]">{ex.exercise.name}</span>
<span className="shrink-0 text-dim text-[0.8125rem] tabular-nums">
{ex.sets.length}×{' '}
{ex.sets.map((s) => `${s.reps ?? '?'} powt.${s.loadKg ? ` @ ${s.loadKg}kg` : ''}`).join(', ')}
{ex.sets
.map((s) => `${s.reps ?? '?'} powt.${s.loadKg ? ` @ ${s.loadKg}kg` : ''}`)
.join(', ')}
</span>
</li>
))}
@@ -78,6 +85,7 @@ export function PlanWeekCard({
<div className="mb-1 flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2.5">
<H2 className="mb-0">Tydzień {week.index + 1}</H2>
{week.customName && <Badge color="blue">{week.customName}</Badge>}
{total > 0 && (
<Badge color={completed === total ? 'green' : 'gray'}>
{completed}/{total} dni
@@ -92,7 +100,9 @@ export function PlanWeekCard({
style={{ width: `${percent}%` }}
/>
</div>
<span className="font-display text-[0.75rem] font-bold tabular-nums text-dim">{percent}%</span>
<span className="font-display text-[0.75rem] font-bold tabular-nums text-dim">
{percent}%
</span>
</div>
)}
</div>

View File

@@ -1,7 +1,7 @@
import { useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { CalendarDays, Pencil, Play, Trash2 } from 'lucide-react';
import { CalendarDays, MapPin, Pencil, Play, Trash2 } from 'lucide-react';
import {
abandonPlan,
activatePlan,
@@ -73,10 +73,22 @@ export default function PlanDetail() {
label: 'Aktywuj',
icon: Play,
disabled: !startDate || busy || hasOtherActivePlan,
onClick: () => void act(() => activatePlan(planData.id, startDate), 'Plan aktywowany'),
onClick: () =>
void act(() => activatePlan(planData.id, startDate), 'Plan aktywowany'),
},
{
label: 'Edytuj',
to: `/plans/${planData.id}/edit`,
variant: 'secondary',
icon: Pencil,
},
{
label: 'Usuń',
icon: Trash2,
variant: 'danger',
disabled: busy,
onClick: () => setConfirm('delete'),
},
{ label: 'Edytuj', to: `/plans/${planData.id}/edit`, variant: 'secondary', icon: Pencil },
{ label: 'Usuń', icon: Trash2, variant: 'danger', disabled: busy, onClick: () => setConfirm('delete') },
]
: planData.status === 'ACTIVE'
? [
@@ -86,7 +98,12 @@ export default function PlanDetail() {
disabled: busy,
onClick: () => void act(() => completePlan(planData.id), 'Plan ukończony'),
},
{ label: 'Porzuć', variant: 'danger', disabled: busy, onClick: () => setConfirm('abandon') },
{
label: 'Porzuć',
variant: 'danger',
disabled: busy,
onClick: () => setConfirm('abandon'),
},
]
: undefined
: undefined,
@@ -131,7 +148,10 @@ export default function PlanDetail() {
<span className="text-dim text-[0.875rem]">
{doneDays}/{allDays.length} dni
</span>
{plan.startDate && <MetaItem icon={CalendarDays}>start: {fmtDate(plan.startDate)}</MetaItem>}
{plan.gym && <MetaItem icon={MapPin}>{plan.gym.name}</MetaItem>}
{plan.startDate && (
<MetaItem icon={CalendarDays}>start: {fmtDate(plan.startDate)}</MetaItem>
)}
{creatorName && <Muted className="text-[0.875rem]">utworzył: {creatorName}</Muted>}
</div>
{allDays.length > 0 && (
@@ -142,7 +162,9 @@ export default function PlanDetail() {
style={{ width: `${planPercent}%` }}
/>
</div>
<span className="font-display text-[0.8125rem] font-bold tabular-nums text-dim">{planPercent}%</span>
<span className="font-display text-[0.8125rem] font-bold tabular-nums text-dim">
{planPercent}%
</span>
</div>
)}
{plan.status === 'DRAFT' && (
@@ -156,8 +178,8 @@ export default function PlanDetail() {
</p>
) : (
<p className="mt-3 text-[0.875rem] text-dim">
Zaznacz tydzień startu — plan zacznie się w jego poniedziałek. Daty dni treningowych liczone
automatycznie.
Zaznacz tydzień startu — plan zacznie się w jego poniedziałek. Daty dni treningowych
liczone automatycznie.
</p>
)}
</div>

View File

@@ -1,24 +1,30 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Link, useNavigate, useParams } from 'react-router-dom';
import {
createPlan,
createTraineePlan,
updatePlan,
updateTraineePlan,
useGyms,
usePlan,
useTrainee,
useTraineePlan,
useTraineeExerciseProgress,
useTraineeLatestResults,
useExercises,
type PlanWeekInput,
type PlanBody,
} from '../../api/queries';
import { CalendarX, Check } from 'lucide-react';
import {
BackButton,
Button,
Card,
ConfirmDialog,
EmptyState,
ErrorText,
Field,
isPastWeek,
Select,
Skeleton,
Tabs,
type BadgeColor,
@@ -35,6 +41,7 @@ import { useTopbar } from '../../topbar';
import { displayedDaysOf, type EditorDay, type EditorWeek } from './plan-editor/types';
import { usePlanEditorState } from './plan-editor/usePlanEditorState';
import { PlanMetaForm } from './plan-editor/PlanMetaForm';
import { PlanSummary } from './plan-editor/PlanSummary';
import { WeekPanel } from './plan-editor/WeekPanel';
import { DayPicker } from './plan-editor/DayPicker';
import { DayEditor } from './plan-editor/DayEditor';
@@ -51,6 +58,60 @@ function EditorSkeleton() {
);
}
const WIZARD_STEPS = [
{ n: 1, label: 'Szczegóły' },
{ n: 2, label: 'Ćwiczenia' },
{ n: 3, label: 'Podsumowanie' },
];
/** Stepper 3 kroków — klikalny (zwrot do wcześniejszego kroku zawsze dozwolony). */
function WizardStepper({ step, onGo }: { step: number; onGo: (n: number) => void }) {
return (
<div
className="flex items-center gap-1.5 sm:gap-2"
role="list"
aria-label="Kroki tworzenia planu"
>
{WIZARD_STEPS.map((s, i) => {
const done = step > s.n;
const active = step === s.n;
return (
<div key={s.n} className="flex items-center gap-1.5 sm:gap-2" role="listitem">
{i > 0 && <span className="h-px w-4 sm:w-8 bg-line" aria-hidden="true" />}
<button
type="button"
onClick={() => onGo(s.n)}
aria-current={active ? 'step' : undefined}
className={cn(
'flex items-center gap-2 rounded-full border px-2.5 py-1.5 text-[0.8125rem] font-medium transition-colors',
active
? 'border-accent bg-accent/10 text-accent-text'
: done
? 'border-line text-ink hover:border-accent/50'
: 'border-line text-dim',
)}
>
<span
className={cn(
'flex h-5 w-5 items-center justify-center rounded-full text-[0.6875rem] font-bold',
active
? 'bg-accent text-white'
: done
? 'bg-accent/15 text-accent-text'
: 'bg-line text-dim',
)}
>
{done ? <Check className="h-3 w-3" /> : s.n}
</span>
<span className="hidden sm:inline">{s.label}</span>
</button>
</div>
);
})}
</div>
);
}
export default function PlanEditor() {
const { id, userId, planId } = useParams();
const traineeUserId = userId ?? '';
@@ -65,6 +126,9 @@ export default function PlanEditor() {
const { data: exData } = useExercises();
const { data: latestData } = useTraineeLatestResults(traineeUserId);
const { data: progressData } = useTraineeExerciseProgress(traineeUserId);
// 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 : '');
const backPath = isTraineeMode
? `/trainees/${traineeUserId}?tab=plans`
@@ -73,6 +137,7 @@ export default function PlanEditor() {
: '/plans';
const [saving, setSaving] = useState(false);
const [step, setStep] = useState(1);
const requestExit = () => {
if (editor.dirty) setConfirmExit(true);
@@ -130,6 +195,17 @@ export default function PlanEditor() {
? 'Tydzień startu nie może być w przeszłości'
: '';
// Krok 1 blokuje przejście: pusty tytuł lub start w przeszłości. Krok 2 → 3 zawsze.
const step1Valid = editor.title.trim() !== '' && !startWeekError;
const goToStep = (n: number) => {
if (n <= step) {
setStep(n);
return;
}
if (n === 2 && step1Valid) setStep(2);
if (n === 3 && step1Valid) setStep(3);
};
// Podsumowanie stopki: dni/ćwiczenia/serie + tygodnie bez ćwiczeń (nie blokuje)
const totals = useMemo(() => {
let days = 0;
@@ -206,29 +282,30 @@ export default function PlanEditor() {
setError(`Plan ma ${editor.weeksCount} tygodni — zdefiniuj je wszystkie`);
return;
}
const body: { title: string; weeksCount: number; weeks: PlanWeekInput[]; startDate?: string } =
{
title: editor.title.trim(),
weeksCount: editor.weeksCount,
weeks: editor.weeks.map((_, i) => ({
index: i,
days: displayedDaysOf(editor.weeks, i).map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e, oi) => ({
exerciseId: e.exerciseId,
order: oi,
sets: e.sets.map((s, si) => ({
index: si,
reps: s.reps ? parseInt(s.reps) : null,
loadKg: s.loadKg ? parseFloat(s.loadKg) : null,
restSec: s.restSec ? parseInt(s.restSec) : null,
rir: s.rir !== '' ? parseInt(s.rir) : null,
difficulty: s.difficulty ? parseInt(s.difficulty) : null,
})),
const body: PlanBody = {
title: editor.title.trim(),
weeksCount: editor.weeksCount,
gymId: editor.gymId,
weeks: editor.weeks.map((w, i) => ({
index: i,
customName: w.customName.trim() || null,
days: displayedDaysOf(editor.weeks, i).map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e, oi) => ({
exerciseId: e.exerciseId,
order: oi,
sets: e.sets.map((s, si) => ({
index: si,
reps: s.reps ? parseInt(s.reps) : null,
loadKg: s.loadKg ? parseFloat(s.loadKg) : null,
restSec: s.restSec ? parseInt(s.restSec) : null,
rir: s.rir !== '' ? parseInt(s.rir) : null,
difficulty: s.difficulty ? parseInt(s.difficulty) : null,
})),
})),
})),
};
})),
};
// Data startu tylko przy tworzeniu — plan tworzony i aktywowany w jednym kroku.
// Tydzień startu: bieżący lub przyszły (WeekPicker blokuje minione; guard zapasowy).
if (!isEdit && editor.startDate) {
@@ -281,136 +358,211 @@ export default function PlanEditor() {
return <EditorSkeleton />;
}
// Opcje siłowni: tryb własny = useGyms (cłonkostwa zalogowanego),
// tryb trenera = gyms z detalu podopiecznego (cłonkostwa podopiecznego).
const gymOptions = isTraineeMode
? (traineeData?.gyms ?? [])
: (gymsData?.gyms ?? []).map((g) => ({ id: g.id, name: g.name }));
const gymName = gymOptions.find((g) => g.id === editor.gymId)?.name ?? null;
const week = editor.weeks[activeWi];
const weekDays = displayedDaysOf(editor.weeks, activeWi);
const weekSummaryActive = weekSummary(activeWi, week, weekDays);
return (
<>
<div className="flex justify-end mb-4">
<div className="flex items-center justify-between gap-2 mb-4">
<BackButton onClick={requestExit} />
<WizardStepper step={step} onGo={goToStep} />
</div>
<PlanMetaForm
title={editor.title}
onTitleChange={editor.setTitle}
onTitleBlur={() => setTitleTouched(true)}
titleError={titleError}
weeksCount={editor.weeksCount}
onWeeksCountChange={editor.setWeeksCount}
startDate={editor.startDate}
onStartDateChange={editor.setStartDate}
startWeekError={startWeekError}
showStartWeek={!isEdit}
/>
{/* Zakładki tygodni (sticky pod topbarem): każdy tydzień z osobna,
renderowany jest tylko panel aktywnej zakładki */}
<div className="sticky top-[55px] md:top-[59px] z-20 -mx-4 px-4 md:-mx-8 md:px-8 py-2 bg-bg/95 backdrop-blur">
<Tabs
tabs={editor.weeks.map((w, wi) => ({
id: String(wi),
label: (
<span className="inline-flex items-center gap-1.5">
<span className="sm:hidden">T.{wi + 1}</span>
<span className="hidden sm:inline">Tydzień {wi + 1}</span>
<span
aria-hidden="true"
className={cn(
'h-2 w-2 rounded-full',
DOT_COLORS[weekSummary(wi, w, displayedDaysOf(editor.weeks, wi)).color],
)}
/>
</span>
),
}))}
active={String(activeWi)}
onChange={(id) => setActiveWeek(parseInt(id, 10))}
{step === 1 && (
<PlanMetaForm
title={editor.title}
onTitleChange={editor.setTitle}
onTitleBlur={() => setTitleTouched(true)}
titleError={titleError}
weeksCount={editor.weeksCount}
onWeeksCountChange={editor.setWeeksCount}
startDate={editor.startDate}
onStartDateChange={editor.setStartDate}
startWeekError={startWeekError}
showStartWeek={!isEdit}
/>
</div>
)}
<div ref={panelRef} className="scroll-mt-28">
<WeekPanel
index={activeWi}
summary={weekSummaryActive}
canCopy={activeWi > 0}
onCopyPrev={() => editor.copyPrevWeek(activeWi)}
canClear={weekDays.length > 0 || !week.detached}
onClear={() => setClearWeekIdx(activeWi)}
>
<DayPicker
days={weekDays}
onAddDay={(dow) => editor.addDay(activeWi, dow)}
onRemoveDay={(dow) => {
const day = weekDays.find((d) => d.dayOfWeek === dow);
// dzień z ćwiczeniami: potwierdzenie (tap na mobile nie może być destrukcyjny)
if (day && day.exercises.length > 0) setRemoveDayReq({ wi: activeWi, dow });
else editor.removeDay(activeWi, dow);
}}
/>
{step === 2 && (
<>
{/* Wybór siłowni (informacyjny) — z członkostw właściciela planu */}
<Card className="mb-4">
<Field label="Siłownia">
{gymOptions.length > 0 ? (
<Select
value={editor.gymId ?? ''}
onChange={(e) => editor.setGymId(e.target.value || null)}
>
<option value="">Bez siłowni</option>
{gymOptions.map((g) => (
<option key={g.id} value={g.id}>
{g.name}
</option>
))}
</Select>
) : (
<p className="text-dim text-[0.875rem] py-1">
{isTraineeMode ? (
'Podopieczny nie należy do żadnej siłowni.'
) : (
<>
Nie należysz do żadnej siłowni.{' '}
<Link to="/gyms" className="text-accent-text underline">
Zarządzaj siłowniami
</Link>
</>
)}
</p>
)}
</Field>
</Card>
{weekDays.length === 0 && (
<EmptyState
icon={CalendarX}
title="Brak dni treningowych"
description={
activeWi === 0
? 'Wybierz dni treningowe powyżej — pozostałe tygodnie będą je odzwierciedlać.'
: week.detached
? 'Tydzień wolny (przerwa) — pozostanie pusty.'
: 'Odzwierciedla tydzień 1. Kliknij dzień, aby edytować niezależnie.'
}
{/* Zakładki tygodni (sticky pod topbarem): każdy tydzień z osobna,
renderowany jest tylko panel aktywnej zakładki */}
<div className="sticky top-[55px] md:top-[59px] z-20 -mx-4 px-4 md:-mx-8 md:px-8 py-2 bg-bg/95 backdrop-blur">
<Tabs
tabs={editor.weeks.map((w, wi) => ({
id: String(wi),
label: (
<span className="inline-flex items-center gap-1.5">
<span className="sm:hidden">T.{wi + 1}</span>
<span className="hidden sm:inline">Tydzień {wi + 1}</span>
<span
aria-hidden="true"
className={cn(
'h-2 w-2 rounded-full',
DOT_COLORS[weekSummary(wi, w, displayedDaysOf(editor.weeks, wi)).color],
)}
/>
</span>
),
}))}
active={String(activeWi)}
onChange={(id) => setActiveWeek(parseInt(id, 10))}
/>
)}
</div>
{weekDays.length > 0 && (
<div className="mt-3 divide-y divide-line">
{weekDays.map((d, di) => (
<DayEditor
key={d.dayOfWeek}
day={d}
weekIndex={activeWi}
dayIndex={di}
exerciseName={exerciseName}
isTraineeMode={isTraineeMode}
exercises={exercises}
exercisesLoading={exData === undefined}
resultsOpenKey={resultsOpenKey}
onToggleResults={(ei) => {
const key = `${activeWi}:${di}:${ei}`;
setResultsOpenKey(resultsOpenKey === key ? null : key);
}}
onAddExercise={(exerciseId) => editor.addExercise(activeWi, di, exerciseId)}
onRemoveExercise={(ei) => editor.removeExercise(activeWi, di, ei)}
onMoveExercise={(ei, dir) => editor.moveExercise(activeWi, di, ei, dir)}
onSetField={(ei, si, field, value) =>
editor.setSetField(activeWi, di, ei, si, field, value)
<div ref={panelRef} className="scroll-mt-28">
<WeekPanel
index={activeWi}
summary={weekSummaryActive}
canCopy={activeWi > 0}
onCopyPrev={() => editor.copyPrevWeek(activeWi)}
canClear={weekDays.length > 0 || !week.detached}
onClear={() => setClearWeekIdx(activeWi)}
alias={week.customName}
onAliasChange={(v) => editor.setWeekAlias(activeWi, v)}
>
<DayPicker
days={weekDays}
onAddDay={(dow) => editor.addDay(activeWi, dow)}
onRemoveDay={(dow) => {
const day = weekDays.find((d) => d.dayOfWeek === dow);
// dzień z ćwiczeniami: potwierdzenie (tap na mobile nie może być destrukcyjny)
if (day && day.exercises.length > 0) setRemoveDayReq({ wi: activeWi, dow });
else editor.removeDay(activeWi, dow);
}}
/>
{weekDays.length === 0 && (
<EmptyState
icon={CalendarX}
title="Brak dni treningowych"
description={
activeWi === 0
? 'Wybierz dni treningowe powyżej — pozostałe tygodnie będą je odzwierciedlać.'
: week.detached
? 'Tydzień wolny (przerwa) — pozostanie pusty.'
: 'Odzwierciedla tydzień 1. Kliknij dzień, aby edytować niezależnie.'
}
onAddSet={(ei) => editor.addSet(activeWi, di, ei)}
onRemoveSet={(ei, si) => editor.removeSet(activeWi, di, ei, si)}
onDuplicateSet={(ei, si) => editor.duplicateSet(activeWi, di, ei, si)}
latestByExercise={latestByExercise}
progressByExercise={progressByExercise}
onPrefill={(ei) => {
const latest = latestByExercise.get(d.exercises[ei].exerciseId);
if (latest) editor.prefillExercise(activeWi, di, ei, latest);
}}
/>
))}
</div>
)}
</WeekPanel>
</div>
)}
{weekDays.length > 0 && (
<div className="mt-3 divide-y divide-line">
{weekDays.map((d, di) => (
<DayEditor
key={d.dayOfWeek}
day={d}
weekIndex={activeWi}
dayIndex={di}
exerciseName={exerciseName}
isTraineeMode={isTraineeMode}
exercises={exercises}
exercisesLoading={exData === undefined}
resultsOpenKey={resultsOpenKey}
onToggleResults={(ei) => {
const key = `${activeWi}:${di}:${ei}`;
setResultsOpenKey(resultsOpenKey === key ? null : key);
}}
onAddExercise={(exerciseId) => editor.addExercise(activeWi, di, exerciseId)}
onRemoveExercise={(ei) => editor.removeExercise(activeWi, di, ei)}
onMoveExercise={(ei, dir) => editor.moveExercise(activeWi, di, ei, dir)}
onSetField={(ei, si, field, value) =>
editor.setSetField(activeWi, di, ei, si, field, value)
}
onAddSet={(ei) => editor.addSet(activeWi, di, ei)}
onRemoveSet={(ei, si) => editor.removeSet(activeWi, di, ei, si)}
onDuplicateSet={(ei, si) => editor.duplicateSet(activeWi, di, ei, si)}
latestByExercise={latestByExercise}
progressByExercise={progressByExercise}
onPrefill={(ei) => {
const latest = latestByExercise.get(d.exercises[ei].exerciseId);
if (latest) editor.prefillExercise(activeWi, di, ei, latest);
}}
/>
))}
</div>
)}
</WeekPanel>
</div>
</>
)}
{step === 3 && (
<PlanSummary
title={editor.title}
gymName={gymName}
startDate={isEdit ? '' : editor.startDate}
weeks={editor.weeks}
/>
)}
{/* sticky stopka; na mobile pod stałym dolnym paskiem topmenu (+ safe-area) */}
<div className="sticky bottom-0 -mx-4 px-4 py-3 bg-bg/95 backdrop-blur border-t border-line mt-2 md:-mx-8 md:px-8 max-md:bottom-[calc(43px+max(0.5rem,env(safe-area-inset-bottom)))]">
{error && <ErrorText>{error}</ErrorText>}
<div className="text-dim text-[0.8125rem]">
{dayCountLabel(totals.days)} · {exerciseCountLabel(totals.exercises)} ·{' '}
{setCountLabel(totals.sets)}
{totals.emptyWeeks > 0 && (
<span className="text-warn"> · {weekCountLabel(totals.emptyWeeks)} bez ćwiczeń</span>
)}
<div className="flex flex-col gap-2 sm:flex-row sm:items-center">
<div className="text-dim text-[0.8125rem]">
{dayCountLabel(totals.days)} · {exerciseCountLabel(totals.exercises)} ·{' '}
{setCountLabel(totals.sets)}
{totals.emptyWeeks > 0 && (
<span className="text-warn"> · {weekCountLabel(totals.emptyWeeks)} bez ćwiczeń</span>
)}
</div>
<div className="flex items-center gap-2 sm:ml-auto">
{step > 1 && (
<Button variant="secondary" onClick={() => setStep(step - 1)}>
Wstecz
</Button>
)}
{step < 3 ? (
<Button onClick={() => goToStep(step + 1)} disabled={step === 1 && !step1Valid}>
Dalej
</Button>
) : (
<Button onClick={() => save()} disabled={saving}>
{isEdit ? 'Zapisz zmiany' : 'Zapisz'}
</Button>
)}
</div>
</div>
</div>

View File

@@ -0,0 +1,89 @@
import { MapPin } from 'lucide-react';
import { Badge, Card, H2, H3 } from '../../../components/ui';
import {
DAY_NAMES,
dayCountLabel,
exerciseCountLabel,
setCountLabel,
weekCountLabel,
} from '../../../lib/labels';
import { fmtDate } from '../../../lib/format';
import { displayedDaysOf, type EditorWeek } from './types';
/**
* Krok 3 wizarda: przejrzysty przegląd całego planu przed zapisem.
* Puste tygodnie nie blokują zapisu — są oznaczone ostrzeżeniem.
*/
export function PlanSummary({
title,
gymName,
startDate,
weeks,
}: {
title: string;
gymName: string | null;
/** '' = szkic bez tygodnia startu. */
startDate: string;
weeks: EditorWeek[];
}) {
const rows = weeks.map((w, i) => {
const days = displayedDaysOf(weeks, i);
let exercises = 0;
let sets = 0;
days.forEach((d) => {
exercises += d.exercises.length;
d.exercises.forEach((e) => {
sets += e.sets.length;
});
});
return { i, alias: w.customName.trim(), days, exercises, sets };
});
const totals = rows.reduce(
(acc, r) => ({
days: acc.days + r.days.length,
exercises: acc.exercises + r.exercises,
sets: acc.sets + r.sets,
empty: acc.empty + (r.exercises === 0 ? 1 : 0),
}),
{ days: 0, exercises: 0, sets: 0, empty: 0 },
);
return (
<Card>
<H2>{title || 'Bez tytułu'}</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 ?? 'bez siłowni'}
</span>
<span>{startDate ? `start: ${fmtDate(startDate)}` : 'szkic — bez startu'}</span>
</div>
<div className="mt-4 divide-y divide-line">
{rows.map((r) => (
<div key={r.i} className="py-2.5">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<H3 className="mb-0">{r.alias || `Tydzień ${r.i + 1}`}</H3>
{r.exercises === 0 && <Badge color="yellow">bez ćwiczeń</Badge>}
<span className="text-dim text-[0.8125rem] sm:ml-auto">
{r.days.length > 0
? `${r.days.map((d) => DAY_NAMES[d.dayOfWeek].slice(0, 3)).join(', ')} · `
: ''}
{dayCountLabel(r.days.length)} · {exerciseCountLabel(r.exercises)} ·{' '}
{setCountLabel(r.sets)}
</span>
</div>
</div>
))}
</div>
<div className="mt-3 border-t border-line pt-3 text-dim text-[0.875rem]">
Łącznie: {dayCountLabel(totals.days)} · {exerciseCountLabel(totals.exercises)} ·{' '}
{setCountLabel(totals.sets)}
{totals.empty > 0 && (
<span className="text-warn"> · {weekCountLabel(totals.empty)} bez ćwiczeń</span>
)}
</div>
</Card>
);
}

View File

@@ -1,9 +1,10 @@
import type { ReactNode } from 'react';
import { Copy, Trash2 } from 'lucide-react';
import { Badge, Button, Card, H2, type BadgeColor } from '../../../components/ui';
import { Badge, Button, Card, Field, H2, Input, type BadgeColor } from '../../../components/ui';
/* Panel tygodnia (zamiast akordeonu): nagłówek z badge podsumowania + akcje,
treść zawsze widoczna — przełączanie tygodni odbywa się przez zakładki. */
opcjonalny alias tygodnia, treść zawsze widoczna — przełączanie tygodni
odbywa się przez zakładki. */
export function WeekPanel({
index,
summary,
@@ -11,6 +12,8 @@ export function WeekPanel({
onCopyPrev,
canClear,
onClear,
alias,
onAliasChange,
children,
}: {
index: number;
@@ -19,6 +22,9 @@ export function WeekPanel({
onCopyPrev: () => void;
canClear: boolean;
onClear: () => void;
/** Opcjonalny alias tygodnia (np. „Deload"); undefined = pole ukryte. */
alias?: string;
onAliasChange?: (v: string) => void;
children: ReactNode;
}) {
return (
@@ -41,6 +47,18 @@ export function WeekPanel({
)}
</div>
</div>
{alias !== undefined && onAliasChange && (
<div className="mt-4 max-w-xs">
<Field label="Nazwa tygodnia (opcjonalnie)">
<Input
value={alias}
onChange={(e) => onAliasChange(e.target.value)}
placeholder="np. Deload"
maxLength={40}
/>
</Field>
</div>
)}
<div className="mt-4">{children}</div>
</Card>
);

View File

@@ -19,12 +19,20 @@ export interface EditorDay {
export interface EditorWeek {
days: EditorDay[];
detached: boolean;
/** Opcjonalny alias tygodnia (np. „Deload"); '' = bez aliasu. */
customName: string;
}
export const DEFAULT_SET: EditorSet = { reps: '10', loadKg: '20', restSec: '90', rir: '2', difficulty: '3' };
export const DEFAULT_SET: EditorSet = {
reps: '10',
loadKg: '20',
restSec: '90',
rir: '2',
difficulty: '3',
};
export function emptyWeek(): EditorWeek {
return { days: [], detached: false };
return { days: [], detached: false, customName: '' };
}
export function displayedDaysOf(ws: EditorWeek[], wi: number): EditorDay[] {
@@ -33,8 +41,25 @@ export function displayedDaysOf(ws: EditorWeek[], wi: number): EditorDay[] {
return ws[0].days;
}
export function weekFromApi(week: { index: number; days: { dayOfWeek: number; exercises: { exerciseId: string; sets: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null; difficulty: number | null }[] }[] }[] }): EditorWeek {
export function weekFromApi(week: {
index: number;
customName?: string | null;
days: {
dayOfWeek: number;
exercises: {
exerciseId: string;
sets: {
reps: number | null;
loadKg: number | null;
restSec: number | null;
rir: number | null;
difficulty: number | null;
}[];
}[];
}[];
}): EditorWeek {
return {
customName: week.customName ?? '',
days: week.days.map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e) => ({

View File

@@ -6,6 +6,8 @@ import { DEFAULT_SET, emptyWeek, weekFromApi, type EditorSet, type EditorWeek }
export interface PlanLike {
title: string;
weeksCount: number;
/** Informacyjna — siłownia planu; null = bez siłowni. */
gym?: { id: string; name: string } | null;
weeks: Parameters<typeof weekFromApi>[0][];
}
@@ -21,17 +23,19 @@ export function usePlanEditorState() {
const [weeks, setWeeks] = useState<EditorWeek[]>(() =>
Array.from({ length: 4 }, () => emptyWeek()),
);
// Siłownia planu (informacyjna): null = „bez siłowni”.
const [gymId, setGymIdState] = useState<string | null>(null);
const [initialized, setInitialized] = useState(false);
// snapshot startowy: tryb nowy = stan początkowy; tryb edycji = po initFromPlan
const snapshotRef = useRef<string | null>(null);
if (snapshotRef.current === null) {
snapshotRef.current = JSON.stringify({ title, startDate, weeksCount, weeks });
snapshotRef.current = JSON.stringify({ title, startDate, weeksCount, weeks, gymId });
}
const dirty = useMemo(
() => JSON.stringify({ title, startDate, weeksCount, weeks }) !== snapshotRef.current,
[title, startDate, weeksCount, weeks],
() => JSON.stringify({ title, startDate, weeksCount, weeks, gymId }) !== snapshotRef.current,
[title, startDate, weeksCount, weeks, gymId],
);
/** Inicjalizacja trybu edycji po załadowaniu danych (zamiast setState during render). */
@@ -40,17 +44,20 @@ export function usePlanEditorState() {
setTitleState(plan.title);
setWeeksCountState(plan.weeksCount);
setWeeks(loaded);
setGymIdState(plan.gym?.id ?? null);
snapshotRef.current = JSON.stringify({
title: plan.title,
startDate: '',
weeksCount: plan.weeksCount,
weeks: loaded,
gymId: plan.gym?.id ?? null,
});
setInitialized(true);
}, []);
const setTitle = useCallback((v: string) => setTitleState(v), []);
const setStartDate = useCallback((v: string) => setStartDateState(v), []);
const setGymId = useCallback((v: string | null) => setGymIdState(v), []);
const setWeeksCount = useCallback((n: number) => {
setWeeksCountState(n);
@@ -58,7 +65,7 @@ export function usePlanEditorState() {
const next = [...ws];
while (next.length < n) {
const prev = next[next.length - 1] ?? emptyWeek();
next.push({ days: structuredClone(prev.days), detached: true });
next.push({ days: structuredClone(prev.days), detached: true, customName: '' });
}
return next.slice(0, n);
});
@@ -242,7 +249,12 @@ export function usePlanEditorState() {
if (wi === 0) return;
setWeeks((ws) => {
const prevDays = ws[wi - 1].detached ? ws[wi - 1].days : ws[0].days;
return ws.map((w, i) => (i === wi ? { days: structuredClone(prevDays), detached: true } : w));
// Alias tygodnia jest specyficzny — nie jest kopiowany z poprzedniego tygodnia.
return ws.map((w, i) =>
i === wi
? { days: structuredClone(prevDays), detached: true, customName: w.customName }
: w,
);
});
}, []);
@@ -252,16 +264,24 @@ export function usePlanEditorState() {
[],
);
/** Alias tygodnia (np. „Deload”) — bez odłączania dni od lustrzanego tygodnia 1. */
const setWeekAlias = useCallback((wi: number, v: string) => {
setWeeks((ws) => ws.map((w, i) => (i === wi ? { ...w, customName: v.slice(0, 40) } : w)));
}, []);
return {
title,
startDate,
weeksCount,
weeks,
gymId,
initialized,
dirty,
setTitle,
setStartDate,
setGymId,
setWeeksCount,
setWeekAlias,
initFromPlan,
addDay,
removeDay,

View File

@@ -39,7 +39,11 @@ export function TraineePlansTab({ userId }: { userId: string }) {
const { data, isLoading, error } = useTraineePlans(userId);
const { data: meData } = useMe();
const [selectedId, setSelectedId] = useState<string | null>(null);
const { data: detail, isLoading: detailLoading, error: detailError } = useTraineePlan(userId, selectedId ?? '');
const {
data: detail,
isLoading: detailLoading,
error: detailError,
} = useTraineePlan(userId, selectedId ?? '');
const [startDate, setStartDate] = useState('');
const [actionError, setActionError] = useState('');
const [busy, setBusy] = useState(false);
@@ -96,7 +100,10 @@ export function TraineePlansTab({ userId }: { userId: string }) {
const st = PLAN_STATUS[p.status];
const isSel = p.id === selectedId;
return (
<div key={p.id} className={isSel ? 'rounded-xl bg-accent/10 px-2 py-3' : 'px-1 py-3'}>
<div
key={p.id}
className={isSel ? 'rounded-xl bg-accent/10 px-2 py-3' : 'px-1 py-3'}
>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<button
type="button"
@@ -107,8 +114,12 @@ export function TraineePlansTab({ userId }: { userId: string }) {
</button>
<Badge color={st.color}>{st.label}</Badge>
<Muted className="text-[0.875rem]">{p.weeksCount} tyg.</Muted>
{p.startDate && <Muted className="text-[0.875rem]">start {fmtDate(p.startDate)}</Muted>}
{creatorLabel(p) && <Muted className="text-[0.875rem]">{creatorLabel(p)}</Muted>}
{p.startDate && (
<Muted className="text-[0.875rem]">start {fmtDate(p.startDate)}</Muted>
)}
{creatorLabel(p) && (
<Muted className="text-[0.875rem]">{creatorLabel(p)}</Muted>
)}
</div>
{isSel && (
@@ -125,10 +136,18 @@ export function TraineePlansTab({ userId }: { userId: string }) {
actionError={actionError}
startDate={startDate}
onStartDateChange={setStartDate}
onActivate={() => setConfirm({ type: 'activate', planId: selectedDetail.id })}
onDelete={() => setConfirm({ type: 'delete', planId: selectedDetail.id })}
onComplete={() => setConfirm({ type: 'complete', planId: selectedDetail.id })}
onAbandon={() => setConfirm({ type: 'abandon', planId: selectedDetail.id })}
onActivate={() =>
setConfirm({ type: 'activate', planId: selectedDetail.id })
}
onDelete={() =>
setConfirm({ type: 'delete', planId: selectedDetail.id })
}
onComplete={() =>
setConfirm({ type: 'complete', planId: selectedDetail.id })
}
onAbandon={() =>
setConfirm({ type: 'abandon', planId: selectedDetail.id })
}
activateDisabled={hasActivePlan}
hint={
hasActivePlan
@@ -139,8 +158,13 @@ export function TraineePlansTab({ userId }: { userId: string }) {
</div>
{selectedDetail.weeks.map((w) => (
<div key={w.id} className="mb-3">
<H3 className="mb-1.5">Tydzień {w.index + 1}</H3>
{w.days.length === 0 && <p className="text-dim">Brak dni treningowych.</p>}
<div className="mb-1.5 flex items-center gap-2">
<H3 className="mb-0">Tydzień {w.index + 1}</H3>
{w.customName && <Badge color="blue">{w.customName}</Badge>}
</div>
{w.days.length === 0 && (
<p className="text-dim">Brak dni treningowych.</p>
)}
<div className="divide-y divide-line">
{w.days.map((d) => (
<PlanDayRow key={d.id} day={d} showDate />

View File

@@ -40,7 +40,7 @@ interface Capture {
createPlanBody?: Record<string, unknown>;
}
function mockApi(capture: Capture) {
function mockApi(capture: Capture, gyms: { id: string; name: string }[] = []) {
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
@@ -62,7 +62,7 @@ function mockApi(capture: Capture) {
extra: null,
missing: null,
});
if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] });
if (url.includes('/gyms')) return jsonResponse(200, { gyms });
if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] });
if (url.includes('/plans/plan-new'))
return jsonResponse(200, {
@@ -212,6 +212,70 @@ describe('PlanEditor — data startu i menu kontekstowe', () => {
expect(capture.createPlanBody).not.toHaveProperty('startDate');
});
it('wizard: krok 1 blokuje „Dalej” bez tytułu; select siłowni z /gyms; zapis z gymId i aliasem', async () => {
const capture: Capture = {};
mockApi(capture, [{ id: 'gym-1', name: 'Siłownia Testowa' }]);
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
// krok 1: „Dalej” zablokowany przy pustym tytule
expect(screen.getByRole('button', { name: 'Dalej' })).toBeDisabled();
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan wizard');
expect(screen.getByRole('button', { name: 'Dalej' })).toBeEnabled();
// 1 tydzień — podsumowanie bez lustrzanych tygodni
const weeksField = screen.getByText('Długość (tygodnie)').closest('[data-slot="field"]') as HTMLElement;
await user.selectOptions(within(weeksField).getByRole('combobox'), '1');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// krok 2: select siłowni (cłonkostwa zalogowanego) + dzień + ćwiczenie + alias
const gymField = screen.getByText('Siłownia').closest('[data-slot="field"]') as HTMLElement;
const gymSelect = within(gymField).getByRole('combobox');
expect(within(gymSelect).getByRole('option', { name: 'Bez siłowni' })).toBeInTheDocument();
expect(within(gymSelect).getByRole('option', { name: 'Siłownia Testowa' })).toBeInTheDocument();
await user.selectOptions(gymSelect, 'gym-1');
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
await user.click(await screen.findByRole('option', { name: /Przysiady/ }));
const aliasField = screen
.getByText('Nazwa tygodnia (opcjonalnie)')
.closest('[data-slot="field"]') as HTMLElement;
await user.type(within(aliasField).getByRole('textbox'), 'Deload');
// krok 3: podsumowanie — siłownia, alias, „szkic — bez startu”, liczniki
await user.click(screen.getByRole('button', { name: 'Dalej' }));
expect(await screen.findByText('Deload')).toBeInTheDocument();
expect(screen.getByText('Siłownia Testowa')).toBeInTheDocument();
expect(screen.getByText('szkic — bez startu')).toBeInTheDocument();
// liczniki w karcie podsumowania (w stopce jest identyczny tekst — zakres = karta)
const summaryCard = screen
.getByText('Łącznie: 1 dzień · 1 ćwiczenie · 1 seria')
.closest('[data-slot="card"]') as HTMLElement;
expect(within(summaryCard).getByText('Pon · 1 dzień · 1 ćwiczenie · 1 seria')).toBeInTheDocument();
// zapis — body z gymId i customName
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
await waitFor(() => expect(capture.createPlanBody).toBeDefined());
expect(capture.createPlanBody).toMatchObject({
title: 'Plan wizard',
gymId: 'gym-1',
weeks: [expect.objectContaining({ index: 0, customName: 'Deload' })],
});
});
it('wizard: pusta lista siłowni — informacja z linkiem do /gyms', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
expect(screen.getByText('Nie należysz do żadnej siłowni.')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Zarządzaj siłowniami' })).toBeInTheDocument();
});
it('pokazuje „Wstecz” w treści formularza na /plans/new', async () => {
mockApi({});
const user = userEvent.setup();

View File

@@ -405,6 +405,7 @@ export const TEST_TRAINEE_PLANS = [
status: 'DRAFT',
weeksCount: 1,
startDate: null,
gym: null,
creator: { id: 'trainer-2', firstName: 'Jan', lastName: 'Kowalski' },
weeks: [],
},
@@ -414,6 +415,7 @@ export const TEST_TRAINEE_PLANS = [
status: 'ACTIVE',
weeksCount: 4,
startDate: '2026-08-24',
gym: { id: 'gym-1', name: 'Żelazna Świątynia' },
creator: null,
weeks: [],
},
@@ -425,11 +427,13 @@ export const TEST_TRAINEE_PLAN_DETAIL = {
status: 'DRAFT',
weeksCount: 1,
startDate: null,
gym: null,
creator: { id: 'trainer-2', firstName: 'Jan', lastName: 'Kowalski' },
weeks: [
{
id: 'tw-1',
index: 0,
customName: null,
days: [
{
id: 'td-1',
@@ -461,11 +465,13 @@ export const TEST_TRAINEE_PLAN_DETAIL_ACTIVE = {
status: 'ACTIVE',
weeksCount: 4,
startDate: '2026-08-24',
gym: { id: 'gym-1', name: 'Żelazna Świątynia' },
creator: null,
weeks: [
{
id: 'tw-1',
index: 0,
customName: null,
days: [
{
id: 'td-1',
@@ -1380,6 +1386,7 @@ export function mockPlans(page: Page) {
status: 'ACTIVE',
weeksCount: 4,
startDate: '2026-08-24',
gym: null,
weeks: [],
},
}),
@@ -1388,10 +1395,18 @@ export function mockPlans(page: Page) {
page.route('**/api/v1/plans', (route) => {
const req = route.request();
if (req.method() === 'POST') {
// echo gymId z ciała żądania (customName w tygodniach nie ma wpływu na odpowiedź)
let gym: { id: string; name: string } | null = null;
try {
const body = req.postDataJSON() as { gymId?: string | null };
if (body.gymId) gym = { id: body.gymId, name: 'Żelazna Świątynia' };
} catch {
// brak ciała — bez siłowni
}
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ plan: { id: 'plan-new' } }),
body: JSON.stringify({ plan: { id: 'plan-new', gym } }),
});
}
return route.fulfill({
@@ -1445,7 +1460,19 @@ export function mockTraineePlans(page: Page, opts: MockApiOptions = {}) {
page.route('**/api/v1/trainer/trainees/*/plans', (route) => {
const req = route.request();
if (req.method() === 'POST') {
return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ plan: { id: 'tp-new' } }) });
// echo gymId z ciała żądania (customName w tygodniach nie ma wpływu na odpowiedź)
let gym: { id: string; name: string } | null = null;
try {
const body = req.postDataJSON() as { gymId?: string | null };
if (body.gymId) gym = { id: body.gymId, name: 'Żelazna Świątynia' };
} catch {
// brak ciała — bez siłowni
}
return route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ plan: { id: 'tp-new', gym } }),
});
}
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ plans: TEST_TRAINEE_PLANS }) });
});

View File

@@ -0,0 +1,94 @@
import { test, expect, type Page } from './fixtures';
import { mockPlans } from './mock-api';
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();
}
async function openNewPlan(page: Page) {
await page.getByRole('link', { name: 'Plany' }).click();
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await expect(page.getByRole('heading', { name: 'Nowy plan' })).toBeVisible();
}
test('wizard: 3 kroki — szczegóły, ćwiczenia (siłownia + alias), podsumowanie i zapis', async ({
page,
}) => {
mockPlans(page);
await login(page);
await openNewPlan(page);
// stepper: 3 kroki, krok 1 aktywny
await expect(page.getByRole('button', { name: 'Szczegóły' })).toBeVisible();
await expect(page.getByRole('button', { name: 'Ćwiczenia' })).toBeVisible();
await expect(page.getByRole('button', { name: 'Podsumowanie' })).toBeVisible();
// krok 1: „Dalej” zablokowany przy pustym tytule
await expect(page.getByRole('button', { name: 'Dalej' })).toBeDisabled();
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan wizard');
await expect(page.getByRole('button', { name: 'Dalej' })).toBeEnabled();
await page.getByRole('button', { name: 'Dalej' }).click();
// krok 2: select siłowni (cłonkostwa zalogowanego — mock: Żelazna Świątynia)
const gymSelect = page.locator('select').first();
await expect(gymSelect).toBeVisible();
await expect(gymSelect.locator('option')).toHaveText(['Bez siłowni', 'Żelazna Świątynia']);
await gymSelect.selectOption({ label: 'Żelazna Świątynia' });
// dzień + ćwiczenie + alias tygodnia
await page.getByRole('button', { name: 'Pon' }).click();
await page.getByRole('button', { name: 'dodaj ćwiczenie…' }).click();
await page.getByRole('option', { name: /Przysiady/ }).click();
const aliasInput = page.getByPlaceholder('np. Deload');
await aliasInput.fill('Deload');
// krok 3: podsumowanie — alias, siłownia, liczniki; „Zapisz” tylko tutaj
await page.getByRole('button', { name: 'Dalej' }).click();
await expect(page.getByRole('heading', { name: 'Deload' })).toBeVisible();
await expect(page.getByText('Żelazna Świątynia')).toBeVisible();
await expect(page.getByText('szkic — bez startu')).toBeVisible();
await expect(page.getByRole('button', { name: 'Zapisz' })).toBeVisible();
// zapis: ciało POST /plans z gymId i customName
const [request] = await Promise.all([
page.waitForRequest((r) => r.url().includes('/api/v1/plans') && r.method() === 'POST'),
page.getByRole('button', { name: 'Zapisz' }).click(),
]);
const body = request.postDataJSON() as {
title: string;
gymId: string | null;
weeks: { index: number; customName: string | null }[];
};
expect(body.title).toBe('Plan wizard');
expect(body.gymId).toBe('gym-1');
expect(body.weeks[0]).toMatchObject({ index: 0, customName: 'Deload' });
// po utworzeniu — szczegóły planu
await expect(page.getByRole('heading', { name: 'Plan e2e' })).toBeVisible();
});
test('wizard: zwrot do kroku 1 ze steppera i ostrzeżenie o pustych tygodniach w podsumowaniu', async ({
page,
}) => {
mockPlans(page);
await login(page);
await openNewPlan(page);
// krok 2 bez ćwiczeń: podsumowanie pokazuje ostrzeżenie o pustych tygodniach
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan pusty');
await page.getByRole('button', { name: 'Dalej' }).click();
// zwrot do kroku 1 przez stepper
await page.getByRole('button', { name: 'Szczegóły' }).click();
await expect(page.getByPlaceholder('np. Plan masowy 8-tygodniowy')).toBeVisible();
// z powrotem do podsumowania (krok 2 → 3)
await page.getByRole('button', { name: 'Ćwiczenia' }).click();
await page.getByRole('button', { name: 'Dalej' }).click();
// ostrzeżenie o pustych tygodniach w karcie podsumowania („Łącznie:” = unikalne)
await expect(
page.getByText('Łącznie: 0 dni · 0 ćwiczeń · 0 serii · 4 tygodnie bez ćwiczeń'),
).toBeVisible();
});

View File

@@ -30,7 +30,9 @@ test('mobile: tworzenie planu — bezpieczny tap dnia, bottom sheet, edycja seri
await login(page);
await openNewPlan(page);
// dodaj dzień (Poniedziałek)
// dodaj dzień (Poniedziałek) — krok 2 po tytule i przejściu „Dalej”
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
await page.getByRole('button', { name: 'Pon' }).click();
// dodaj ćwiczenie przez bottom sheet (Radix Dialog na mobile)
@@ -49,11 +51,10 @@ test('mobile: tworzenie planu — bezpieczny tap dnia, bottom sheet, edycja seri
await page.getByRole('button', { name: 'Usuń dzień' }).click();
await expect(page.getByText('Przysiady')).toHaveCount(0);
// ponownie dodaj dzień + ćwiczenie, utwórz plan
// ponownie dodaj dzień + ćwiczenie, utwórz plan (tytuł wpisany na kroku 1)
await page.getByRole('button', { name: 'Pon' }).click();
await page.getByRole('button', { name: 'dodaj ćwiczenie…' }).click();
await page.getByRole('option', { name: /Wyciskanie/ }).click();
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan mobile');
// „Zatwierdź plan" w grupie „Akcje" dolnego paska
await page.getByRole('button', { name: 'Akcje' }).click();
await page.getByRole('button', { name: 'Zatwierdź plan' }).click();
@@ -68,7 +69,9 @@ test('mobile 320px: brak poziomego scrolla w edytorze', async ({ page }) => {
await login(page);
await openNewPlan(page);
// dodaj dzień + ćwiczenie — tabela serii (min-w) nie może przelewać strony
// dodaj dzień + ćwiczenie (krok 2) — tabela serii (min-w) nie może przelewać strony
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
await page.getByRole('button', { name: 'Pon' }).click();
await page.getByRole('button', { name: 'dodaj ćwiczenie…' }).click();
await page.getByRole('option', { name: /Przysiady/ }).click();

View File

@@ -66,7 +66,9 @@ test('walidacja tytułu i podsumowanie stopki', async ({ page }) => {
await expect(page.getByText(/0 dni · 0 ćwiczeń · 0 serii/)).toBeVisible();
await expect(page.getByText(/4 tygodnie bez ćwiczeń/)).toBeVisible();
// dodaj dzień + ćwiczenie → podsumowanie się zmienia (tyg. 2–4 odzwierciedlają tyg. 1)
// dodaj dzień + ćwiczenie (krok 2) → podsumowanie się zmienia (tyg. 2–4 odzwierciedlają tyg. 1)
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
await page.getByRole('button', { name: 'Pon' }).click();
await page.getByRole('button', { name: 'dodaj ćwiczenie…' }).click();
await page.getByRole('option', { name: /Przysiady/ }).click();
@@ -82,7 +84,9 @@ test('zakładki tygodni: klik taba przełącza na dany tydzień', async ({ page
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await expect(page.getByRole('heading', { name: 'Nowy plan' })).toBeVisible();
// zakładki tygodni (4 tygodnie domyślnie)
// zakładki tygodni są na kroku 2 (4 tygodnie domyślnie)
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
await expect(page.getByRole('button', { name: 'Tydzień 1' })).toBeVisible();
await expect(page.getByRole('button', { name: 'Tydzień 4' })).toBeVisible();
@@ -102,7 +106,9 @@ test('zmiana kolejności ćwiczeń i kopiowanie serii', async ({ page }) => {
await page.getByRole('button', { name: 'Nowy plan' }).first().click();
await expect(page.getByRole('heading', { name: 'Nowy plan' })).toBeVisible();
// dodaj dzień i dwa ćwiczenia
// dodaj dzień i dwa ćwiczenia (krok 2)
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
await page.getByRole('button', { name: 'Pon' }).click();
await page.getByRole('button', { name: 'dodaj ćwiczenie…' }).click();
await page.getByRole('option', { name: /Przysiady/ }).click();

View File

@@ -85,7 +85,9 @@ test('edytor planu podopiecznego: „Wstaw wyniki" prefylluje serie z ostatniej
// (lista: akcja tworzenia w topbarze) — w edytorze zapis = „Zatwierdź plan"
await expect(page.getByRole('heading', { name: 'Plan dla podopiecznego' })).toBeVisible();
// dodaj dzień (Poniedziałek)
// dodaj dzień (Poniedziałek) — krok 2 po tytule i przejściu „Dalej”
await page.getByPlaceholder('np. Plan masowy 8-tygodniowy').fill('Plan');
await page.getByRole('button', { name: 'Dalej' }).click();
await page.getByRole('button', { name: 'Pon' }).click();
// dodaj ćwiczenie Przysiady (wyszukiwarka ćwiczeń zamiast selecta)
await page.getByRole('button', { name: 'dodaj ćwiczenie…' }).click();

View File

@@ -88,6 +88,47 @@ describe('usePlanEditorState — akcje mutacji', () => {
expect(sets[1].loadKg).toBe('20');
});
it('gymId: setGymId zmienia stan i dirty; initFromPlan wczytuje siłownię planu', () => {
const { result } = renderHook(() => usePlanEditorState());
expect(result.current.gymId).toBeNull();
act(() => result.current.setGymId('gym-1'));
expect(result.current.gymId).toBe('gym-1');
expect(result.current.dirty).toBe(true);
act(() => result.current.setGymId(null));
expect(result.current.gymId).toBeNull();
const plan: PlanLike = {
title: 'Plan',
weeksCount: 1,
gym: { id: 'gym-9', name: 'Siłownia' },
weeks: [{ index: 0, customName: 'Deload', days: [] }],
};
act(() => result.current.initFromPlan(plan));
expect(result.current.gymId).toBe('gym-9');
expect(result.current.weeks[0].customName).toBe('Deload');
expect(result.current.dirty).toBe(false);
});
it('setWeekAlias ustawia alias bez odłączania tygodnia; copyPrevWeek nie kopiuje aliasu', () => {
const { result } = renderHook(() => usePlanEditorState());
act(() => result.current.addDay(0, 1));
act(() => result.current.setWeekAlias(1, 'Deload'));
// alias nie odłącza tygodnia od lustrzanego tygodnia 1
expect(result.current.weeks[1].customName).toBe('Deload');
expect(result.current.weeks[1].detached).toBe(false);
// alias dłuższy niż 40 znaków jest obcięty
act(() => result.current.setWeekAlias(1, 'a'.repeat(60)));
expect(result.current.weeks[1].customName).toHaveLength(40);
act(() => result.current.copyPrevWeek(1));
// copyPrevWeek kopiuje dni, ale nie alias
expect(result.current.weeks[1].days).toHaveLength(1);
expect(result.current.weeks[1].customName).toBe('a'.repeat(40));
act(() => result.current.setWeekAlias(2, 'Przerwa'));
act(() => result.current.copyPrevWeek(2));
expect(result.current.weeks[2].customName).toBe('Przerwa');
});
it('dirty: start=false, po zmianie=true; initFromPlan resetuje snapshot', () => {
const { result } = renderHook(() => usePlanEditorState());
expect(result.current.dirty).toBe(false);

View File

@@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react';
import { render, screen, waitFor, 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';
@@ -37,7 +37,7 @@ const EXERCISES = [
const TRAINEE_DETAIL = {
user: { id: TRAINEE_ID, firstName: 'Anna', lastName: 'Nowak' },
gyms: [],
gyms: [{ id: 'gym-1', name: 'Siłownia Podopiecznej' }],
activePlan: null,
progress: null,
killstreak: 0,
@@ -193,7 +193,7 @@ function jsonResponse(status: number, body: unknown) {
});
}
function mockApi(opts: { plans?: unknown[] } = {}) {
function mockApi(opts: { plans?: unknown[]; capture?: { createBody?: Record<string, unknown> } } = {}) {
const plans = opts.plans ?? PLANS;
vi.stubGlobal(
'fetch',
@@ -228,7 +228,10 @@ function mockApi(opts: { plans?: unknown[] } = {}) {
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/plans/plan-2`))
return jsonResponse(200, { plan: ACTIVE_DETAIL });
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/plans`)) {
if (method === 'POST') return jsonResponse(201, { plan: { id: 'plan-new' } });
if (method === 'POST') {
if (opts.capture) opts.capture.createBody = JSON.parse(String(init?.body));
return jsonResponse(201, { plan: { id: 'plan-new' } });
}
return jsonResponse(200, { plans });
}
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/exercise-latest`))
@@ -331,14 +334,16 @@ describe('Zakładka „Plany" w panelu podopiecznego', () => {
describe('PlanEditor — tryb podopiecznego', () => {
it('edycja: formularz inicjalizuje się z danych planu po załadowaniu', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}/plans/plan-1/edit`);
expect(
await screen.findByRole('heading', { name: 'Edycja planu podopiecznego' }),
).toBeInTheDocument();
// tytuł i serie wczytane z API (DRAFT_DETAIL: Przysiady 1 seria 10 @ 60)
// tytuł wczytany z API (krok 1); serie (krok 2) po przejściu „Dalej”
expect(await screen.findByDisplayValue('Plan masowy')).toBeInTheDocument();
expect(screen.getByDisplayValue('60')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Dalej' }));
expect(await screen.findByDisplayValue('60')).toBeInTheDocument();
});
it('„Wstecz" przy niezapisanych zmianach pyta o potwierdzenie', async () => {
@@ -363,6 +368,9 @@ describe('PlanEditor — tryb podopiecznego', () => {
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' });
// krok 2 (ćwiczenia) — po tytule i przejściu „Dalej”
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
await user.click(await screen.findByRole('option', { name: /Przysiady/ }));
@@ -392,6 +400,9 @@ describe('PlanEditor — tryb podopiecznego', () => {
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' }),
).toBeInTheDocument();
// krok 2 (ćwiczenia) — po tytule i przejściu „Dalej”
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// dodaj dzień (Poniedziałek — aria-label z pełną nazwą)
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
// dodaj ćwiczenie Przysiady (wyszukiwarka ćwiczeń)
@@ -408,3 +419,66 @@ describe('PlanEditor — tryb podopiecznego', () => {
expect(screen.getByDisplayValue('70')).toBeInTheDocument();
});
});
describe('PlanEditor — wizard 3-etapowy (tryb podopiecznego)', () => {
it('krok 1 blokuje „Dalej” przy pustym tytule', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' });
expect(screen.getByRole('button', { name: 'Dalej' })).toBeDisabled();
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
expect(screen.getByRole('button', { name: 'Dalej' })).toBeEnabled();
});
it('krok 2: select siłowni z członkostw podopiecznego + alias tygodnia; krok 3: podsumowanie i zapis', async () => {
const capture: { createBody?: Record<string, unknown> } = {};
mockApi({ capture });
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' });
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan wizard');
// 1 tydzień — podsumowanie bez lustrzanych tygodni
const weeksField = screen.getByText('Długość (tygodnie)').closest('[data-slot="field"]') as HTMLElement;
await user.selectOptions(within(weeksField).getByRole('combobox'), '1');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// select siłowni: opcja „Bez siłowni” + siłownia podopiecznego
// (Field bez <label for> — selekcja przez kontener pola)
const gymField = screen.getByText('Siłownia').closest('[data-slot="field"]') as HTMLElement;
const gymSelect = within(gymField).getByRole('combobox');
expect(within(gymSelect).getByRole('option', { name: 'Bez siłowni' })).toBeInTheDocument();
expect(within(gymSelect).getByRole('option', { name: 'Siłownia Podopiecznej' })).toBeInTheDocument();
await user.selectOptions(gymSelect, 'gym-1');
// dzień + ćwiczenie + alias tygodnia
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
await user.click(await screen.findByRole('option', { name: /Przysiady/ }));
const aliasField = screen
.getByText('Nazwa tygodnia (opcjonalnie)')
.closest('[data-slot="field"]') as HTMLElement;
await user.type(within(aliasField).getByRole('textbox'), 'Deload');
// krok 3: podsumowanie — alias, siłownia, dni i ćwiczenia
await user.click(screen.getByRole('button', { name: 'Dalej' }));
expect(await screen.findByText('Deload')).toBeInTheDocument();
expect(screen.getByText('Siłownia Podopiecznej')).toBeInTheDocument();
// liczniki w karcie podsumowania (w stopce jest identyczny tekst — zakres = karta)
const summaryCard = screen
.getByText('Łącznie: 1 dzień · 1 ćwiczenie · 1 seria')
.closest('[data-slot="card"]') as HTMLElement;
expect(within(summaryCard).getByText('Pon · 1 dzień · 1 ćwiczenie · 1 seria')).toBeInTheDocument();
// zapis (krok 3) — body z gymId i customName
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
await waitFor(() => expect(capture.createBody).toBeDefined());
expect(capture.createBody).toMatchObject({
title: 'Plan wizard',
gymId: 'gym-1',
weeks: [expect.objectContaining({ index: 0, customName: 'Deload' })],
});
});
});